forked from borschik/borschik
/
freeze.js
422 lines (361 loc) · 11 KB
/
freeze.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
var CRYPTO = require('crypto'),
FS = require('./fs'),
PATH = require('path'),
configs = {
paths: {}
},
config = {
paths: {},
freezePaths: {},
followSymlinks: {}
};
if (!PATH.sep) PATH.sep = process.platform === 'win32'? '\\' : '/';
/**
* Process image.
*
* @param {String} filePath Path to image file to process.
* @returns {String} New path of processed image.
*/
exports.processPath = function(filePath) {
return freeze(realpathSync(filePath));
};
/**
* Code content by SHA1 Base64 algorithm.
*
* @param {String} content Content to code.
* @returns {String} Coded content.
*/
var sha1Base64 = exports.sha1Base64 = function(content) {
var sha1 = CRYPTO.createHash('sha1');
sha1.update(content);
return sha1.digest('base64');
};
/**
* Fix Base64 string to accomplish Borschik needs.
*
* @param {String} base64 String to fix.
* @returns {String} Fixed string.
*/
var fixBase64 = exports.fixBase64 = function(base64) {
return base64
.replace(/\+/g, '-')
.replace(/\//g, '_')
.replace(/=/g, '')
.replace(/^[+-]+/g, '');
};
/**
* Freeze image.
*
* @param {String} filePath Path to the image to freeze.
* @param {String} content Optional content to use.
* @returns {String} Path to the frozen image.
*/
var freeze = exports.freeze = function(filePath, content) {
if (filePath !== realpathSync(filePath)) throw new Error();
var _freezeDir = freezeDir(filePath);
if (_freezeDir) {
if (content === undefined) {
if (!FS.existsSync(filePath)) throw new Error("No such file or directory: " + filePath);
if (FS.statSync(filePath).isDirectory()) throw new Error("Is a directory (file needed): " + filePath);
content = FS.readFileSync(filePath);
}
var hash = fixBase64(sha1Base64(content));
filePath = PATH.join(_freezeDir, hash + PATH.extname(filePath));
if (content && !FS.existsSync(filePath)) {
save(filePath, content);
}
}
return filePath;
};
/**
* Get freeze dir for specific file path.
*
* @param {String} filePath File path to use.
* @returns {String} Freeze dir.
*/
var freezeDir = exports.freezeDir = function(filePath) {
filePath = PATH.normalize(filePath);
if (filePath !== realpathSync(filePath)) throw Error();
var suffix = filePath,
prefix = '',
freezeDir,
rePrefix = new RegExp('^(' + PATH.sep + '*[^' + PATH.sep +']+)', 'g'),
matched;
while (matched = filePath.match(rePrefix)) {
prefix += matched[0];
freezeDir = freezePath(prefix) || freezeDir;
filePath = filePath.replace(rePrefix, '');
}
return freezeDir;
};
/**
* Recursivly freeze all files in path.
* @param {String} input File or directory path
*/
exports.freezeAll = function(input) {
/**
* Result JSON
* @type {Object}
*/
var result = {};
var basePath = PATH.dirname(input);
var stat = FS.statSync(input);
if (stat.isFile()) {
freezeAllProcessFile(input, process.cwd(), result);
} else if (stat.isDirectory()) {
freezeAllProcessDir(input, basePath, result);
}
return result;
};
/**
* Process file: freeze and write meta-data to result JSON
* @param absPath
* @param basePath
* @param {Object} result Result JSON
*/
function freezeAllProcessFile(absPath, basePath, result) {
var url = absPath;
if (freezableRe.test(url) || /\.(?:css|js|swf)$/.test(url)) {
url = freeze(url);
}
var relOriginalPath = PATH.relative(basePath, absPath);
var resolved = resolveUrl2(url);
url = (resolved == url ? PATH.relative(basePath, url) : resolved);
result[relOriginalPath] = url;
}
/**
* Read dir recursivly and process files
* @param dir
* @param basePath
* @param {Object} result Result JSON
*/
function freezeAllProcessDir(dir, basePath, result) {
FS.readdirSync(dir).forEach(function(file) {
file = PATH.resolve(dir, file);
var stat = FS.statSync(file);
if (stat.isFile()) {
freezeAllProcessFile(file, basePath, result);
} else if (stat.isDirectory()) {
freezeAllProcessDir(file, basePath, result);
}
});
}
/**
* Get path from "path" config by path if any.
*
* @param {String} _path Path to search config for.
* @returns {String} Path.
*/
var path = exports.path = function(_path) {
loadConfig(_path);
return config.paths[_path];
};
/**
* Get path from "freeze path" config by path if any.
*
* @param {String} path Path to search config for.
* @returns {String} Path.
*/
var freezePath = exports.freezePath = function(path) {
loadConfig(path);
return config.freezePaths[path];
};
/**
* Get path from "follow symlinks" config by path if any.
*
* @param {String} path Path to search config for.
* @returns {String} Path.
*/
var followSymlinks = exports.followSymlinks = function(path) {
loadConfig(path);
return config.followSymlinks[path];
};
/**
* Load config from path.
*
* @param {String} path Path to load from.
*/
var loadConfig = exports.loadConfig = function(path) {
if (configs.paths[path] !== undefined) return;
var config_path = PATH.join(path, '.borschik');
if (FS.existsSync(config_path)) {
configs.paths[path] = true;
try {
var _config = JSON.parse(FS.readFileSync(config_path));
} catch (e) {
if (e instanceof SyntaxError) {
console.error('Invalid config: ' + config_path);
}
throw e;
}
var paths = _config.paths || _config.pathmap || {};
for (var dir in paths) {
var realpath = realpathSync(PATH.resolve(path, dir));
if (!config.paths[realpath]) {
var value = paths[dir];
if (value) value = value.replace(/\*/g, PATH.sep);
config.paths[realpath] = value;
}
}
var freezePaths = _config.freeze_paths || _config.hashsum_paths || {};
for (var dir in freezePaths) {
var realpath = realpathSync(PATH.resolve(path, dir));
if (!config.freezePaths[realpath]) {
var value = freezePaths[dir];
value = realpathSync(PATH.resolve(PATH.resolve(path, dir), value));
if (value) value = value.replace(/\*/g, PATH.sep);
config.freezePaths[realpath] = value;
}
}
var _followSymlinks = _config.follow_symlinks || {};
for (var dir in _followSymlinks) {
var realpath = realpathSync(PATH.resolve(path, dir));
if (!config.followSymlinks[realpath]) {
config.followSymlinks[realpath] = _followSymlinks[dir];
}
}
} else {
configs.paths[path] = false;
}
};
/**
* Resolve URL.
*
* @param {String} filePath File path to resolve.
* @param {String} base Base to use if any.
* @returns {String} Resolved URL.
*/
var resolveUrl2 = exports.resolveUrl2 = function(filePath, base) {
filePath = realpathSync(filePath);
var suffix = filePath,
prefix = '',
host = '',
hostpath = '',
rePrefix = new RegExp('^(' + PATH.sep + '[^' + PATH.sep + ']+)', 'g'),
matched;
while (matched = suffix.match(rePrefix)) {
prefix += matched[0];
hostpath += matched[0];
var _path = path(prefix);
if (_path !== undefined) {
host = _path;
hostpath = '';
}
suffix = suffix.replace(rePrefix, '');
}
var result;
if (host) {
hostpath = hostpath.replace(new RegExp('^' + PATH.sep + '+'), '');
result = host + hostpath + suffix;
} else {
result = PATH.resolve(base, prefix + suffix);
}
return result;
};
/**
* Make dirs if not exists.
*
* @param {String} path Path to make.
*/
function mkpath(path) {
var dirs = path.split(PATH.sep),
_path = '';
dirs.forEach(function(dir) {
dir = dir || PATH.sep;
if (dir) {
_path = PATH.join(_path, dir);
if (!FS.existsSync(_path)) {
FS.mkdirSync(_path);
}
}
});
}
/**
* Save file and make dirs if needed.
*
* @param {String} filePath File path to save.
* @param {String} content File content to save.
*/
function save(filePath, content) {
mkpath(PATH.dirname(filePath));
FS.writeFileSync(filePath, content);
}
/**
* Expands all symbolic links (if "follow symlinks" config "true") and resolves references.
*
* @param {String} path Path to make real.
* @param {String} base Base to use.
* @returns {String} Real file path.
*/
var realpathSync = exports.realpathSync = function(path, base) {
path = PATH.resolve(base? base : process.cwd(), path);
var folders = path.split(PATH.sep);
for (var i = 0; i < folders.length; ) {
var name = folders[i];
if (name === '') {
i++;
continue;
}
var prefix = subArrayJoin(folders, PATH.sep, 0, i - 1),
_followSymlinks = false;
for (var j = 0; j < i; j++) {
var followSymlinksJ = followSymlinks(subArrayJoin(folders, PATH.sep, 0, j));
if (followSymlinksJ !== undefined) _followSymlinks = followSymlinksJ;
}
if (_followSymlinks && isSymLink(PATH.join(prefix, name))) {
var linkParts = FS.readlinkSync(PATH.join(prefix, name)).split(PATH.sep);
folders = arraySplice(folders, 0, i + 1, linkParts);
} else {
i++;
}
}
return folders.join(PATH.sep);
};
// Freezable test extensions
var freezableExts = (process.env.BORSCHIK_FREEZABLE_EXTS ||
'jpg jpeg gif ico png swf svg ttf eot otf woff').split(' '),
freezableRe = new RegExp('\\.(' + freezableExts.join('|') + ')$');
/**
* Check if URL is freezable.
*
* @param {String} url URL to check.
* @returns {boolean} True if URL is freezable, otherwise false.
*/
exports.isFreezableUrl = function(url) {
return freezableRe.test(url);
};
/**
* Join part of array.
*
* @param {Array} a Array to join.
* @param {String} separator Separator to use in join.
* @param {Number} from Join start index.
* @param {Number} to Join finish index.
* @returns {String} Joined array string.
*/
function subArrayJoin(a, separator, from, to) {
return a.slice(from, to + 1).join(separator);
}
/**
* Splice array replacing it's elements by another array.
*
* @param {Array} a1 Array to splice.
* @param {Number} from Splice start index.
* @param {Number} to Splice finish index.
* @param {Array} a2 Array to inject.
* @returns {Array} New array.
*/
function arraySplice(a1, from, to, a2) {
var aL = a1.slice(0, from),
aR = a1.slice(to);
return aL.concat(a2).concat(aR);
}
/**
* Check if path is the path to symbolic link.
*
* @param {String} path Path to check.
* @returns {boolean} True if it is symbolic link, otherwise false.
*/
function isSymLink(path) {
return FS.existsSync(path) && FS.lstatSync(path).isSymbolicLink();
}