Debian Codegraph @

packages/babel-core/src/config/helpers/config-api.ts

raw
1 import semver from "semver";
2 import type { Targets } from "@babel/helper-compilation-targets";
3
4 import { version as coreVersion } from "../../";
5 import { assertSimpleType } from "../caching";
6 import type {
7 CacheConfigurator,
8 SimpleCacheConfigurator,
9 SimpleType,
10 } from "../caching";
11
12 import type { AssumptionName, CallerMetadata } from "../validation/options";
13
14 import type * as Context from "../cache-contexts";
15
16 type EnvFunction = {
17 (): string;
18 <T>(extractor: (babelEnv: string) => T): T;
19 (envVar: string): boolean;
20 (envVars: Array<string>): boolean;
21 };
22
23 type CallerFactory = (
24 extractor: (callerMetadata: CallerMetadata | undefined) => unknown,
25 ) => SimpleType;
26 type TargetsFunction = () => Targets;
27 type AssumptionFunction = (name: AssumptionName) => boolean | undefined;
28
29 export type ConfigAPI = {
30 version: string;
31 cache: SimpleCacheConfigurator;
32 env: EnvFunction;
33 async: () => boolean;
34 assertVersion: typeof assertVersion;
35 caller?: CallerFactory;
36 };
37
38 export type PresetAPI = {
39 targets: TargetsFunction;
40 addExternalDependency: (ref: string) => void;
41 } & ConfigAPI;
42
43 export type PluginAPI = {
44 assumption: AssumptionFunction;
45 } & PresetAPI;
46
47 export function makeConfigAPI<SideChannel extends Context.SimpleConfig>(
48 cache: CacheConfigurator<SideChannel>,
49 ): ConfigAPI {
50 // TODO(@nicolo-ribaudo): If we remove the explicit type from `value`
51 // and the `as any` type cast, TypeScript crashes in an infinite
52 // recursion. After upgrading to TS4.7 and finishing the noImplicitAny
53 // PR, we should check if it still crashes and report it to the TS team.
54 const env: EnvFunction = ((
55 value: string | string[] | (<T>(babelEnv: string) => T),
56 ) =>
57 cache.using(data => {
58 if (typeof value === "undefined") return data.envName;
59 if (typeof value === "function") {
60 return assertSimpleType(value(data.envName));
61 }
62 return (Array.isArray(value) ? value : [value]).some(entry => {
63 if (typeof entry !== "string") {
64 throw new Error("Unexpected non-string value");
65 }
66 return entry === data.envName;
67 });
68 })) as any;
69
70 const caller = (cb: {
71 (CallerMetadata: CallerMetadata | undefined): SimpleType;
72 }) => cache.using(data => assertSimpleType(cb(data.caller)));
73
74 return {
75 version: coreVersion,
76 cache: cache.simple(),
77 // Expose ".env()" so people can easily get the same env that we expose using the "env" key.
78 env,
79 async: () => false,
80 caller,
81 assertVersion,
82 };
83 }
84
85 export function makePresetAPI<SideChannel extends Context.SimplePreset>(
86 cache: CacheConfigurator<SideChannel>,
87 externalDependencies: Array<string>,
88 ): PresetAPI {
89 const targets = () =>
90 // We are using JSON.parse/JSON.stringify because it's only possible to cache
91 // primitive values. We can safely stringify the targets object because it
92 // only contains strings as its properties.
93 // Please make the Record and Tuple proposal happen!
94 JSON.parse(cache.using(data => JSON.stringify(data.targets)));
95
96 const addExternalDependency = (ref: string) => {
97 externalDependencies.push(ref);
98 };
99
100 return { ...makeConfigAPI(cache), targets, addExternalDependency };
101 }
102
103 export function makePluginAPI<SideChannel extends Context.SimplePlugin>(
104 cache: CacheConfigurator<SideChannel>,
105 externalDependencies: Array<string>,
106 ): PluginAPI {
107 const assumption = (name: string) =>
108 cache.using(data => data.assumptions[name]);
109
110 return { ...makePresetAPI(cache, externalDependencies), assumption };
111 }
112
113 function assertVersion(range: string | number): void {
114 if (typeof range === "number") {
115 if (!Number.isInteger(range)) {
116 throw new Error("Expected string or integer value.");
117 }
118 range = `^${range}.0.0-0`;
119 }
120 if (typeof range !== "string") {
121 throw new Error("Expected string or integer value.");
122 }
123
124 if (semver.satisfies(coreVersion, range)) return;
125
126 const limit = Error.stackTraceLimit;
127
128 if (typeof limit === "number" && limit < 25) {
129 // Bump up the limit if needed so that users are more likely
130 // to be able to see what is calling Babel.
131 Error.stackTraceLimit = 25;
132 }
133
134 const err = new Error(
135 `Requires Babel "${range}", but was loaded with "${coreVersion}". ` +
136 `If you are sure you have a compatible version of @babel/core, ` +
137 `it is likely that something in your build process is loading the ` +
138 `wrong version. Inspect the stack trace of this error to look for ` +
139 `the first entry that doesn't mention "@babel/core" or "babel-core" ` +
140 `to see what is calling Babel.`,
141 );
142
143 if (typeof limit === "number") {
144 Error.stackTraceLimit = limit;
145 }
146
147 throw Object.assign(err, {
148 code: "BABEL_VERSION_UNSUPPORTED",
149 version: coreVersion,
150 range,
151 });
152 }