/
lessc.js
executable file
·538 lines (495 loc) · 17.7 KB
/
lessc.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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
import * as path from 'path';
import fs from './less-node/fs';
import * as os from 'os';
import * as utils from './less/utils';
import * as Constants from './less/constants';
let errno;
let mkdirp;
try {
errno = require('errno');
} catch (err) {
errno = null;
}
import less from './less-node';
const pluginManager = new less.PluginManager(less);
const fileManager = new less.FileManager();
const plugins = [];
const queuePlugins = [];
let args = process.argv.slice(1);
let silent = false;
let verbose = false;
const options = less.options;
options.plugins = plugins;
options.reUsePluginManager = true;
const sourceMapOptions = {};
let continueProcessing = true;
const checkArgFunc = (arg, option) => {
if (!option) {
console.error(`${arg} option requires a parameter`);
continueProcessing = false;
process.exitCode = 1;
return false;
}
return true;
};
const checkBooleanArg = arg => {
const onOff = /^((on|t|true|y|yes)|(off|f|false|n|no))$/i.exec(arg);
if (!onOff) {
console.error(` unable to parse ${arg} as a boolean. use one of on/t/true/y/yes/off/f/false/n/no`);
continueProcessing = false;
process.exitCode = 1;
return false;
}
return Boolean(onOff[2]);
};
const parseVariableOption = (option, variables) => {
const parts = option.split('=', 2);
variables[parts[0]] = parts[1];
};
let sourceMapFileInline = false;
function printUsage() {
less.lesscHelper.printUsage();
pluginManager.Loader.printUsage(plugins);
continueProcessing = false;
}
function render() {
if (!continueProcessing) {
return;
}
let input = args[1];
if (input && input != '-') {
input = path.resolve(process.cwd(), input);
}
let output = args[2];
const outputbase = args[2];
if (output) {
output = path.resolve(process.cwd(), output);
}
if (options.sourceMap) {
sourceMapOptions.sourceMapInputFilename = input;
if (!sourceMapOptions.sourceMapFullFilename) {
if (!output && !sourceMapFileInline) {
console.error('the sourcemap option only has an optional filename if the css filename is given');
console.error('consider adding --source-map-map-inline which embeds the sourcemap into the css');
process.exitCode = 1;
return;
}
// its in the same directory, so always just the basename
if (output) {
sourceMapOptions.sourceMapOutputFilename = path.basename(output);
sourceMapOptions.sourceMapFullFilename = `${output}.map`;
}
// its in the same directory, so always just the basename
if ('sourceMapFullFilename' in sourceMapOptions) {
sourceMapOptions.sourceMapFilename = path.basename(sourceMapOptions.sourceMapFullFilename);
}
} else if (options.sourceMap && !sourceMapFileInline) {
const mapFilename = path.resolve(process.cwd(), sourceMapOptions.sourceMapFullFilename);
const mapDir = path.dirname(mapFilename);
const outputDir = path.dirname(output);
// find the path from the map to the output file
sourceMapOptions.sourceMapOutputFilename = path.join(
path.relative(mapDir, outputDir), path.basename(output));
// make the sourcemap filename point to the sourcemap relative to the css file output directory
sourceMapOptions.sourceMapFilename = path.join(
path.relative(outputDir, mapDir), path.basename(sourceMapOptions.sourceMapFullFilename));
}
}
if (sourceMapOptions.sourceMapBasepath === undefined) {
sourceMapOptions.sourceMapBasepath = input ? path.dirname(input) : process.cwd();
}
if (sourceMapOptions.sourceMapRootpath === undefined) {
const pathToMap = path.dirname((sourceMapFileInline ? output : sourceMapOptions.sourceMapFullFilename) || '.');
const pathToInput = path.dirname(sourceMapOptions.sourceMapInputFilename || '.');
sourceMapOptions.sourceMapRootpath = path.relative(pathToMap, pathToInput);
}
if (!input) {
console.error('lessc: no input files');
console.error('');
printUsage();
process.exitCode = 1;
return;
}
const ensureDirectory = filepath => {
const dir = path.dirname(filepath);
let cmd;
const existsSync = fs.existsSync || path.existsSync;
if (!existsSync(dir)) {
if (mkdirp === undefined) {
try {mkdirp = require('make-dir');}
catch (e) { mkdirp = null; }
}
cmd = mkdirp && mkdirp.sync || fs.mkdirSync;
cmd(dir);
}
};
if (options.depends) {
if (!outputbase) {
console.error('option --depends requires an output path to be specified');
process.exitCode = 1;
return;
}
process.stdout.write(`${outputbase}: `);
}
if (!sourceMapFileInline) {
var writeSourceMap = (output = '', onDone) => {
const filename = sourceMapOptions.sourceMapFullFilename;
ensureDirectory(filename);
fs.writeFile(filename, output, 'utf8', err => {
if (err) {
let description = 'Error: ';
if (errno && errno.errno[err.errno]) {
description += errno.errno[err.errno].description;
} else {
description += `${err.code} ${err.message}`;
}
console.error(`lessc: failed to create file ${filename}`);
console.error(description);
process.exitCode = 1;
} else {
less.logger.info(`lessc: wrote ${filename}`);
}
onDone();
});
};
}
const writeSourceMapIfNeeded = (output, onDone) => {
if (options.sourceMap && !sourceMapFileInline) {
writeSourceMap(output, onDone);
} else {
onDone();
}
};
const writeOutput = (output, result, onSuccess) => {
if (options.depends) {
onSuccess();
} else if (output) {
ensureDirectory(output);
fs.writeFile(output, result.css, {encoding: 'utf8'}, err => {
if (err) {
let description = 'Error: ';
if (errno && errno.errno[err.errno]) {
description += errno.errno[err.errno].description;
} else {
description += `${err.code} ${err.message}`;
}
console.error(`lessc: failed to create file ${output}`);
console.error(description);
process.exitCode = 1;
} else {
less.logger.info(`lessc: wrote ${output}`);
onSuccess();
}
});
} else if (!options.depends) {
process.stdout.write(result.css);
onSuccess();
}
};
const logDependencies = (options, result) => {
if (options.depends) {
let depends = '';
for (let i = 0; i < result.imports.length; i++) {
depends += `${result.imports[i]} `;
}
console.log(depends);
}
};
const parseLessFile = (e, data) => {
if (e) {
console.error(`lessc: ${e.message}`);
process.exitCode = 1;
return;
}
data = data.replace(/^\uFEFF/, '');
options.paths = [path.dirname(input)].concat(options.paths);
options.filename = input;
if (options.lint) {
options.sourceMap = false;
}
sourceMapOptions.sourceMapFileInline = sourceMapFileInline;
if (options.sourceMap) {
options.sourceMap = sourceMapOptions;
}
less.logger.addListener({
info: function(msg) {
if (verbose) {
console.log(msg);
}
},
warn: function(msg) {
// do not show warning if the silent option is used
if (!silent) {
console.warn(msg);
}
},
error: function(msg) {
console.error(msg);
}
});
less.render(data, options)
.then(result => {
if (!options.lint) {
writeOutput(output, result, () => {
writeSourceMapIfNeeded(result.map, () => {
logDependencies(options, result);
});
});
}
},
err => {
if (!options.silent) {
console.error(err.toString({
stylize: options.color && less.lesscHelper.stylize
}));
}
process.exitCode = 1;
});
};
if (input != '-') {
fs.readFile(input, 'utf8', parseLessFile);
} else {
process.stdin.resume();
process.stdin.setEncoding('utf8');
let buffer = '';
process.stdin.on('data', data => {
buffer += data;
});
process.stdin.on('end', () => {
parseLessFile(false, buffer);
});
}
}
function processPluginQueue() {
let x = 0;
function pluginError(name) {
console.error(`Unable to load plugin ${name} please make sure that it is installed under or at the same level as less`);
process.exitCode = 1;
}
function pluginFinished(plugin) {
x++;
plugins.push(plugin);
if (x === queuePlugins.length) {
render();
}
}
queuePlugins.forEach(queue => {
const context = utils.clone(options);
pluginManager.Loader.loadPlugin(queue.name, process.cwd(), context, less.environment, fileManager)
.then(data => {
pluginFinished({
fileContent: data.contents,
filename: data.filename,
options: queue.options
});
})
.catch(() => {
pluginError(queue.name);
});
});
}
// self executing function so we can return
(() => {
args = args.filter(arg => {
let match;
match = arg.match(/^-I(.+)$/);
if (match) {
options.paths.push(match[1]);
return false;
}
match = arg.match(/^--?([a-z][0-9a-z-]*)(?:=(.*))?$/i);
if (match) {
arg = match[1];
} else {
return arg;
}
switch (arg) {
case 'v':
case 'version':
console.log(`lessc ${less.version.join('.')} (Less Compiler) [JavaScript]`);
continueProcessing = false;
break;
case 'verbose':
verbose = true;
break;
case 's':
case 'silent':
silent = true;
break;
case 'l':
case 'lint':
options.lint = true;
break;
case 'strict-imports':
options.strictImports = true;
break;
case 'h':
case 'help':
printUsage();
break;
case 'x':
case 'compress':
options.compress = true;
break;
case 'insecure':
options.insecure = true;
break;
case 'M':
case 'depends':
options.depends = true;
break;
case 'max-line-len':
if (checkArgFunc(arg, match[2])) {
options.maxLineLen = parseInt(match[2], 10);
if (options.maxLineLen <= 0) {
options.maxLineLen = -1;
}
}
break;
case 'no-color':
options.color = false;
break;
case 'js':
options.javascriptEnabled = true;
break;
case 'no-js':
console.error('The "--no-js" argument is deprecated, as inline JavaScript ' +
'is disabled by default. Use "--js" to enable inline JavaScript (not recommended).');
break;
case 'include-path':
if (checkArgFunc(arg, match[2])) {
// ; supported on windows.
// : supported on windows and linux, excluding a drive letter like C:\ so C:\file:D:\file parses to 2
options.paths = match[2]
.split(os.type().match(/Windows/) ? /:(?!\\)|;/ : ':')
.map(p => {
if (p) {
return path.resolve(process.cwd(), p);
}
});
}
break;
case 'line-numbers':
if (checkArgFunc(arg, match[2])) {
options.dumpLineNumbers = match[2];
}
break;
case 'source-map':
options.sourceMap = true;
if (match[2]) {
sourceMapOptions.sourceMapFullFilename = match[2];
}
break;
case 'source-map-rootpath':
if (checkArgFunc(arg, match[2])) {
sourceMapOptions.sourceMapRootpath = match[2];
}
break;
case 'source-map-basepath':
if (checkArgFunc(arg, match[2])) {
sourceMapOptions.sourceMapBasepath = match[2];
}
break;
case 'source-map-inline':
case 'source-map-map-inline':
sourceMapFileInline = true;
options.sourceMap = true;
break;
case 'source-map-include-source':
case 'source-map-less-inline':
sourceMapOptions.outputSourceFiles = true;
break;
case 'source-map-url':
if (checkArgFunc(arg, match[2])) {
sourceMapOptions.sourceMapURL = match[2];
}
break;
case 'rp':
case 'rootpath':
if (checkArgFunc(arg, match[2])) {
options.rootpath = match[2].replace(/\\/g, '/');
}
break;
case 'relative-urls':
console.warn('The --relative-urls option has been deprecated. Use --rewrite-urls=all.');
options.rewriteUrls = Constants.RewriteUrls.ALL;
break;
case 'ru':
case 'rewrite-urls':
const m = match[2];
if (m) {
if (m === 'local') {
options.rewriteUrls = Constants.RewriteUrls.LOCAL;
} else if (m === 'off') {
options.rewriteUrls = Constants.RewriteUrls.OFF;
} else if (m === 'all') {
options.rewriteUrls = Constants.RewriteUrls.ALL;
} else {
console.error(`Unknown rewrite-urls argument ${m}`);
continueProcessing = false;
process.exitCode = 1;
}
} else {
options.rewriteUrls = Constants.RewriteUrls.ALL;
}
break;
case 'sm':
case 'strict-math':
console.warn('The --strict-math option has been deprecated. Use --math=strict.');
if (checkArgFunc(arg, match[2])) {
if (checkBooleanArg(match[2])) {
options.math = Constants.Math.STRICT_LEGACY;
}
}
break;
case 'm':
case 'math':
if (checkArgFunc(arg, match[2])) {
options.math = match[2];
}
break;
case 'su':
case 'strict-units':
if (checkArgFunc(arg, match[2])) {
options.strictUnits = checkBooleanArg(match[2]);
}
break;
case 'global-var':
if (checkArgFunc(arg, match[2])) {
if (!options.globalVars) {
options.globalVars = {};
}
parseVariableOption(match[2], options.globalVars);
}
break;
case 'modify-var':
if (checkArgFunc(arg, match[2])) {
if (!options.modifyVars) {
options.modifyVars = {};
}
parseVariableOption(match[2], options.modifyVars);
}
break;
case 'url-args':
if (checkArgFunc(arg, match[2])) {
options.urlArgs = match[2];
}
break;
case 'plugin':
const splitupArg = match[2].match(/^([^=]+)(=(.*))?/);
const name = splitupArg[1];
const pluginOptions = splitupArg[3];
queuePlugins.push({ name, options: pluginOptions });
break;
default:
queuePlugins.push({ name: arg, options: match[2], default: true });
break;
}
});
if (queuePlugins.length > 0) {
processPluginQueue();
}
else {
render();
}
})();