forked from babel/babel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
option-manager.js
350 lines (293 loc) · 10.2 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
import * as context from "../../../api/node";
import type Logger from "../logger";
import Plugin from "../../plugin";
import * as messages from "babel-messages";
import { normaliseOptions } from "./index";
import resolvePlugin from "../../../helpers/resolve-plugin";
import resolvePreset from "../../../helpers/resolve-preset";
import cloneDeepWith from "lodash/cloneDeepWith";
import clone from "lodash/clone";
import merge from "../../../helpers/merge";
import config from "./config";
import removed from "./removed";
import buildConfigChain from "./build-config-chain";
import path from "path";
type PluginObject = {
pre?: Function;
post?: Function;
manipulateOptions?: Function;
visitor: ?{
[key: string]: Function | {
enter?: Function | Array<Function>;
exit?: Function | Array<Function>;
}
};
};
type MergeOptions = {
options?: Object,
extending?: Object,
alias: string,
loc?: string,
dirname?: string
};
export default class OptionManager {
constructor(log?: Logger) {
this.resolvedConfigs = [];
this.options = OptionManager.createBareOptions();
this.log = log;
}
resolvedConfigs: Array<string>;
options: Object;
log: ?Logger;
static memoisedPlugins: Array<{
container: Function;
plugin: Plugin;
}>;
static memoisePluginContainer(fn, loc, i, alias) {
for (const cache of (OptionManager.memoisedPlugins: Array<Object>)) {
if (cache.container === fn) return cache.plugin;
}
let obj: ?PluginObject;
if (typeof fn === "function") {
obj = fn(context);
} else {
obj = fn;
}
if (typeof obj === "object") {
const plugin = new Plugin(obj, alias);
OptionManager.memoisedPlugins.push({
container: fn,
plugin: plugin
});
return plugin;
} else {
throw new TypeError(messages.get("pluginNotObject", loc, i, typeof obj) + loc + i);
}
}
static createBareOptions() {
const opts = {};
for (const key in config) {
const opt = config[key];
opts[key] = clone(opt.default);
}
return opts;
}
static normalisePlugin(plugin, loc, i, alias) {
plugin = plugin.__esModule ? plugin.default : plugin;
if (!(plugin instanceof Plugin)) {
// allow plugin containers to be specified so they don't have to manually require
if (typeof plugin === "function" || typeof plugin === "object") {
plugin = OptionManager.memoisePluginContainer(plugin, loc, i, alias);
} else {
throw new TypeError(messages.get("pluginNotFunction", loc, i, typeof plugin));
}
}
plugin.init(loc, i);
return plugin;
}
static normalisePlugins(loc, dirname, plugins) {
return plugins.map(function (val, i) {
let plugin, options;
if (!val) {
throw new TypeError("Falsy value found in plugins");
}
// destructure plugins
if (Array.isArray(val)) {
[plugin, options] = val;
} else {
plugin = val;
}
const alias = typeof plugin === "string" ? plugin : `${loc}$${i}`;
// allow plugins to be specified as strings
if (typeof plugin === "string") {
const pluginLoc = resolvePlugin(plugin, dirname);
if (pluginLoc) {
plugin = require(pluginLoc);
} else {
throw new ReferenceError(messages.get("pluginUnknown", plugin, loc, i, dirname));
}
}
plugin = OptionManager.normalisePlugin(plugin, loc, i, alias);
return [plugin, options];
});
}
/**
* This is called when we want to merge the input `opts` into the
* base options (passed as the `extendingOpts`: at top-level it's the
* main options, at presets level it's presets 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({
options: rawOpts,
extending: extendingOpts,
alias,
loc,
dirname
}: MergeOptions) {
alias = alias || "foreign";
if (!rawOpts) return;
//
if (typeof rawOpts !== "object" || Array.isArray(rawOpts)) {
this.log.error(`Invalid options type for ${alias}`, TypeError);
}
//
const opts = cloneDeepWith(rawOpts, (val) => {
if (val instanceof Plugin) {
return val;
}
});
//
dirname = dirname || process.cwd();
loc = loc || alias;
for (const key in opts) {
const option = config[key];
// check for an unknown option
if (!option && this.log) {
if (removed[key]) {
this.log.error(`Using removed Babel 5 option: ${alias}.${key} - ${removed[key].message}`,
ReferenceError);
} else {
/* eslint-disable max-len */
const unknownOptErr = `Unknown option: ${alias}.${key}. Check out http://babeljs.io/docs/usage/options/ for more information about options.`;
const presetConfigErr = "A common cause of this error is the presence of a configuration options object without the corresponding preset name. Example:\n\nInvalid:\n `{ presets: [{option: value}] }`\nValid:\n `{ presets: [['presetName', {option: value}]] }`\n\nFor more detailed information on preset configuration, please see http://babeljs.io/docs/plugins/#pluginpresets-options.";
/* eslint-enable max-len */
this.log.error(`${unknownOptErr}\n\n${presetConfigErr}`, ReferenceError);
}
}
}
// normalise options
normaliseOptions(opts);
// resolve plugins
if (opts.plugins) {
opts.plugins = OptionManager.normalisePlugins(loc, dirname, opts.plugins);
}
// resolve presets
if (opts.presets) {
// If we're in the "pass per preset" mode, we resolve the presets
// and keep them for further execution to calculate the options.
if (opts.passPerPreset) {
opts.presets = this.resolvePresets(opts.presets, dirname, (preset, presetLoc) => {
this.mergeOptions({
options: preset,
extending: preset,
alias: presetLoc,
loc: presetLoc,
dirname: dirname
});
});
} else {
// Otherwise, just merge presets options into the main options.
this.mergePresets(opts.presets, dirname);
delete opts.presets;
}
}
// Merge them into current extending options in case of top-level
// options. In case of presets, just re-assign options which are got
// normalized during the `mergeOptions`.
if (rawOpts === extendingOpts) {
Object.assign(extendingOpts, opts);
} else {
merge(extendingOpts || this.options, opts);
}
}
/**
* Merges all presets into the main options in case we are not in the
* "pass per preset" mode. Otherwise, options are calculated per preset.
*/
mergePresets(presets: Array<string | Object>, dirname: string) {
this.resolvePresets(presets, dirname, (presetOpts, presetLoc) => {
this.mergeOptions({
options: presetOpts,
alias: presetLoc,
loc: presetLoc,
dirname: path.dirname(presetLoc || "")
});
});
}
/**
* Resolves presets options which can be either direct object data,
* or a module name to require.
*/
resolvePresets(presets: Array<string | Object>, dirname: string, onResolve?) {
return presets.map((val) => {
let options;
if (Array.isArray(val)) {
if (val.length > 2) {
throw new Error(`Unexpected extra options ${JSON.stringify(val.slice(2))} passed to preset.`);
}
[val, options] = val;
}
let presetLoc;
try {
if (typeof val === "string") {
presetLoc = resolvePreset(val, dirname);
if (!presetLoc) {
throw new Error(`Couldn't find preset ${JSON.stringify(val)} relative to directory ` +
JSON.stringify(dirname));
}
val = require(presetLoc);
}
// If the imported preset is a transpiled ES2015 module
if (typeof val === "object" && val.__esModule) {
// Try to grab the default export.
if (val.default) {
val = val.default;
} else {
// If there is no default export we treat all named exports as options
// and just remove the __esModule. This is to support presets that have been
// exporting named exports in the past, although we definitely want presets to
// only use the default export (with either an object or a function)
const { __esModule, ...rest } = val; // eslint-disable-line no-unused-vars
val = rest;
}
}
// For compatibility with babel-core < 6.13.x, allow presets to export an object with a
// a 'buildPreset' function that will return the preset itself, while still exporting a
// simple object (rather than a function), for supporting old Babel versions.
if (typeof val === "object" && val.buildPreset) val = val.buildPreset;
if (typeof val !== "function" && options !== undefined) {
throw new Error(`Options ${JSON.stringify(options)} passed to ` +
(presetLoc || "a preset") + " which does not accept options.");
}
if (typeof val === "function") val = val(context, options, { dirname });
if (typeof val !== "object") {
throw new Error(`Unsupported preset format: ${val}.`);
}
onResolve && onResolve(val, presetLoc);
} catch (e) {
if (presetLoc) {
e.message += ` (While processing preset: ${JSON.stringify(presetLoc)})`;
}
throw e;
}
return val;
});
}
normaliseOptions() {
const opts = this.options;
for (const key in config) {
const option = config[key];
const val = opts[key];
// optional
if (!val && option.optional) continue;
// aliases
if (option.alias) {
opts[option.alias] = opts[option.alias] || val;
} else {
opts[key] = val;
}
}
}
init(opts: Object = {}): Object {
for (const config of buildConfigChain(opts, this.log)) {
this.mergeOptions(config);
}
// normalise
this.normaliseOptions(opts);
return this.options;
}
}
OptionManager.memoisedPlugins = [];