forked from clean-css/clean-css-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
364 lines (304 loc) · 12.1 KB
/
index.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
var fs = require('fs');
var path = require('path');
var CleanCSS = require('clean-css');
var program = require('commander');
var glob = require('glob');
var COMPATIBILITY_PATTERN = /([\w\.]+)=(\w+)/g;
var lineBreak = require('os').EOL;
function cli(process, beforeMinifyCallback) {
var packageConfig = fs.readFileSync(path.join(__dirname, 'package.json'));
var buildVersion = JSON.parse(packageConfig).version;
var fromStdin;
var inputOptions;
var options;
var stdin;
var data;
beforeMinifyCallback = beforeMinifyCallback || Function.prototype;
// Specify commander options to parse command line params correctly
program
.usage('[options] <source-file ...>')
.option('-b, --batch', 'If enabled, optimizes input files one by one instead of joining them together')
.option('-c, --compatibility [ie7|ie8]', 'Force compatibility mode (see Readme for advanced examples)')
.option('-d, --debug', 'Shows debug information (minification time & compression efficiency)')
.option('-f, --format <options>', 'Controls output formatting, see examples below')
.option('-h, --help', 'display this help')
.option('-o, --output [output-file]', 'Use [output-file] as output instead of STDOUT')
.option('-O <n> [optimizations]', 'Turn on level <n> optimizations; optionally accepts a list of fine-grained options, defaults to `1`, see examples below, IMPORTANT: the prefix is O (a capital o letter), NOT a 0 (zero, a number)', function (val) { return Math.abs(parseInt(val)); })
.version(buildVersion, '-v, --version')
.option('--batch-suffix <suffix>', 'A suffix (without extension) appended to input file name when processing in batch mode (`-min` is the default)', '-min')
.option('--inline [rules]', 'Enables inlining for listed sources (defaults to `local`)')
.option('--inline-timeout [seconds]', 'Per connection timeout when fetching remote stylesheets (defaults to 5 seconds)', parseFloat)
.option('--input-source-map [file]', 'Specifies the path of the input source map file')
.option('--remove-inlined-files', 'Remove files inlined in <source-file ...> or via `@import` statements')
.option('--source-map', 'Enables building input\'s source map')
.option('--source-map-inline-sources', 'Enables inlining sources inside source maps')
.option('--with-rebase', 'Enable URLs rebasing');
program.on('--help', function () {
console.log('');
console.log('Examples:\n');
console.log(' %> cleancss one.css');
console.log(' %> cleancss -o one-min.css one.css');
console.log(' %> cleancss -o merged-and-minified.css one.css two.css three.css');
console.log(' %> cleancss one.css two.css three.css | gzip -9 -c > merged-minified-and-gzipped.css.gz');
console.log('');
console.log('Formatting options:');
console.log(' %> cleancss --format beautify one.css');
console.log(' %> cleancss --format keep-breaks one.css');
console.log(' %> cleancss --format \'indentBy:1;indentWith:tab\' one.css');
console.log(' %> cleancss --format \'breaks:afterBlockBegins=on;spaces:aroundSelectorRelation=on\' one.css');
console.log(' %> cleancss --format \'breaks:afterBlockBegins=2;spaces:aroundSelectorRelation=on\' one.css');
console.log('');
console.log('Level 0 optimizations:');
console.log(' %> cleancss -O0 one.css');
console.log('');
console.log('Level 1 optimizations:');
console.log(' %> cleancss -O1 one.css');
console.log(' %> cleancss -O1 removeQuotes:off;roundingPrecision:4;specialComments:1 one.css');
console.log(' %> cleancss -O1 all:off;specialComments:1 one.css');
console.log('');
console.log('Level 2 optimizations:');
console.log(' %> cleancss -O2 one.css');
console.log(' %> cleancss -O2 mergeMedia:off;restructureRules:off;mergeSemantically:on;mergeIntoShorthands:off one.css');
console.log(' %> cleancss -O2 all:off;removeDuplicateRules:on one.css');
process.exit();
});
program.parse(process.argv);
inputOptions = program.opts();
// If no sensible data passed in just print help and exit
if (program.args.length === 0) {
fromStdin = !process.env.__DIRECT__ && !process.stdin.isTTY;
if (!fromStdin) {
program.outputHelp();
return 0;
}
}
// Now coerce arguments into CleanCSS configuration...
options = {
batch: inputOptions.batch,
compatibility: inputOptions.compatibility,
format: inputOptions.format,
inline: typeof inputOptions.inline == 'string' ? inputOptions.inline : 'local',
inlineTimeout: inputOptions.inlineTimeout * 1000,
level: { 1: true },
output: inputOptions.output,
rebase: inputOptions.withRebase ? true : false,
rebaseTo: undefined,
sourceMap: inputOptions.sourceMap,
sourceMapInlineSources: inputOptions.sourceMapInlineSources
};
if (program.rawArgs.indexOf('-O0') > -1) {
options.level[0] = true;
}
if (program.rawArgs.indexOf('-O1') > -1) {
options.level[1] = findArgumentTo('-O1', program.rawArgs, program.args);
}
if (program.rawArgs.indexOf('-O2') > -1) {
options.level[2] = findArgumentTo('-O2', program.rawArgs, program.args);
}
if (inputOptions.inputSourceMap && !options.sourceMap) {
options.sourceMap = true;
}
if (options.sourceMap && !options.output && !options.batch) {
outputFeedback(['Source maps will not be built because you have not specified an output file.'], true);
options.sourceMap = false;
}
if (options.output && options.batch) {
fs.mkdirSync(options.output, {recursive: true});
}
if (inputOptions.withRebase && ('output' in inputOptions) && inputOptions.output.length > 0) {
if (isDirectory(path.resolve(inputOptions.output))) {
options.rebaseTo = path.resolve(inputOptions.output);
} else {
options.rebaseTo = path.dirname(path.resolve(inputOptions.output));
}
} else {
if (inputOptions.withRebase) {
options.rebaseTo = process.cwd();
}
}
var configurations = {
batchSuffix: inputOptions.batchSuffix,
beforeMinifyCallback: beforeMinifyCallback,
debugMode: inputOptions.debug,
removeInlinedFiles: inputOptions.removeInlinedFiles,
inputSourceMap: inputOptions.inputSourceMap
};
// ... and do the magic!
if (program.args.length > 0) {
minify(process, options, configurations, expandGlobs(program.args));
} else {
stdin = process.openStdin();
stdin.setEncoding('utf-8');
data = '';
stdin.on('data', function (chunk) {
data += chunk;
});
stdin.on('end', function () {
minify(process, options, configurations, data);
});
}
}
function isDirectory(path) {
try {
return fs.statSync(path).isDirectory();
} catch (e) {
if (e.code == 'ENOENT') {
return false;
} else {
throw e;
}
}
}
function findArgumentTo(option, rawArgs, args) {
var value = true;
var optionAt = rawArgs.indexOf(option);
var nextOption = rawArgs[optionAt + 1];
var looksLikePath;
var asArgumentAt;
if (!nextOption) {
return value;
}
looksLikePath = nextOption.indexOf('.css') > -1 ||
/\//.test(nextOption) ||
/\\[^\-]/.test(nextOption) ||
/^https?:\/\//.test(nextOption);
asArgumentAt = args.indexOf(nextOption);
if (!looksLikePath) {
value = nextOption;
}
if (!looksLikePath && asArgumentAt > -1) {
args.splice(asArgumentAt, 1);
}
return value;
}
function expandGlobs(paths) {
var globPatterns = paths.filter(function (path) { return path[0] != '!'; });
var ignoredGlobPatterns = paths
.filter(function (path) { return path[0] == '!'; })
.map(function (path) { return path.substring(1); });
return globPatterns.reduce(function (accumulator, path) {
var expandedWithSource =
glob.sync(path, { ignore: ignoredGlobPatterns, nodir: true, nonull: true })
.map(function (expandedPath) { return { expanded: expandedPath, source: path }; });
return accumulator.concat(expandedWithSource);
}, []);
}
function minify(process, options, configurations, data) {
var cleanCss = new CleanCSS(options);
var input = typeof(data) == 'string' ?
data :
data.map(function (o) { return o.expanded; });
applyNonBooleanCompatibilityFlags(cleanCss, options.compatibility);
configurations.beforeMinifyCallback(cleanCss);
cleanCss.minify(input, getSourceMapContent(configurations.inputSourceMap), function (errors, minified) {
var inputPath;
var outputPath;
if (options.batch && !('styles' in minified)) {
for (inputPath in minified) {
outputPath = options.batch && options.output ?
toBatchOutputPath(inputPath, configurations.batchSuffix, options.output, data) :
toSimpleOutputPath(inputPath, configurations.batchSuffix);
processMinified(process, configurations, minified[inputPath], inputPath, outputPath);
}
} else {
processMinified(process, configurations, minified, null, options.output);
}
});
}
function toSimpleOutputPath(inputPath, batchSuffix) {
var extensionName = path.extname(inputPath);
return inputPath.replace(new RegExp(extensionName + '$'), batchSuffix + extensionName);
}
function toBatchOutputPath(inputPath, batchSuffix, output, expandedWithSource) {
var extensionName = path.extname(inputPath);
var inputSource = expandedWithSource.find(function (ic) { return ic.expanded == inputPath; }).source;
var inputSourceRoot = inputSource.indexOf('*') > -1 ?
inputSource.substring(0, inputSource.indexOf('*')) :
path.dirname(inputSource);
return path.join(output, inputPath.replace(inputSourceRoot, '').replace(new RegExp(extensionName + '$'), batchSuffix + extensionName));
}
function processMinified(process, configurations, minified, inputPath, outputPath) {
var mapOutputPath;
if (configurations.debugMode) {
if (inputPath) {
console.error('File: %s', inputPath);
}
console.error('Original: %d bytes', minified.stats.originalSize);
console.error('Minified: %d bytes', minified.stats.minifiedSize);
console.error('Efficiency: %d%', ~~(minified.stats.efficiency * 10000) / 100.0);
console.error('Time spent: %dms', minified.stats.timeSpent);
if (minified.inlinedStylesheets.length > 0) {
console.error('Inlined stylesheets:');
minified.inlinedStylesheets.forEach(function (uri) {
console.error('- %s', uri);
});
}
console.error('');
}
outputFeedback(minified.errors, true);
outputFeedback(minified.warnings);
if (minified.errors.length > 0) {
process.exit(1);
}
if (configurations.removeInlinedFiles) {
minified.inlinedStylesheets.forEach(fs.unlinkSync);
}
if (minified.sourceMap) {
mapOutputPath = outputPath + '.map';
output(process, outputPath, minified.styles + lineBreak + '/*# sourceMappingURL=' + path.basename(mapOutputPath) + ' */');
outputMap(mapOutputPath, minified.sourceMap);
} else {
output(process, outputPath, minified.styles);
}
}
function applyNonBooleanCompatibilityFlags(cleanCss, compatibility) {
var match;
var scope;
var parts;
var i, l;
if (!compatibility) {
return;
}
patternLoop:
while ((match = COMPATIBILITY_PATTERN.exec(compatibility)) !== null) {
scope = cleanCss.options.compatibility;
parts = match[1].split('.');
for (i = 0, l = parts.length - 1; i < l; i++) {
scope = scope[parts[i]];
if (!scope) {
continue patternLoop;
}
}
scope[parts.pop()] = match[2];
}
}
function outputFeedback(messages, isError) {
var prefix = isError ? '\x1B[31mERROR\x1B[39m:' : 'WARNING:';
messages.forEach(function (message) {
console.error('%s %s', prefix, message);
});
}
function getSourceMapContent(sourceMapPath) {
if (!sourceMapPath || !fs.existsSync(sourceMapPath)) {
return null;
}
var content = null;
try {
content = fs.readFileSync(sourceMapPath).toString();
} catch (e) {
console.error('Failed to read the input source map file.');
}
return content;
}
function output(process, outputPath, minified) {
if (outputPath) {
fs.mkdirSync(path.dirname(outputPath), {recursive: true});
fs.writeFileSync(outputPath, minified, 'utf8');
} else {
process.stdout.write(minified);
}
}
function outputMap(mapOutputPath, sourceMap) {
fs.writeFileSync(mapOutputPath, sourceMap.toString(), 'utf-8');
}
module.exports = cli;