This repository was archived by the owner on Mar 7, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbabel.js
557 lines (445 loc) · 11.3 KB
/
babel.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
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
#!/usr/bin/env node
/*
* Copyright (c) 2016 Kelvin W Sherlock <[email protected]>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
"use strict";
/*
* babel [options] files...
* like babel cli, but you can actually use it.
*
*/
var babel = require('babel-core');
var fs = require("fs");
const EX = require('sysexits');
var getopt_long = require('./getopt').getopt_long;
var getsubopt = require('./getsubopt');
var data = require('./data');
function _(x) {
return Array.isArray(x) ? x : [x];
}
/* delete and re-insert a key in a map so it shuffles to the end */
function move_back(map, key) {
if (map.has(key)) {
let tmp = map.get(key);
map.delete(key);
map.set(key, tmp);
}
}
function transform(code, options) {
var ex;
try {
return babel.transform(code, options);
}
catch(ex) {
console.warn(ex.message);
if (ex.codeFrame)
console.warn(ex.codeFrame);
process.exit(EX.DATAERR);
}
}
function transformFile(file, options) {
var ex;
try {
return babel.transformFileSync(file, options);
}
catch(ex) {
console.warn(ex.message);
if (ex.code === 'ENOENT')
process.exit(EX.NOINPUT);
if (ex.codeFrame)
console.warn(ex.codeFrame);
process.exit(EX.DATAERR);
}
}
function read_stdin() {
return new Promise(function(resolve, reject){
var rv = '';
var stdin = process.stdin;
stdin.setEncoding("utf8");
stdin.on("data", function (chunk) {
rv += chunk;
});
stdin.on("end", function () {
resolve(rv);
});
})
}
function coerce_type(v, t) {
if (t == Array) return v.split((/\s*;\s*/)).filter( (x) => x.length > 0);
if (t == Boolean) {
switch(v) {
case undefined: // 'tdz' => key=tdz, value=undefined ... so treat as true.
case null:
case "true":
return true;
case "false":
case "":
case "0":
return false;
case true:
case false:
return v;
default:
var x = Number.parseInt(v,10);
if (Number.isNaN(x)) return false;
return x != 0;
}
}
if (t == Number) {
if (v.match(/^0x/)) return Number.parseInt(v, 16);
return Number.parseInt(v, 10);
}
return v;
}
function coerce_types(data, keys) {
var lookup = function(o,k) {
return Object.prototype.hasOwnProperty.call(o, k) ? o[k] : void(0);
};
var rv = {};
Object.keys(data).forEach((k) => {
var v = data[k];
var type = lookup(keys, k);
rv[k] = coerce_type(v, type);
});
return rv;
}
/* move unknown options into a child object. */
function splatify(data, keys) {
var splat = {};
var rv = {};
var lookup = function(o,k) {
return Object.prototype.hasOwnProperty.call(o, k) ? o[k] : void(0);
};
// find the splat object in keys
Object.keys(keys).forEach( (k) => {
if (keys[k] === Object) rv[k] = splat;
});
Object.keys(data).forEach((k) => {
var v = data[k];
var type = lookup(keys, k);
switch(type) {
case Object: // same name as the splat key.
case undefined:
splat[k] = v;
break;
default:
rv[k] = coerce_type(v, type);
break;
}
});
return rv;
}
function version() {
var pkg = require('./package.json');
console.log(`better-babel-cli version ${pkg.version}`);
}
function help_presets(verbose) {
console.log("Presets:");
var x = [];
data.presets.forEach(function(v,k) { x.push(k); });
x.sort();
x.forEach(function(k){
console.log(` --${k}`);
if (verbose) {
var y = data.presets.get(k).map(function(k){
return Array.isArray(k) ? k[0] : k;
});
y.sort();
y.forEach(function(k){
console.log(` ${k}`);
});
console.log("");
}
});
}
function help_plugins() {
console.log("Plugins:");
var x = [];
data.plugins.forEach(function(k) { x.push(k); });
x.sort();
x.forEach(function(k){console.log(` --${k}`); });
}
function config_str(o) {
return Object.keys(o).map(function(k){
return `${k}=${o[k].name}`;
}).join(',');
}
function help_config() {
console.log("Configuration:");
data.config.forEach(function(v, k) {
console.log(`--${k} ${config_str(v)}`);
});
}
function help(exitcode) {
console.log("babel [options] infile...");
console.log("");
console.log("Options:");
console.log(" -o [outfile] Write output to file.");
console.log(" -h, --help Display usage information.");
console.log(" --help-presets Display presets.");
console.log(" --help-plugins Display plugins.");
console.log(" --help-config Display plugin configuration.");
console.log(" -v, --[no-]verbose Enable/Disable verbose mode.");
console.log(" -V, --version Display version information.");
console.log(" --[no-]babelrc Enable/Disable .babelrc.");
console.log(" --[no-]comments Enable/Disable comments.");
console.log(" --[no-]compact Enable/Disable compaction.");
console.log(" --loose Enable loose mode.");
console.log(" --spec Enable spec mode.");
console.log(" --tdz Enable tdz mode.");
console.log(" --preset [name] Enable specified preset.");
console.log(" --[no-]plugin [plugin] Enable/Disable specified plugin.");
/*
console.log("");
help_presets();
console.log("");
help_plugins();
*/
process.exit(exitcode);
}
var nono = new Map();
var plugins = new Map();
var verbose = false;
var outfile = null;
var ex;
var loose = false;
var spec = false;
var tdz = false;
var babelrc = {
babelrc: false,
plugins: []
};
var go = [ "help", "help-plugins", "help-presets", "help-config",
"verbose!", "version", "babelrc!", "comments!", "compact!", "loose!", "spec!", "tdz!"];
// add pre-sets
data.presets.forEach(function(v, k){
go.push(k);
});
// add plug-ins.
data.plugins.forEach(function(k){
var m;
go.push(`${k}:s`);
go.push(`no-${k}`);
nono.set(`no-${k}`, k);
// --transform-this-that == --this-that
if (m = k.match(/^transform-(.+)$/)) {
var k2 = m[1];
go.push(`${k2}:s`);
go.push(`no-${k2}`);
nono.set(`no-${k2}`, k);
}
});
var argv = getopt_long(process.argv.slice(2), "hVvo:", go,
function(key, optarg) {
switch(key) {
case ':':
case '?':
// optarg is an Error object.
console.warn(optarg.message);
process.exit(EX.USAGE);
break;
case 'h':
case 'help':
help(EX.OK);
case 'help-plugins':
help_plugins();
process.exit(EX.OK);
case 'help-presets':
help_presets(true);
process.exit(EX.OK);
case "help-config":
help_config();
process.exit(EX.OK);
case 'V':
case 'version':
version();
process.exit(EX.OK);
case 'v':
verbose = true;
break;
case 'verbose':
verbose = optarg;
break;
case 'babelrc':
babelrc.babelrc = optarg;
break;
case 'comments':
babelrc.comments = optarg;
break;
case 'compact':
babelrc.compact = optarg;
break;
case 'loose':
loose = optarg;
break;
case 'spec':
spec = optarg;
break;
case 'tdz':
tdz = optarg;
break;
case 'o':
if (optarg === '-') optarg = null;
outfile = optarg;
break;
default:
// --preset ?
var x = key;
if (data.presets.has(x)) {
data.presets.get(x).forEach(function(k){
if (Array.isArray(k)) {
plugins.set(k[0], k[1]);
} else {
plugins.set(k, {});
}
});
break;
}
// --no plugin?
if (nono.has(x)) {
plugins.delete(nono.get(x));
break;
}
// --plugin?
if (data.plugins.has(x)) {
plugins.set(x, optarg ? getsubopt(optarg) : {});
break;
}
x = 'transform-' + key;
if (data.plugins.has(x)) {
plugins.set(x, optarg ? getsubopt(optarg) : {});
break;
}
console.warn(`Unknown plugin/preset: ${key}`);
process.exit(EX.USAGE);
break;
}
});
/*
* NOTE: Order of Plugins Matters!
*
* If you are including your plugins manually and using transform-class-properties,
* make sure that transform-decorators[-legacy] comes before transform-class-properties.
*/
/* turns out the above advice is backwards.... */
// should also check for conflicts, eg, react / vue / inferno.
if (plugins.has('transform-class-properties')) {
move_back(plugins, 'transform-decorators');
move_back(plugins, 'transform-decorators-legacy');
// transform-class-properties should come before transform-es2015-classes
move_back(plugins, 'transform-es2015-classes');
}
// special handling for config options that go into a child object
plugins.forEach(function(value,key,map){
var config = data.config.get(key);
switch(key) {
case 'transform-es2015-modules-umd':
case 'minify-mangle-names':
value = splatify(value, config);
map.set(key, value);
break;
case 'minify-replace':
// todo -- overly complicated structure...
break;
default:
value = coerce_types(value, config);
map.set(key, value);
break;
}
});
if (loose) {
plugins.forEach(function(value, key, map){
var x = data.config.get(key);
if (x && x.loose === Boolean) value.loose = true;
});
}
if (spec) {
plugins.forEach(function(value, key, map){
var x = data.config.get(key);
if (x && x.spec === Boolean) value.spec = true;
});
}
if (tdz) {
plugins.forEach(function(value, key, map){
var x = data.config.get(key);
if (x && x.tdz === Boolean) value.tdz = true;
});
}
plugins.forEach(function(value,key,map){
if (verbose) console.warn(`requiring ${key}`);
var x, y, ex;
try {
x = `./babel-plugin/${key}.js`;
y = require(x);
y = y.__esModule ? y.default : y;
babelrc.plugins.push([y, value]);
return;
} catch(ex) {}
try {
x = `babel-plugin-${key}`;
y = require(x);
y = y.__esModule ? y.default : y;
babelrc.plugins.push([y, value]);
return;
} catch(ex) {
console.warn(`Unable to load plugin ${key}`);
console.warn(ex.message);
}
});
var fd = -1;
if (outfile) {
try {
fd = fs.openSync(outfile, 'w', 0o666);
} catch(ex) {
console.warn(ex.message);
process.exit(EX.CANTCREAT);
}
}
if (argv.length) {
argv.forEach(function(infile){
babelrc.filename = infile;
if (verbose) console.warn(`transforming ${infile}`);
var result = transformFile(infile, babelrc);
if (outfile) {
fs.appendFileSync(fd, result.code);
fs.appendFileSync(fd, "\n");
}
else {
process.stdout.write(result.code);
process.stdout.write("\n");
}
});
if (fd != -1) fs.closeSync(fd);
process.exit(EX.OK);
}
// read from stdin....
if (verbose) console.warn(`transforming stdin`);
read_stdin().then(function(code){
babelrc.filename="<stdin>";
var result = transform(code, babelrc);
if (outfile) {
fs.appendFileSync(fd, result.code);
fs.appendFileSync(fd, "\n");
fs.closeSync(fd);
}
else {
process.stdout.write(result.code);
process.stdout.write("\n");
}
process.exit(EX.OK);
}).catch((ex) => {
console.warn(ex.message);
process.exit(EX.DATAERR);
});