Debian Codegraph @

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

raw
1 import buildDebug from "debug";
2 import nodeFs from "fs";
3 import path from "path";
4 import json5 from "json5";
5 import gensync from "gensync";
6 import type { Handler } from "gensync";
7 import { makeStrongCache, makeWeakCacheSync } from "../caching";
8 import type { CacheConfigurator } from "../caching";
9 import { makeConfigAPI } from "../helpers/config-api";
10 import type { ConfigAPI } from "../helpers/config-api";
11 import { makeStaticFileCache } from "./utils";
12 import loadCjsOrMjsDefault from "./module-types";
13 import pathPatternToRegex from "../pattern-to-regex";
14 import type { FilePackageData, RelativeConfig, ConfigFile } from "./types";
15 import type { CallerMetadata } from "../validation/options";
16 import ConfigError from "../../errors/config-error";
17
18 import * as fs from "../../gensync-utils/fs";
19
20 import { createRequire } from "module";
21 import { endHiddenCallStack } from "../../errors/rewrite-stack-trace";
22 const require = createRequire(import.meta.url);
23
24 const debug = buildDebug("babel:config:loading:files:configuration");
25
26 export const ROOT_CONFIG_FILENAMES = [
27 "babel.config.js",
28 "babel.config.cjs",
29 "babel.config.mjs",
30 "babel.config.json",
31 ];
32 const RELATIVE_CONFIG_FILENAMES = [
33 ".babelrc",
34 ".babelrc.js",
35 ".babelrc.cjs",
36 ".babelrc.mjs",
37 ".babelrc.json",
38 ];
39
40 const BABELIGNORE_FILENAME = ".babelignore";
41
42 const LOADING_CONFIGS = new Set();
43
44 const readConfigJS = makeStrongCache(function* readConfigJS(
45 filepath: string,
46 cache: CacheConfigurator<{
47 envName: string;
48 caller: CallerMetadata | undefined;
49 }>,
50 ): Handler<ConfigFile | null> {
51 if (!nodeFs.existsSync(filepath)) {
52 cache.never();
53 return null;
54 }
55
56 // The `require()` call below can make this code reentrant if a require hook like @babel/register has been
57 // loaded into the system. That would cause Babel to attempt to compile the `.babelrc.js` file as it loads
58 // below. To cover this case, we auto-ignore re-entrant config processing.
59 if (LOADING_CONFIGS.has(filepath)) {
60 cache.never();
61
62 debug("Auto-ignoring usage of config %o.", filepath);
63 return {
64 filepath,
65 dirname: path.dirname(filepath),
66 options: {},
67 };
68 }
69
70 let options: unknown;
71 try {
72 LOADING_CONFIGS.add(filepath);
73 options = yield* loadCjsOrMjsDefault(
74 filepath,
75 "You appear to be using a native ECMAScript module configuration " +
76 "file, which is only supported when running Babel asynchronously.",
77 );
78 } finally {
79 LOADING_CONFIGS.delete(filepath);
80 }
81
82 let assertCache = false;
83 if (typeof options === "function") {
84 // @ts-expect-error - if we want to make it possible to use async configs
85 yield* [];
86
87 options = endHiddenCallStack(options as any as (api: ConfigAPI) => {})(
88 makeConfigAPI(cache),
89 );
90
91 assertCache = true;
92 }
93
94 if (!options || typeof options !== "object" || Array.isArray(options)) {
95 throw new ConfigError(
96 `Configuration should be an exported JavaScript object.`,
97 filepath,
98 );
99 }
100
101 // @ts-expect-error todo(flow->ts)
102 if (typeof options.then === "function") {
103 throw new ConfigError(
104 `You appear to be using an async configuration, ` +
105 `which your current version of Babel does not support. ` +
106 `We may add support for this in the future, ` +
107 `but if you're on the most recent version of @babel/core and still ` +
108 `seeing this error, then you'll need to synchronously return your config.`,
109 filepath,
110 );
111 }
112
113 if (assertCache && !cache.configured()) throwConfigError(filepath);
114
115 return {
116 filepath,
117 dirname: path.dirname(filepath),
118 options,
119 };
120 });
121
122 const packageToBabelConfig = makeWeakCacheSync(
123 (file: ConfigFile): ConfigFile | null => {
124 const babel: unknown = file.options["babel"];
125
126 if (typeof babel === "undefined") return null;
127
128 if (typeof babel !== "object" || Array.isArray(babel) || babel === null) {
129 throw new ConfigError(`.babel property must be an object`, file.filepath);
130 }
131
132 return {
133 filepath: file.filepath,
134 dirname: file.dirname,
135 options: babel,
136 };
137 },
138 );
139
140 const readConfigJSON5 = makeStaticFileCache((filepath, content): ConfigFile => {
141 let options;
142 try {
143 options = json5.parse(content);
144 } catch (err) {
145 throw new ConfigError(
146 `Error while parsing config - ${err.message}`,
147 filepath,
148 );
149 }
150
151 if (!options) throw new ConfigError(`No config detected`, filepath);
152
153 if (typeof options !== "object") {
154 throw new ConfigError(`Config returned typeof ${typeof options}`, filepath);
155 }
156 if (Array.isArray(options)) {
157 throw new ConfigError(`Expected config object but found array`, filepath);
158 }
159
160 delete options["$schema"];
161
162 return {
163 filepath,
164 dirname: path.dirname(filepath),
165 options,
166 };
167 });
168
169 const readIgnoreConfig = makeStaticFileCache((filepath, content) => {
170 const ignoreDir = path.dirname(filepath);
171 const ignorePatterns = content
172 .split("\n")
173 .map<string>(line => line.replace(/#(.*?)$/, "").trim())
174 .filter(line => !!line);
175
176 for (const pattern of ignorePatterns) {
177 if (pattern[0] === "!") {
178 throw new ConfigError(
179 `Negation of file paths is not supported.`,
180 filepath,
181 );
182 }
183 }
184
185 return {
186 filepath,
187 dirname: path.dirname(filepath),
188 ignore: ignorePatterns.map(pattern =>
189 pathPatternToRegex(pattern, ignoreDir),
190 ),
191 };
192 });
193
194 export function findConfigUpwards(rootDir: string): string | null {
195 let dirname = rootDir;
196 for (;;) {
197 for (const filename of ROOT_CONFIG_FILENAMES) {
198 if (nodeFs.existsSync(path.join(dirname, filename))) {
199 return dirname;
200 }
201 }
202
203 const nextDir = path.dirname(dirname);
204 if (dirname === nextDir) break;
205 dirname = nextDir;
206 }
207
208 return null;
209 }
210
211 export function* findRelativeConfig(
212 packageData: FilePackageData,
213 envName: string,
214 caller: CallerMetadata | undefined,
215 ): Handler<RelativeConfig> {
216 let config = null;
217 let ignore = null;
218
219 const dirname = path.dirname(packageData.filepath);
220
221 for (const loc of packageData.directories) {
222 if (!config) {
223 config = yield* loadOneConfig(
224 RELATIVE_CONFIG_FILENAMES,
225 loc,
226 envName,
227 caller,
228 packageData.pkg?.dirname === loc
229 ? packageToBabelConfig(packageData.pkg)
230 : null,
231 );
232 }
233
234 if (!ignore) {
235 const ignoreLoc = path.join(loc, BABELIGNORE_FILENAME);
236 ignore = yield* readIgnoreConfig(ignoreLoc);
237
238 if (ignore) {
239 debug("Found ignore %o from %o.", ignore.filepath, dirname);
240 }
241 }
242 }
243
244 return { config, ignore };
245 }
246
247 export function findRootConfig(
248 dirname: string,
249 envName: string,
250 caller: CallerMetadata | undefined,
251 ): Handler<ConfigFile | null> {
252 return loadOneConfig(ROOT_CONFIG_FILENAMES, dirname, envName, caller);
253 }
254
255 function* loadOneConfig(
256 names: string[],
257 dirname: string,
258 envName: string,
259 caller: CallerMetadata | undefined,
260 previousConfig: ConfigFile | null = null,
261 ): Handler<ConfigFile | null> {
262 const configs = yield* gensync.all(
263 names.map(filename =>
264 readConfig(path.join(dirname, filename), envName, caller),
265 ),
266 );
267 const config = configs.reduce((previousConfig: ConfigFile | null, config) => {
268 if (config && previousConfig) {
269 throw new ConfigError(
270 `Multiple configuration files found. Please remove one:\n` +
271 ` - ${path.basename(previousConfig.filepath)}\n` +
272 ` - ${config.filepath}\n` +
273 `from ${dirname}`,
274 );
275 }
276
277 return config || previousConfig;
278 }, previousConfig);
279
280 if (config) {
281 debug("Found configuration %o from %o.", config.filepath, dirname);
282 }
283 return config;
284 }
285
286 export function* loadConfig(
287 name: string,
288 dirname: string,
289 envName: string,
290 caller: CallerMetadata | undefined,
291 ): Handler<ConfigFile> {
292 const filepath = require.resolve(name, { paths: [dirname] });
293
294 const conf = yield* readConfig(filepath, envName, caller);
295 if (!conf) {
296 throw new ConfigError(
297 `Config file contains no configuration data`,
298 filepath,
299 );
300 }
301
302 debug("Loaded config %o from %o.", name, dirname);
303 return conf;
304 }
305
306 /**
307 * Read the given config file, returning the result. Returns null if no config was found, but will
308 * throw if there are parsing errors while loading a config.
309 */
310 function readConfig(
311 filepath: string,
312 envName: string,
313 caller: CallerMetadata | undefined,
314 ): Handler<ConfigFile | null> {
315 const ext = path.extname(filepath);
316 return ext === ".js" || ext === ".cjs" || ext === ".mjs"
317 ? readConfigJS(filepath, { envName, caller })
318 : readConfigJSON5(filepath);
319 }
320
321 export function* resolveShowConfigPath(
322 dirname: string,
323 ): Handler<string | null> {
324 const targetPath = process.env.BABEL_SHOW_CONFIG_FOR;
325 if (targetPath != null) {
326 const absolutePath = path.resolve(dirname, targetPath);
327 const stats = yield* fs.stat(absolutePath);
328 if (!stats.isFile()) {
329 throw new Error(
330 `${absolutePath}: BABEL_SHOW_CONFIG_FOR must refer to a regular file, directories are not supported.`,
331 );
332 }
333 return absolutePath;
334 }
335 return null;
336 }
337
338 function throwConfigError(filepath: string): never {
339 throw new ConfigError(
340 `\
341 Caching was left unconfigured. Babel's plugins, presets, and .babelrc.js files can be configured
342 for various types of caching, using the first param of their handler functions:
343
344 module.exports = function(api) {
345 // The API exposes the following:
346
347 // Cache the returned value forever and don't call this function again.
348 api.cache(true);
349
350 // Don't cache at all. Not recommended because it will be very slow.
351 api.cache(false);
352
353 // Cached based on the value of some function. If this function returns a value different from
354 // a previously-encountered value, the plugins will re-evaluate.
355 var env = api.cache(() => process.env.NODE_ENV);
356
357 // If testing for a specific env, we recommend specifics to avoid instantiating a plugin for
358 // any possible NODE_ENV value that might come up during plugin execution.
359 var isProd = api.cache(() => process.env.NODE_ENV === "production");
360
361 // .cache(fn) will perform a linear search though instances to find the matching plugin based
362 // based on previous instantiated plugins. If you want to recreate the plugin and discard the
363 // previous instance whenever something changes, you may use:
364 var isProd = api.cache.invalidate(() => process.env.NODE_ENV === "production");
365
366 // Note, we also expose the following more-verbose versions of the above examples:
367 api.cache.forever(); // api.cache(true)
368 api.cache.never(); // api.cache(false)
369 api.cache.using(fn); // api.cache(fn)
370
371 // Return the value that will be cached.
372 return { };
373 };`,
374 filepath,
375 );
376 }