/
option-manager.js
575 lines (493 loc) 路 13.8 KB
/
option-manager.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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
// @flow
import * as context from "../index";
import Plugin from "./plugin";
import defaults from "lodash/defaults";
import merge from "lodash/merge";
import removed from "./removed";
import buildConfigChain from "./build-config-chain";
import path from "path";
import traverse from "babel-traverse";
import clone from "lodash/clone";
import { makeWeakCache } from "./caching";
import { getEnv } from "./helpers/environment";
import {
loadPlugin,
loadPreset,
loadParser,
loadGenerator,
} from "./loading/files";
type MergeOptions = {
+type: "arguments" | "options" | "preset",
options: {},
alias: string,
loc: string,
dirname: string,
};
const optionNames = new Set([
"relative",
"filename",
"filenameRelative",
"inputSourceMap",
"env",
"mode",
"retainLines",
"highlightCode",
"suppressDeprecationMessages",
"presets",
"plugins",
"ignore",
"only",
"code",
"ast",
"extends",
"comments",
"shouldPrintComment",
"wrapPluginVisitorMethod",
"compact",
"minified",
"sourceMaps",
"sourceMapTarget",
"sourceFileName",
"sourceRoot",
"babelrc",
"sourceType",
"auxiliaryCommentBefore",
"auxiliaryCommentAfter",
"getModuleId",
"moduleRoot",
"moduleIds",
"moduleId",
"passPerPreset",
// Deprecate top level parserOpts
"parserOpts",
// Deprecate top level generatorOpts
"generatorOpts",
]);
const ALLOWED_PLUGIN_KEYS = new Set([
"name",
"manipulateOptions",
"pre",
"post",
"visitor",
"inherits",
]);
export default function manageOptions(opts: {}): {
options: Object,
passes: Array<Array<Plugin>>,
} | null {
return new OptionManager().init(opts);
}
class OptionManager {
constructor() {
this.options = createInitialOptions();
this.passes = [[]];
}
options: Object;
passes: Array<Array<Plugin>>;
/**
* This is called when we want to merge the input `opts` into the
* base options.
*
* - `alias` is used to output pretty traces back to the original source.
* - `loc` is used to point to the original config.
* - `dirname` is used to resolve plugins relative to it.
*/
mergeOptions(config: MergeOptions, pass?: Array<Plugin>) {
const result = loadConfig(config);
const plugins = result.plugins.map(descriptor =>
loadPluginDescriptor(descriptor),
);
const presets = result.presets.map(descriptor =>
loadPresetDescriptor(descriptor),
);
if (
config.options.passPerPreset != null &&
typeof config.options.passPerPreset !== "boolean"
) {
throw new Error(".passPerPreset must be a boolean or undefined");
}
const passPerPreset = config.options.passPerPreset;
pass = pass || this.passes[0];
// resolve presets
if (presets.length > 0) {
let presetPasses = null;
if (passPerPreset) {
presetPasses = presets.map(() => []);
// The passes are created in the same order as the preset list, but are inserted before any
// existing additional passes.
this.passes.splice(1, 0, ...presetPasses);
}
presets.forEach((presetConfig, i) => {
this.mergeOptions(presetConfig, presetPasses ? presetPasses[i] : pass);
});
}
// resolve plugins
if (plugins.length > 0) {
pass.unshift(...plugins);
}
merge(this.options, result.options);
}
init(opts: {}) {
const configChain = buildConfigChain(opts);
if (!configChain) return null;
try {
for (const config of configChain) {
this.mergeOptions(config);
}
} catch (e) {
// There are a few case where thrown errors will try to annotate themselves multiple times, so
// to keep things simple we just bail out if re-wrapping the message.
if (!/^\[BABEL\]/.test(e.message)) {
const filename =
typeof opts.filename === "string" ? opts.filename : null;
e.message = `[BABEL] ${filename || "unknown"}: ${e.message}`;
}
throw e;
}
opts = this.options;
// Tack the passes onto the object itself so that, if this object is passed back to Babel a second time,
// it will be in the right structure to not change behavior.
opts.plugins = this.passes[0];
opts.presets = this.passes
.slice(1)
.filter(plugins => plugins.length > 0)
.map(plugins => ({ plugins }));
if (opts.inputSourceMap) {
opts.sourceMaps = true;
}
if (opts.moduleId) {
opts.moduleIds = true;
}
defaults(opts, {
moduleRoot: opts.sourceRoot,
});
defaults(opts, {
sourceRoot: opts.moduleRoot,
});
defaults(opts, {
filenameRelative: opts.filename,
});
const basenameRelative = path.basename(opts.filenameRelative);
if (path.extname(opts.filenameRelative) === ".mjs") {
opts.sourceType = "module";
}
defaults(opts, {
sourceFileName: basenameRelative,
sourceMapTarget: basenameRelative,
});
return {
options: opts,
passes: this.passes,
};
}
}
type BasicDescriptor = {
value: {} | Function,
options: ?{},
dirname: string,
alias: string,
loc: string,
};
/**
* Load and validate the given config into a set of options, plugins, and presets.
*/
const loadConfig = makeWeakCache((config): {
options: {},
plugins: Array<BasicDescriptor>,
presets: Array<BasicDescriptor>,
} => {
const options = normalizeOptions(config);
if (
config.options.plugins != null &&
!Array.isArray(config.options.plugins)
) {
throw new Error(".plugins should be an array, null, or undefined");
}
const plugins = (config.options.plugins || []).map((plugin, index) => {
const { filepath, value, options } = normalizePair(
plugin,
loadPlugin,
config.dirname,
);
return {
alias: filepath || `${config.loc}$${index}`,
loc: filepath || config.loc,
value,
options,
dirname: config.dirname,
};
});
if (
config.options.presets != null &&
!Array.isArray(config.options.presets)
) {
throw new Error(".presets should be an array, null, or undefined");
}
const presets = (config.options.presets || []).map((preset, index) => {
const { filepath, value, options } = normalizePair(
preset,
loadPreset,
config.dirname,
);
return {
alias: filepath || `${config.loc}$${index}`,
loc: filepath || config.loc,
value,
options,
dirname: config.dirname,
};
});
return { options, plugins, presets };
});
/**
* Load a generic plugin/preset from the given descriptor loaded from the config object.
*/
const loadDescriptor = makeWeakCache((descriptor, cache) => {
if (typeof descriptor.value !== "function") {
return { value: descriptor.value, descriptor };
}
const { value, options } = descriptor;
const api = Object.assign(Object.create(context), {
cache,
env: () => cache.using(() => getEnv()),
});
let item;
try {
item = value(api, options, { dirname: descriptor.dirname });
} catch (e) {
if (descriptor.alias) {
e.message += ` (While processing: ${JSON.stringify(descriptor.alias)})`;
}
throw e;
}
if (!item || typeof item !== "object") {
throw new Error("Plugin/Preset did not return an object.");
}
return { value: item, descriptor };
});
/**
* Instantiate a plugin for the given descriptor, returning the plugin/options pair.
*/
function loadPluginDescriptor(descriptor: BasicDescriptor) {
if (descriptor.value instanceof Plugin) {
if (descriptor.options) {
throw new Error(
"Passed options to an existing Plugin instance will not work.",
);
}
return descriptor.value;
}
return instantiatePlugin(loadDescriptor(descriptor));
}
const instantiatePlugin = makeWeakCache(
({ value: pluginObj, descriptor }, cache) => {
Object.keys(pluginObj).forEach(key => {
if (!ALLOWED_PLUGIN_KEYS.has(key)) {
throw new Error(
`Plugin ${descriptor.alias} provided an invalid property of ${key}`,
);
}
});
if (
pluginObj.visitor &&
(pluginObj.visitor.enter || pluginObj.visitor.exit)
) {
throw new Error(
"Plugins aren't allowed to specify catch-all enter/exit handlers. " +
"Please target individual nodes.",
);
}
const plugin = Object.assign({}, pluginObj, {
visitor: clone(pluginObj.visitor || {}),
});
traverse.explode(plugin.visitor);
let inheritsDescriptor;
let inherits;
if (plugin.inherits) {
inheritsDescriptor = {
alias: `${descriptor.loc}$inherits`,
loc: descriptor.loc,
value: plugin.inherits,
options: descriptor.options,
dirname: descriptor.dirname,
};
// If the inherited plugin changes, reinstantiate this plugin.
inherits = cache.invalidate(() =>
loadPluginDescriptor(inheritsDescriptor),
);
plugin.pre = chain(inherits.pre, plugin.pre);
plugin.post = chain(inherits.post, plugin.post);
plugin.manipulateOptions = chain(
inherits.manipulateOptions,
plugin.manipulateOptions,
);
plugin.visitor = traverse.visitors.merge([
inherits.visitor,
plugin.visitor,
]);
}
return new Plugin(plugin, descriptor.options, descriptor.alias);
},
);
/**
* Generate a config object that will act as the root of a new nested config.
*/
const loadPresetDescriptor = (descriptor: BasicDescriptor): MergeOptions => {
return instantiatePreset(loadDescriptor(descriptor));
};
const instantiatePreset = makeWeakCache(({ value, descriptor }) => {
return {
type: "preset",
options: value,
alias: descriptor.alias,
loc: descriptor.loc,
dirname: descriptor.dirname,
};
});
/**
* Validate and return the options object for the config.
*/
function normalizeOptions(config) {
const alias = config.alias || "foreign";
const type = config.type;
//
if (typeof config.options !== "object" || Array.isArray(config.options)) {
throw new TypeError(`Invalid options type for ${alias}`);
}
//
const options = Object.assign({}, config.options);
if (type !== "arguments") {
if (options.filename !== undefined) {
throw new Error(`${alias}.filename is only allowed as a root argument`);
}
if (options.babelrc !== undefined) {
throw new Error(`${alias}.babelrc is only allowed as a root argument`);
}
}
if (type === "preset") {
if (options.only !== undefined) {
throw new Error(`${alias}.only is not supported in a preset`);
}
if (options.ignore !== undefined) {
throw new Error(`${alias}.ignore is not supported in a preset`);
}
if (options.extends !== undefined) {
throw new Error(`${alias}.extends is not supported in a preset`);
}
if (options.env !== undefined) {
throw new Error(`${alias}.env is not supported in a preset`);
}
}
if (options.sourceMap !== undefined) {
if (options.sourceMaps !== undefined) {
throw new Error(`Both ${alias}.sourceMap and .sourceMaps have been set`);
}
options.sourceMaps = options.sourceMap;
delete options.sourceMap;
}
for (const key in options) {
// check for an unknown option
if (!optionNames.has(key)) {
if (removed[key]) {
const { message, version = 5 } = removed[key];
throw new ReferenceError(
`Using removed Babel ${version} option: ${alias}.${key} - ${message}`,
);
} else {
// eslint-disable-next-line max-len
const unknownOptErr = `Unknown option: ${alias}.${key}. Check out http://babeljs.io/docs/usage/options/ for more information about options.`;
throw new ReferenceError(unknownOptErr);
}
}
}
if (options.parserOpts && typeof options.parserOpts.parser === "string") {
options.parserOpts = Object.assign({}, options.parserOpts);
options.parserOpts.parser = loadParser(
options.parserOpts.parser,
config.dirname,
).value;
}
if (
options.generatorOpts &&
typeof options.generatorOpts.generator === "string"
) {
options.generatorOpts = Object.assign({}, options.generatorOpts);
options.generatorOpts.generator = loadGenerator(
options.generatorOpts.generator,
config.dirname,
).value;
}
delete options.passPerPreset;
delete options.plugins;
delete options.presets;
return options;
}
/**
* Given a plugin/preset item, resolve it into a standard format.
*/
function normalizePair(
pair: mixed,
resolver,
dirname,
): {
filepath: string | null,
value: {} | Function,
options: ?{},
} {
let options;
let value = pair;
if (Array.isArray(pair)) {
if (pair.length > 2) {
throw new Error(
`Unexpected extra options ${JSON.stringify(pair.slice(2))}.`,
);
}
[value, options] = pair;
}
let filepath = null;
if (typeof value === "string") {
({ filepath, value } = resolver(value, dirname));
}
if (!value) {
throw new Error(`Unexpected falsy value: ${String(value)}`);
}
if (typeof value === "object" && value.__esModule) {
if (value.default) {
value = value.default;
} else {
throw new Error("Must export a default export when using ES6 modules.");
}
}
if (typeof value !== "object" && typeof value !== "function") {
throw new Error(
`Unsupported format: ${typeof value}. Expected an object or a function.`,
);
}
if (options != null && typeof options !== "object") {
throw new Error(
"Plugin/Preset options must be an object, null, or undefined",
);
}
return { filepath, value, options };
}
function chain(a, b) {
const fns = [a, b].filter(Boolean);
if (fns.length <= 1) return fns[0];
return function(...args) {
for (const fn of fns) {
fn.apply(this, args);
}
};
}
function createInitialOptions() {
return {
sourceType: "module",
babelrc: true,
filename: "unknown",
code: true,
ast: true,
comments: true,
compact: "auto",
highlightCode: true,
};
}