Debian Codegraph @

packages/babel-core/src/config/config-descriptors.ts

raw
1 import gensync, { type Handler } from "gensync";
2 import { once } from "../gensync-utils/functional";
3
4 import { loadPlugin, loadPreset } from "./files";
5
6 import { getItemDescriptor } from "./item";
7
8 import {
9 makeWeakCacheSync,
10 makeStrongCacheSync,
11 makeStrongCache,
12 } from "./caching";
13 import type { CacheConfigurator } from "./caching";
14
15 import type {
16 ValidatedOptions,
17 PluginList,
18 PluginItem,
19 } from "./validation/options";
20
21 import { resolveBrowserslistConfigFile } from "./resolve-targets";
22
23 // Represents a config object and functions to lazily load the descriptors
24 // for the plugins and presets so we don't load the plugins/presets unless
25 // the options object actually ends up being applicable.
26 export type OptionsAndDescriptors = {
27 options: ValidatedOptions;
28 plugins: () => Handler<Array<UnloadedDescriptor>>;
29 presets: () => Handler<Array<UnloadedDescriptor>>;
30 };
31
32 // Represents a plugin or presets at a given location in a config object.
33 // At this point these have been resolved to a specific object or function,
34 // but have not yet been executed to call functions with options.
35 export type UnloadedDescriptor = {
36 name: string | undefined;
37 value: any | Function;
38 options: {} | undefined | false;
39 dirname: string;
40 alias: string;
41 ownPass?: boolean;
42 file?: {
43 request: string;
44 resolved: string;
45 };
46 };
47
48 function isEqualDescriptor(
49 a: UnloadedDescriptor,
50 b: UnloadedDescriptor,
51 ): boolean {
52 return (
53 a.name === b.name &&
54 a.value === b.value &&
55 a.options === b.options &&
56 a.dirname === b.dirname &&
57 a.alias === b.alias &&
58 a.ownPass === b.ownPass &&
59 (a.file && a.file.request) === (b.file && b.file.request) &&
60 (a.file && a.file.resolved) === (b.file && b.file.resolved)
61 );
62 }
63
64 export type ValidatedFile = {
65 filepath: string;
66 dirname: string;
67 options: ValidatedOptions;
68 };
69
70 // eslint-disable-next-line require-yield
71 function* handlerOf<T>(value: T): Handler<T> {
72 return value;
73 }
74
75 function optionsWithResolvedBrowserslistConfigFile(
76 options: ValidatedOptions,
77 dirname: string,
78 ): ValidatedOptions {
79 if (typeof options.browserslistConfigFile === "string") {
80 options.browserslistConfigFile = resolveBrowserslistConfigFile(
81 options.browserslistConfigFile,
82 dirname,
83 );
84 }
85 return options;
86 }
87
88 /**
89 * Create a set of descriptors from a given options object, preserving
90 * descriptor identity based on the identity of the plugin/preset arrays
91 * themselves, and potentially on the identity of the plugins/presets + options.
92 */
93 export function createCachedDescriptors(
94 dirname: string,
95 options: ValidatedOptions,
96 alias: string,
97 ): OptionsAndDescriptors {
98 const { plugins, presets, passPerPreset } = options;
99 return {
100 options: optionsWithResolvedBrowserslistConfigFile(options, dirname),
101 plugins: plugins
102 ? () =>
103 // @ts-expect-error todo(flow->ts) ts complains about incorrect arguments
104 // eslint-disable-next-line @typescript-eslint/no-use-before-define
105 createCachedPluginDescriptors(plugins, dirname)(alias)
106 : () => handlerOf([]),
107 presets: presets
108 ? () =>
109 // @ts-expect-error todo(flow->ts) ts complains about incorrect arguments
110 // eslint-disable-next-line @typescript-eslint/no-use-before-define
111 createCachedPresetDescriptors(presets, dirname)(alias)(
112 !!passPerPreset,
113 )
114 : () => handlerOf([]),
115 };
116 }
117
118 /**
119 * Create a set of descriptors from a given options object, with consistent
120 * identity for the descriptors, but not caching based on any specific identity.
121 */
122 export function createUncachedDescriptors(
123 dirname: string,
124 options: ValidatedOptions,
125 alias: string,
126 ): OptionsAndDescriptors {
127 return {
128 options: optionsWithResolvedBrowserslistConfigFile(options, dirname),
129 // The returned result here is cached to represent a config object in
130 // memory, so we build and memoize the descriptors to ensure the same
131 // values are returned consistently.
132 plugins: once(() =>
133 createPluginDescriptors(options.plugins || [], dirname, alias),
134 ),
135 presets: once(() =>
136 createPresetDescriptors(
137 options.presets || [],
138 dirname,
139 alias,
140 !!options.passPerPreset,
141 ),
142 ),
143 };
144 }
145
146 const PRESET_DESCRIPTOR_CACHE = new WeakMap();
147 const createCachedPresetDescriptors = makeWeakCacheSync(
148 (items: PluginList, cache: CacheConfigurator<string>) => {
149 const dirname = cache.using(dir => dir);
150 return makeStrongCacheSync((alias: string) =>
151 makeStrongCache(function* (
152 passPerPreset: boolean,
153 ): Handler<Array<UnloadedDescriptor>> {
154 const descriptors = yield* createPresetDescriptors(
155 items,
156 dirname,
157 alias,
158 passPerPreset,
159 );
160 return descriptors.map(
161 // Items are cached using the overall preset array identity when
162 // possibly, but individual descriptors are also cached if a match
163 // can be found in the previously-used descriptor lists.
164 desc => loadCachedDescriptor(PRESET_DESCRIPTOR_CACHE, desc),
165 );
166 }),
167 );
168 },
169 );
170
171 const PLUGIN_DESCRIPTOR_CACHE = new WeakMap();
172 const createCachedPluginDescriptors = makeWeakCacheSync(
173 (items: PluginList, cache: CacheConfigurator<string>) => {
174 const dirname = cache.using(dir => dir);
175 return makeStrongCache(function* (
176 alias: string,
177 ): Handler<Array<UnloadedDescriptor>> {
178 const descriptors = yield* createPluginDescriptors(items, dirname, alias);
179 return descriptors.map(
180 // Items are cached using the overall plugin array identity when
181 // possibly, but individual descriptors are also cached if a match
182 // can be found in the previously-used descriptor lists.
183 desc => loadCachedDescriptor(PLUGIN_DESCRIPTOR_CACHE, desc),
184 );
185 });
186 },
187 );
188
189 /**
190 * When no options object is given in a descriptor, this object is used
191 * as a WeakMap key in order to have consistent identity.
192 */
193 const DEFAULT_OPTIONS = {};
194
195 /**
196 * Given the cache and a descriptor, returns a matching descriptor from the
197 * cache, or else returns the input descriptor and adds it to the cache for
198 * next time.
199 */
200 function loadCachedDescriptor(
201 cache: WeakMap<{} | Function, WeakMap<{}, Array<UnloadedDescriptor>>>,
202 desc: UnloadedDescriptor,
203 ) {
204 const { value, options = DEFAULT_OPTIONS } = desc;
205 if (options === false) return desc;
206
207 let cacheByOptions = cache.get(value);
208 if (!cacheByOptions) {
209 cacheByOptions = new WeakMap();
210 cache.set(value, cacheByOptions);
211 }
212
213 let possibilities = cacheByOptions.get(options);
214 if (!possibilities) {
215 possibilities = [];
216 cacheByOptions.set(options, possibilities);
217 }
218
219 if (possibilities.indexOf(desc) === -1) {
220 const matches = possibilities.filter(possibility =>
221 isEqualDescriptor(possibility, desc),
222 );
223 if (matches.length > 0) {
224 return matches[0];
225 }
226
227 possibilities.push(desc);
228 }
229
230 return desc;
231 }
232
233 function* createPresetDescriptors(
234 items: PluginList,
235 dirname: string,
236 alias: string,
237 passPerPreset: boolean,
238 ): Handler<Array<UnloadedDescriptor>> {
239 return yield* createDescriptors(
240 "preset",
241 items,
242 dirname,
243 alias,
244 passPerPreset,
245 );
246 }
247
248 function* createPluginDescriptors(
249 items: PluginList,
250 dirname: string,
251 alias: string,
252 ): Handler<Array<UnloadedDescriptor>> {
253 return yield* createDescriptors("plugin", items, dirname, alias);
254 }
255
256 function* createDescriptors(
257 type: "plugin" | "preset",
258 items: PluginList,
259 dirname: string,
260 alias: string,
261 ownPass?: boolean,
262 ): Handler<Array<UnloadedDescriptor>> {
263 const descriptors = yield* gensync.all(
264 items.map((item, index) =>
265 createDescriptor(item, dirname, {
266 type,
267 alias: `${alias}$${index}`,
268 ownPass: !!ownPass,
269 }),
270 ),
271 );
272
273 assertNoDuplicates(descriptors);
274
275 return descriptors;
276 }
277
278 /**
279 * Given a plugin/preset item, resolve it into a standard format.
280 */
281 export function* createDescriptor(
282 pair: PluginItem,
283 dirname: string,
284 {
285 type,
286 alias,
287 ownPass,
288 }: {
289 type?: "plugin" | "preset";
290 alias: string;
291 ownPass?: boolean;
292 },
293 ): Handler<UnloadedDescriptor> {
294 const desc = getItemDescriptor(pair);
295 if (desc) {
296 return desc;
297 }
298
299 let name;
300 let options;
301 // todo(flow->ts) better type annotation
302 let value: any = pair;
303 if (Array.isArray(value)) {
304 if (value.length === 3) {
305 [value, options, name] = value;
306 } else {
307 [value, options] = value;
308 }
309 }
310
311 let file = undefined;
312 let filepath = null;
313 if (typeof value === "string") {
314 if (typeof type !== "string") {
315 throw new Error(
316 "To resolve a string-based item, the type of item must be given",
317 );
318 }
319 const resolver = type === "plugin" ? loadPlugin : loadPreset;
320 const request = value;
321
322 ({ filepath, value } = yield* resolver(value, dirname));
323
324 file = {
325 request,
326 resolved: filepath,
327 };
328 }
329
330 if (!value) {
331 throw new Error(`Unexpected falsy value: ${String(value)}`);
332 }
333
334 if (typeof value === "object" && value.__esModule) {
335 if (value.default) {
336 value = value.default;
337 } else {
338 throw new Error("Must export a default export when using ES6 modules.");
339 }
340 }
341
342 if (typeof value !== "object" && typeof value !== "function") {
343 throw new Error(
344 `Unsupported format: ${typeof value}. Expected an object or a function.`,
345 );
346 }
347
348 if (filepath !== null && typeof value === "object" && value) {
349 // We allow object values for plugins/presets nested directly within a
350 // config object, because it can be useful to define them in nested
351 // configuration contexts.
352 throw new Error(
353 `Plugin/Preset files are not allowed to export objects, only functions. In ${filepath}`,
354 );
355 }
356
357 return {
358 name,
359 alias: filepath || alias,
360 value,
361 options,
362 dirname,
363 ownPass,
364 file,
365 };
366 }
367
368 function assertNoDuplicates(items: Array<UnloadedDescriptor>): void {
369 const map = new Map();
370
371 for (const item of items) {
372 if (typeof item.value !== "function") continue;
373
374 let nameMap = map.get(item.value);
375 if (!nameMap) {
376 nameMap = new Set();
377 map.set(item.value, nameMap);
378 }
379
380 if (nameMap.has(item.name)) {
381 const conflicts = items.filter(i => i.value === item.value);
382 throw new Error(
383 [
384 `Duplicate plugin/preset detected.`,
385 `If you'd like to use two separate instances of a plugin,`,
386 `they need separate names, e.g.`,
387 ``,
388 ` plugins: [`,
389 ` ['some-plugin', {}],`,
390 ` ['some-plugin', {}, 'some unique name'],`,
391 ` ]`,
392 ``,
393 `Duplicates detected are:`,
394 `${JSON.stringify(conflicts, null, 2)}`,
395 ].join("\n"),
396 );
397 }
398
399 nameMap.add(item.name);
400 }
401 }