Debian Codegraph @

packages/babel-core/src/config/files/plugins.ts

raw ◀ ▶
Source reconstructed at patch state 1 of 2 — not the installed (fully patched) source.
2 Debian patches touch this file
1 /**
2 * This file handles all logic for converting string-based configuration references into loaded objects.
3 */
4
5 import buildDebug from "debug";
6 import path from "path";
7 import gensync, { type Handler } from "gensync";
8 import { isAsync } from "../../gensync-utils/async";
9 import loadCjsOrMjsDefault, { supportsESM } from "./module-types";
10 import { fileURLToPath, pathToFileURL } from "url";
11
12 import importMetaResolve from "./import-meta-resolve";
13
14 import { createRequire } from "module";
15 const require = createRequire(import.meta.url);
16
17 const debug = buildDebug("babel:config:loading:files:plugins");
18
19 const EXACT_RE = /^module:/;
20 const BABEL_PLUGIN_PREFIX_RE = /^(?!@|module:|[^/]+\/|babel-plugin-)/;
21 const BABEL_PRESET_PREFIX_RE = /^(?!@|module:|[^/]+\/|babel-preset-)/;
22 const BABEL_PLUGIN_ORG_RE = /^(@babel\/)(?!plugin-|[^/]+\/)/;
23 const BABEL_PRESET_ORG_RE = /^(@babel\/)(?!preset-|[^/]+\/)/;
24 const OTHER_PLUGIN_ORG_RE =
25 /^(@(?!babel\/)[^/]+\/)(?![^/]*babel-plugin(?:-|\/|$)|[^/]+\/)/;
26 const OTHER_PRESET_ORG_RE =
27 /^(@(?!babel\/)[^/]+\/)(?![^/]*babel-preset(?:-|\/|$)|[^/]+\/)/;
28 const OTHER_ORG_DEFAULT_RE = /^(@(?!babel$)[^/]+)$/;
29
30 export function* resolvePlugin(name: string, dirname: string): Handler<string> {
31 // eslint-disable-next-line @typescript-eslint/no-use-before-define
32 return yield* resolveStandardizedName("plugin", name, dirname);
33 }
34
35 export function* resolvePreset(name: string, dirname: string): Handler<string> {
36 // eslint-disable-next-line @typescript-eslint/no-use-before-define
37 return yield* resolveStandardizedName("preset", name, dirname);
38 }
39
40 export function* loadPlugin(
41 name: string,
42 dirname: string,
43 ): Handler<{ filepath: string; value: unknown }> {
44 const filepath = yield* resolvePlugin(name, dirname);
45
46 const value = yield* requireModule("plugin", filepath);
47 debug("Loaded plugin %o from %o.", name, dirname);
48
49 return { filepath, value };
50 }
51
52 export function* loadPreset(
53 name: string,
54 dirname: string,
55 ): Handler<{ filepath: string; value: unknown }> {
56 const filepath = yield* resolvePreset(name, dirname);
57
58 const value = yield* requireModule("preset", filepath);
59
60 debug("Loaded preset %o from %o.", name, dirname);
61
62 return { filepath, value };
63 }
64
65 function standardizeName(type: "plugin" | "preset", name: string) {
66 // Let absolute and relative paths through.
67 if (path.isAbsolute(name)) return name;
68
69 const isPreset = type === "preset";
70
71 return (
72 name
73 // foo -> babel-preset-foo
74 .replace(
75 isPreset ? BABEL_PRESET_PREFIX_RE : BABEL_PLUGIN_PREFIX_RE,
76 `babel-${type}-`,
77 )
78 // @babel/es2015 -> @babel/preset-es2015
79 .replace(
80 isPreset ? BABEL_PRESET_ORG_RE : BABEL_PLUGIN_ORG_RE,
81 `$1${type}-`,
82 )
83 // @foo/mypreset -> @foo/babel-preset-mypreset
84 .replace(
85 isPreset ? OTHER_PRESET_ORG_RE : OTHER_PLUGIN_ORG_RE,
86 `$1babel-${type}-`,
87 )
88 // @foo -> @foo/babel-preset
89 .replace(OTHER_ORG_DEFAULT_RE, `$1/babel-${type}`)
90 // module:mypreset -> mypreset
91 .replace(EXACT_RE, "")
92 );
93 }
94
95 type Result<T> = { error: Error; value: null } | { error: null; value: T };
96
97 function* resolveAlternativesHelper(
98 type: "plugin" | "preset",
99 name: string,
100 ): Iterator<string, string, Result<string>> {
101 const standardizedName = standardizeName(type, name);
102 const { error, value } = yield standardizedName;
103 if (!error) return value;
104
105 // @ts-expect-error code may not index error
106 if (error.code !== "MODULE_NOT_FOUND") throw error;
107
108 if (standardizedName !== name && !(yield name).error) {
109 error.message += `\n- If you want to resolve "${name}", use "module:${name}"`;
110 }
111
112 if (!(yield standardizeName(type, "@babel/" + name)).error) {
113 error.message += `\n- Did you mean "@babel/${name}"?`;
114 }
115
116 const oppositeType = type === "preset" ? "plugin" : "preset";
117 if (!(yield standardizeName(oppositeType, name)).error) {
118 error.message += `\n- Did you accidentally pass a ${oppositeType} as a ${type}?`;
119 }
120
121 throw error;
122 }
123
124 function tryRequireResolve(
125 id: Parameters<RequireResolve>[0],
126 { paths: [dirname] }: Parameters<RequireResolve>[1],
127 ): Result<string> {
128 try {
129 return { error: null, value: require.resolve(id, { paths: [dirname] }) };
130 } catch (error) {
131 return { error, value: null };
132 }
133 }
134
135 async function tryImportMetaResolve(
136 id: Parameters<ImportMeta["resolve"]>[0],
137 options: Parameters<ImportMeta["resolve"]>[1],
138 ): Promise<Result<string>> {
139 try {
140 return { error: null, value: await importMetaResolve(id, options) };
141 } catch (error) {
142 return { error, value: null };
143 }
144 }
145
146 function resolveStandardizedNameForRequire(
147 type: "plugin" | "preset",
148 name: string,
149 dirname: string,
150 ) {
151 const it = resolveAlternativesHelper(type, name);
152 let res = it.next();
153 while (!res.done) {
154 res = it.next(tryRequireResolve(res.value, { paths: [dirname] }));
155 }
156 while (!res.done) {
157 res = it.next(tryRequireResolve(res.value, { paths: ['/usr/share/nodejs'] }));
158 }
159 return res.value;
160 }
161 async function resolveStandardizedNameForImport(
162 type: "plugin" | "preset",
163 name: string,
164 dirname: string,
165 ) {
166 const parentUrl = pathToFileURL(
167 path.join(dirname, "./babel-virtual-resolve-base.js"),
168 ).href;
169
170 const it = resolveAlternativesHelper(type, name);
171 let res = it.next();
172 while (!res.done) {
173 res = it.next(await tryImportMetaResolve(res.value, parentUrl));
174 }
175 return fileURLToPath(res.value);
176 }
177
178 const resolveStandardizedName = gensync<
179 [type: "plugin" | "preset", name: string, dirname?: string],
180 string
181 >({
182 sync(type, name, dirname = process.cwd()) {
183 return resolveStandardizedNameForRequire(type, name, dirname);
184 },
185 async async(type, name, dirname = process.cwd()) {
186 if (!supportsESM) {
187 return resolveStandardizedNameForRequire(type, name, dirname);
188 }
189
190 try {
191 return await resolveStandardizedNameForImport(type, name, dirname);
192 } catch (e) {
193 try {
194 return resolveStandardizedNameForRequire(type, name, dirname);
195 } catch (e2) {
196 if (e.type === "MODULE_NOT_FOUND") throw e;
197 if (e2.type === "MODULE_NOT_FOUND") throw e2;
198 throw e;
199 }
200 }
201 },
202 });
203
204 if (!process.env.BABEL_8_BREAKING) {
205 // eslint-disable-next-line no-var
206 var LOADING_MODULES = new Set();
207 }
208 function* requireModule(type: string, name: string): Handler<unknown> {
209 if (!process.env.BABEL_8_BREAKING) {
210 if (!(yield* isAsync()) && LOADING_MODULES.has(name)) {
211 throw new Error(
212 `Reentrant ${type} detected trying to load "${name}". This module is not ignored ` +
213 "and is trying to load itself while compiling itself, leading to a dependency cycle. " +
214 'We recommend adding it to your "ignore" list in your babelrc, or to a .babelignore.',
215 );
216 }
217 }
218
219 try {
220 if (!process.env.BABEL_8_BREAKING) {
221 LOADING_MODULES.add(name);
222 }
223 return yield* loadCjsOrMjsDefault(
224 name,
225 `You appear to be using a native ECMAScript module ${type}, ` +
226 "which is only supported when running Babel asynchronously.",
227 // For backward compatibility, we need to support malformed presets
228 // defined as separate named exports rather than a single default
229 // export.
230 // See packages/babel-core/test/fixtures/option-manager/presets/es2015_named.js
231 true,
232 );
233 } catch (err) {
234 err.message = `[BABEL]: ${err.message} (While processing: ${name})`;
235 throw err;
236 } finally {
237 if (!process.env.BABEL_8_BREAKING) {
238 LOADING_MODULES.delete(name);
239 }
240 }
241 }