vitest-native 0.14.1 → 0.15.0-rc.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -10
- package/dist/cli.d.mts +9 -1
- package/dist/cli.mjs +2609 -361
- package/dist/context.d.mts +19 -0
- package/dist/context.mjs +47 -1
- package/dist/docs-url.d.mts +4 -0
- package/dist/docs-url.mjs +9 -0
- package/dist/errors.d.mts +21 -1
- package/dist/hang-watch-setup.mjs +55 -0
- package/dist/hang-watch.d.mts +56 -0
- package/dist/hang-watch.mjs +343 -0
- package/dist/helpers.cjs +24 -53
- package/dist/helpers.mjs +22 -1
- package/dist/host-D0r3P_T1.mjs +1985 -0
- package/dist/{index-aNBCTfA5.d.mts → index-JOR602XU.d.mts} +105 -2
- package/dist/index.d.mts +2 -1
- package/dist/index.mjs +723 -149
- package/dist/jest-compat/aliases.d.mts +1 -0
- package/dist/jest-compat/aliases.mjs +11 -0
- package/dist/jest-compat/interop.mjs +1 -1
- package/dist/jest-compat/jest-object.mjs +23 -5
- package/dist/jest-compat/node-registry.mjs +836 -68
- package/dist/jest-compat/setup.mjs +205 -12
- package/dist/jest-compat.cjs +383 -47
- package/dist/jest-compat.d.cts +19 -2
- package/dist/jest-compat.d.mts +19 -2
- package/dist/jest-compat.mjs +232 -47
- package/dist/matchers.d.cts +0 -1
- package/dist/matchers.d.mts +0 -1
- package/dist/native/assets.mjs +3 -1
- package/dist/native/babel-caller.d.mts +13 -0
- package/dist/native/babel-caller.mjs +24 -0
- package/dist/native/babel-toolchain.mjs +27 -3
- package/dist/native/boundary.mjs +45 -8
- package/dist/native/bounded-process.mjs +63 -5
- package/dist/native/bridge-client.mjs +133 -0
- package/dist/native/bridge-server.mjs +215 -0
- package/dist/native/bridge-thread.mjs +79 -0
- package/dist/native/bridge.mjs +512 -0
- package/dist/native/compile-error.mjs +120 -0
- package/dist/native/explain.mjs +3 -2
- package/dist/native/expo-module-mocks.mjs +2 -0
- package/dist/native/export-condition-recovery.mjs +20 -99
- package/dist/native/hooks.mjs +256 -133
- package/dist/native/jest-resolvers.mjs +94 -0
- package/dist/native/library-jest.mjs +352 -0
- package/dist/native/loader.mjs +167 -73
- package/dist/native/match.mjs +67 -7
- package/dist/native/module-reset.mjs +44 -49
- package/dist/native/ownership-ledger.d.mts +87 -0
- package/dist/native/ownership-ledger.mjs +524 -0
- package/dist/native/ownership.d.mts +20 -0
- package/dist/native/ownership.mjs +114 -0
- package/dist/native/registry-compiler.mjs +39 -5
- package/dist/native/registry-process.mjs +327 -28
- package/dist/native/registry.mjs +752 -200
- package/dist/native/resident-health.mjs +1 -0
- package/dist/native/resolve.d.mts +7 -0
- package/dist/native/resolve.mjs +119 -4
- package/dist/native/rntl-hooks.mjs +9 -5
- package/dist/native/rntl-text-host.mjs +5 -15
- package/dist/native/root-spelling.d.mts +6 -0
- package/dist/native/root-spelling.mjs +77 -0
- package/dist/native/runner.mjs +2 -19
- package/dist/native/setup.mjs +119 -38
- package/dist/native/shared-resolver.d.mts +141 -0
- package/dist/native/shared-resolver.mjs +719 -0
- package/dist/native/test-runner.mjs +26 -0
- package/dist/native/transform.mjs +18 -22
- package/dist/native/worker.mjs +9 -4
- package/dist/node-dispatch.mjs +293 -0
- package/dist/{preset-map-CogjYmSw.mjs → preset-map-DdAexIwz.mjs} +113 -2
- package/dist/{presets-CXDyg51l.mjs → presets-_EaSw29m.mjs} +710 -130
- package/dist/presets.d.mts +1 -1
- package/dist/presets.mjs +1 -1
- package/dist/rntl-matchers.d.ts +11 -15
- package/dist/rntl-support.mjs +28 -13
- package/dist/root-mocks-BNXeosbR.mjs +155 -0
- package/dist/serializer.cjs +7 -5
- package/dist/serializer.d.cts +7 -5
- package/dist/serializer.d.mts +7 -5
- package/dist/serializer.mjs +7 -5
- package/dist/setup.mjs +26 -27
- package/docs/migrating-from-jest.md +9 -232
- package/docs/migrating-from-vitest-react-native.md +4 -4
- package/docs/release-readiness.md +9 -11
- package/docs/versioning.md +38 -9
- package/package.json +59 -33
- package/dist/host-BAAAlSkO.mjs +0 -1028
|
@@ -0,0 +1,1985 @@
|
|
|
1
|
+
import { f as presetShadowing, l as libraryMockUsable, t as AUTO_DETECT_PRESETS } from "./preset-map-DdAexIwz.mjs";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import fs from "node:fs";
|
|
5
|
+
import { VitestNativeError, VitestNativeTypeError } from "./errors.mjs";
|
|
6
|
+
import { mainFieldFile } from "./native/shared-resolver.mjs";
|
|
7
|
+
import crypto, { createHash } from "node:crypto";
|
|
8
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
9
|
+
import { resolveTransformPreset } from "./native/babel-preset.mjs";
|
|
10
|
+
import { projectBabelCaller } from "./native/babel-caller.mjs";
|
|
11
|
+
import { relativeToRoot, rootSpellingOf } from "./native/root-spelling.mjs";
|
|
12
|
+
import { containsPath, dependencyDirOf } from "./native/match.mjs";
|
|
13
|
+
// src/validate.ts
|
|
14
|
+
const KNOWN_OPTIONS = [
|
|
15
|
+
"platform",
|
|
16
|
+
"presets",
|
|
17
|
+
"mocks",
|
|
18
|
+
"diagnostics",
|
|
19
|
+
"assetExts",
|
|
20
|
+
"metroConfig",
|
|
21
|
+
"engine",
|
|
22
|
+
"transform",
|
|
23
|
+
"hotRuntime",
|
|
24
|
+
"nativeModules",
|
|
25
|
+
"registryBuild",
|
|
26
|
+
"hangTimeout",
|
|
27
|
+
"ownership",
|
|
28
|
+
"experimental",
|
|
29
|
+
"projectBabel"
|
|
30
|
+
];
|
|
31
|
+
const KNOWN_EXPERIMENTAL_OPTIONS = ["ownershipModel", "nodeMocks"];
|
|
32
|
+
const KNOWN_HOT_RUNTIME_OPTIONS = [
|
|
33
|
+
"mode",
|
|
34
|
+
"recycleAfterFiles",
|
|
35
|
+
"memoryLimit",
|
|
36
|
+
"allowUnboundedMemory",
|
|
37
|
+
"preserveGlobals",
|
|
38
|
+
"esmGeneration"
|
|
39
|
+
];
|
|
40
|
+
const KNOWN_METRO_CONFIG_OPTIONS = ["configFile"];
|
|
41
|
+
function assertStringArray(value, option) {
|
|
42
|
+
if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string" || entry.length === 0)) throw new VitestNativeTypeError("INVALID_OPTION", `"${option}" must be an array of non-empty strings.`);
|
|
43
|
+
}
|
|
44
|
+
function assertNonNegativeInteger(value, option) {
|
|
45
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw new VitestNativeTypeError("INVALID_OPTION", `"${option}" must be a non-negative safe integer.`);
|
|
46
|
+
}
|
|
47
|
+
const OWNERSHIP_MODES = ["warn", "error"];
|
|
48
|
+
function validateOwnership(value) {
|
|
49
|
+
const invalid = (detail) => new VitestNativeTypeError("INVALID_OPTION", `"ownership" ${detail}`);
|
|
50
|
+
if (typeof value === "string") {
|
|
51
|
+
if (!OWNERSHIP_MODES.includes(value)) throw invalid(`must be "warn" or "error".`);
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw invalid(`must be "warn", "error", or { mode, allow }.`);
|
|
55
|
+
const { mode, allow, ...rest } = value;
|
|
56
|
+
const unknown = Object.keys(rest);
|
|
57
|
+
if (unknown.length > 0) throw invalid(`has unknown keys: ${unknown.join(", ")}.`);
|
|
58
|
+
if (mode !== void 0 && !OWNERSHIP_MODES.includes(mode)) throw invalid(`mode must be "warn" or "error".`);
|
|
59
|
+
if (allow === void 0) return;
|
|
60
|
+
if (!Array.isArray(allow) || allow.some((entry) => !entry || typeof entry !== "object" || typeof entry.path !== "string" || entry.path.length === 0 || typeof entry.reason !== "string" || entry.reason.trim().length === 0)) throw invalid(`allow must be an array of { path, reason } with non-empty strings.`);
|
|
61
|
+
}
|
|
62
|
+
function validateOptions(options) {
|
|
63
|
+
if (options.engine !== void 0 && options.engine !== "auto" && options.engine !== "mock" && options.engine !== "native") throw new VitestNativeTypeError("INVALID_OPTION", `"engine" must be "auto", "mock", or "native".`);
|
|
64
|
+
if (options.platform !== void 0 && options.platform !== "ios" && options.platform !== "android") throw new VitestNativeTypeError("INVALID_OPTION", `"platform" must be "ios" or "android".`);
|
|
65
|
+
if (options.projectBabel !== void 0 && options.projectBabel !== "auto" && options.projectBabel !== "always" && options.projectBabel !== "never") throw new VitestNativeTypeError("INVALID_OPTION", `"projectBabel" must be "auto", "always", or "never".`);
|
|
66
|
+
if (options.registryBuild !== void 0 && options.registryBuild !== "background" && options.registryBuild !== "wait") throw new VitestNativeTypeError("INVALID_OPTION", `"registryBuild" must be "background" or "wait".`);
|
|
67
|
+
if (options.hangTimeout !== void 0 && options.hangTimeout !== false && !(typeof options.hangTimeout === "number" && Number.isFinite(options.hangTimeout) && options.hangTimeout > 0 && options.hangTimeout <= 2147483647)) throw new VitestNativeTypeError("INVALID_OPTION", `"hangTimeout" must be a positive number of milliseconds (at most 2147483647), or false.`);
|
|
68
|
+
if (options.nativeModules !== void 0 && options.nativeModules !== "device" && options.nativeModules !== "permissive") throw new VitestNativeTypeError("INVALID_OPTION", `"nativeModules" must be "device" or "permissive".`);
|
|
69
|
+
if (options.ownership !== void 0) validateOwnership(options.ownership);
|
|
70
|
+
if (options.experimental !== void 0) {
|
|
71
|
+
const experimental = options.experimental;
|
|
72
|
+
if (experimental === null || Array.isArray(experimental) || typeof experimental !== "object") throw new VitestNativeTypeError("INVALID_OPTION", `"experimental" must be an object.`);
|
|
73
|
+
const entries = experimental;
|
|
74
|
+
const unknown = Object.keys(entries).filter((key) => !KNOWN_EXPERIMENTAL_OPTIONS.includes(key));
|
|
75
|
+
if (unknown.length > 0) throw new VitestNativeTypeError("UNKNOWN_OPTION", `Unknown experimental option "${unknown[0]}". Valid options: ${KNOWN_EXPERIMENTAL_OPTIONS.join(", ")}.`);
|
|
76
|
+
if (entries.ownershipModel !== void 0 && entries.ownershipModel !== "resolver" && entries.ownershipModel !== "resolution") throw new VitestNativeTypeError("INVALID_OPTION", `"experimental.ownershipModel" must be "resolver" or "resolution".`);
|
|
77
|
+
if (entries.nodeMocks !== void 0 && typeof entries.nodeMocks !== "boolean") throw new VitestNativeTypeError("INVALID_OPTION", `"experimental.nodeMocks" must be a boolean.`);
|
|
78
|
+
if (entries.ownershipModel === "resolution" && entries.nodeMocks === false) throw new VitestNativeTypeError("INVALID_OPTION", "\"experimental.ownershipModel\": \"resolution\" turns \"experimental.nodeMocks\" on, and cannot run with it set to false. Remove \"nodeMocks: false\", or use \"ownershipModel\": \"resolver\".");
|
|
79
|
+
}
|
|
80
|
+
if (options.diagnostics !== void 0 && typeof options.diagnostics !== "boolean") throw new VitestNativeTypeError("INVALID_OPTION", `"diagnostics" must be a boolean.`);
|
|
81
|
+
if (options.assetExts !== void 0) assertStringArray(options.assetExts, "assetExts");
|
|
82
|
+
if (options.metroConfig !== void 0 && typeof options.metroConfig !== "boolean") {
|
|
83
|
+
if (options.metroConfig === null || Array.isArray(options.metroConfig) || typeof options.metroConfig !== "object") throw new VitestNativeTypeError("INVALID_OPTION", `"metroConfig" must be a boolean or an options object.`);
|
|
84
|
+
const metro = options.metroConfig;
|
|
85
|
+
const unknown = Object.keys(metro).filter((key) => !KNOWN_METRO_CONFIG_OPTIONS.includes(key));
|
|
86
|
+
if (unknown.length > 0) throw new VitestNativeTypeError("UNKNOWN_OPTION", `Unknown metroConfig option "${unknown[0]}". Valid options: ${KNOWN_METRO_CONFIG_OPTIONS.join(", ")}.`);
|
|
87
|
+
if (metro.configFile !== void 0 && (typeof metro.configFile !== "string" || !metro.configFile.trim())) throw new VitestNativeTypeError("INVALID_OPTION", `"metroConfig.configFile" must be a non-empty string.`);
|
|
88
|
+
}
|
|
89
|
+
if (options.transform !== void 0) {
|
|
90
|
+
if (Array.isArray(options.transform)) assertStringArray(options.transform, "transform");
|
|
91
|
+
else if (options.transform !== null && typeof options.transform === "object") {
|
|
92
|
+
const shape = options.transform;
|
|
93
|
+
const unknownKeys = Object.keys(shape).filter((k) => k !== "include" && k !== "exclude");
|
|
94
|
+
if (unknownKeys.length > 0) throw new VitestNativeTypeError("INVALID_OPTION", `"transform" accepts only "include" and "exclude"; received ${unknownKeys.map((k) => `"${k}"`).join(", ")}.`);
|
|
95
|
+
if (shape.include !== void 0) assertStringArray(shape.include, "transform.include");
|
|
96
|
+
if (shape.exclude !== void 0) assertStringArray(shape.exclude, "transform.exclude");
|
|
97
|
+
} else throw new VitestNativeTypeError("INVALID_OPTION", `"transform" must be an array of package names, or an object with "include" and/or "exclude".`);
|
|
98
|
+
}
|
|
99
|
+
if (options.presets !== void 0 && !Array.isArray(options.presets)) {
|
|
100
|
+
if (!(options.presets !== null && typeof options.presets === "object" && Object.values(options.presets).every((v) => typeof v === "boolean"))) throw new VitestNativeTypeError("INVALID_OPTION", "\"presets\" must be an array of presets, or an object of booleans to switch auto-detected presets off (for example { navigation: false }).");
|
|
101
|
+
}
|
|
102
|
+
if (options.mocks !== void 0 && (options.mocks === null || Array.isArray(options.mocks) || typeof options.mocks !== "object")) throw new VitestNativeTypeError("INVALID_OPTION", `"mocks" must be a plain object.`);
|
|
103
|
+
const hotRuntime = options.hotRuntime;
|
|
104
|
+
if (hotRuntime === void 0 || typeof hotRuntime === "boolean" || hotRuntime === "auto") return;
|
|
105
|
+
if (hotRuntime === null || Array.isArray(hotRuntime) || typeof hotRuntime !== "object") throw new VitestNativeTypeError("INVALID_OPTION", `"hotRuntime" must be a boolean, "auto", or an options object.`);
|
|
106
|
+
const hotOptions = hotRuntime;
|
|
107
|
+
for (const key of Object.keys(hotOptions)) if (!KNOWN_HOT_RUNTIME_OPTIONS.includes(key)) {
|
|
108
|
+
const suggestion = findClosest(key, KNOWN_HOT_RUNTIME_OPTIONS);
|
|
109
|
+
throw new VitestNativeTypeError("UNKNOWN_OPTION", `Unknown hotRuntime option "${key}".` + (suggestion ? ` Did you mean '${suggestion}'?` : "") + ` Valid options: ${KNOWN_HOT_RUNTIME_OPTIONS.join(", ")}.`);
|
|
110
|
+
}
|
|
111
|
+
if (hotOptions.mode !== void 0 && hotOptions.mode !== "auto") throw new VitestNativeTypeError("INVALID_OPTION", `"hotRuntime.mode" must be "auto", or left out to require the hot runtime.`);
|
|
112
|
+
if (hotOptions.mode === "auto" && hotOptions.allowUnboundedMemory === true) throw new VitestNativeTypeError("INVALID_OPTION", "\"hotRuntime.allowUnboundedMemory\" cannot be combined with mode: \"auto\", which keeps per-file isolation where memory cannot be bounded. Leave out mode to require the hot runtime with unbounded memory.");
|
|
113
|
+
if (hotOptions.recycleAfterFiles !== void 0) assertNonNegativeInteger(hotOptions.recycleAfterFiles, "hotRuntime.recycleAfterFiles");
|
|
114
|
+
if (hotOptions.memoryLimit !== void 0) assertNonNegativeInteger(hotOptions.memoryLimit, "hotRuntime.memoryLimit");
|
|
115
|
+
if (hotOptions.allowUnboundedMemory !== void 0 && typeof hotOptions.allowUnboundedMemory !== "boolean") throw new VitestNativeTypeError("INVALID_OPTION", `"hotRuntime.allowUnboundedMemory" must be a boolean.`);
|
|
116
|
+
if (hotOptions.preserveGlobals !== void 0) assertStringArray(hotOptions.preserveGlobals, "hotRuntime.preserveGlobals");
|
|
117
|
+
if (hotOptions.esmGeneration !== void 0 && typeof hotOptions.esmGeneration !== "boolean") throw new VitestNativeTypeError("INVALID_OPTION", `"hotRuntime.esmGeneration" must be a boolean.`);
|
|
118
|
+
}
|
|
119
|
+
function satisfiesMinimum(version, minimum) {
|
|
120
|
+
const parse = (v) => v.replace(/^[^0-9]*/, "").split(/[-+]/)[0].split(".").map(Number);
|
|
121
|
+
const [aMaj, aMin = 0, aPat = 0] = parse(version);
|
|
122
|
+
const [bMaj, bMin = 0, bPat = 0] = parse(minimum);
|
|
123
|
+
if (aMaj !== bMaj) return aMaj > bMaj;
|
|
124
|
+
if (aMin !== bMin) return aMin > bMin;
|
|
125
|
+
return aPat >= bPat;
|
|
126
|
+
}
|
|
127
|
+
function validatePeerDependency(pkgName, minimumVersion, projectRoot, maximumMajorExclusive, runningVersion, runningSource) {
|
|
128
|
+
const req = createRequire(path.join(projectRoot, "package.json"));
|
|
129
|
+
try {
|
|
130
|
+
const version = runningVersion ?? req(req.resolve(`${pkgName}/package.json`)).version;
|
|
131
|
+
const major = Number(version.replace(/^[^0-9]*/, "").split(".")[0]);
|
|
132
|
+
const range = maximumMajorExclusive === void 0 ? `>= ${minimumVersion}` : `>= ${minimumVersion} and < ${maximumMajorExclusive}`;
|
|
133
|
+
if (!satisfiesMinimum(version, minimumVersion)) return `vitest-native requires ${pkgName} ${range}, but found ${version}${runningVersion && runningSource ? ` (${runningSource})` : ""}. Upgrade ${pkgName} to ${minimumVersion} or later.`;
|
|
134
|
+
if (maximumMajorExclusive !== void 0 && major >= maximumMajorExclusive) return `vitest-native supports ${pkgName} ${range}, but found ${version}.`;
|
|
135
|
+
return null;
|
|
136
|
+
} catch {
|
|
137
|
+
return `vitest-native requires ${pkgName} >= ${minimumVersion}, but it was not found. Please install it.`;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
function warnUnknownOptions(options) {
|
|
141
|
+
for (const key of Object.keys(options)) if (!KNOWN_OPTIONS.includes(key)) {
|
|
142
|
+
const suggestion = findClosest(key, KNOWN_OPTIONS);
|
|
143
|
+
const hint = suggestion ? ` Did you mean '${suggestion}'?` : "";
|
|
144
|
+
console.warn(`[vitest-native] Unknown option '${key}'.${hint}`);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
function findClosest(input, candidates) {
|
|
148
|
+
let best = null;
|
|
149
|
+
let bestDist = Infinity;
|
|
150
|
+
for (const c of candidates) {
|
|
151
|
+
const d = levenshtein(input.toLowerCase(), c.toLowerCase());
|
|
152
|
+
if (d < bestDist && d <= 3) {
|
|
153
|
+
bestDist = d;
|
|
154
|
+
best = c;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
return best;
|
|
158
|
+
}
|
|
159
|
+
function levenshtein(a, b) {
|
|
160
|
+
const m = a.length;
|
|
161
|
+
const n = b.length;
|
|
162
|
+
const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
|
|
163
|
+
for (let i = 0; i <= m; i++) dp[i][0] = i;
|
|
164
|
+
for (let j = 0; j <= n; j++) dp[0][j] = j;
|
|
165
|
+
for (let i = 1; i <= m; i++) for (let j = 1; j <= n; j++) dp[i][j] = a[i - 1] === b[j - 1] ? dp[i - 1][j - 1] : 1 + Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]);
|
|
166
|
+
return dp[m][n];
|
|
167
|
+
}
|
|
168
|
+
// src/peer-requirements.ts
|
|
169
|
+
const PEER_REQUIREMENTS = [
|
|
170
|
+
{
|
|
171
|
+
name: "vitest",
|
|
172
|
+
minimum: "5.0.0",
|
|
173
|
+
maximumMajor: 6
|
|
174
|
+
},
|
|
175
|
+
{
|
|
176
|
+
name: "vite",
|
|
177
|
+
minimum: "8.0.5",
|
|
178
|
+
maximumMajor: 9
|
|
179
|
+
},
|
|
180
|
+
{
|
|
181
|
+
name: "react",
|
|
182
|
+
minimum: "19.0.0"
|
|
183
|
+
},
|
|
184
|
+
{
|
|
185
|
+
name: "@testing-library/react-native",
|
|
186
|
+
minimum: "13.0.0",
|
|
187
|
+
maximumMajor: 15,
|
|
188
|
+
optional: true
|
|
189
|
+
}
|
|
190
|
+
];
|
|
191
|
+
/**
|
|
192
|
+
* The Expo SDKs this release supports: the ones CI installs as packed Expo apps (SDK 57
|
|
193
|
+
* and 58). Expo is not a peer of this package, so it is not in PEER_REQUIREMENTS, but the
|
|
194
|
+
* plugin's startup check and doctor read the range from here, as they do the peers'.
|
|
195
|
+
*/
|
|
196
|
+
const SUPPORTED_EXPO_SDKS = {
|
|
197
|
+
minimum: 57,
|
|
198
|
+
maximum: 58
|
|
199
|
+
};
|
|
200
|
+
/** The SDKs from `minimum` to `maximum` as a list: "57 and 58", "57, 58 or 59". */
|
|
201
|
+
function expoSdkList(conjunction, { minimum, maximum } = SUPPORTED_EXPO_SDKS) {
|
|
202
|
+
const sdks = [];
|
|
203
|
+
for (let sdk = minimum; sdk <= maximum; sdk++) sdks.push(sdk);
|
|
204
|
+
return sdks.length === 1 ? String(sdks[0]) : `${sdks.slice(0, -1).join(", ")} ${conjunction} ${sdks.at(-1)}`;
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* The version in the `expo/package.json` Node resolves from `dir`, or null. Where expo's
|
|
208
|
+
* `exports` leaves its manifest out, the package directory Node would load `expo` from,
|
|
209
|
+
* found along Node's own lookup paths.
|
|
210
|
+
*/
|
|
211
|
+
function expoVersionFrom(dir) {
|
|
212
|
+
const req = createRequire(path.join(dir, "package.json"));
|
|
213
|
+
let manifest;
|
|
214
|
+
try {
|
|
215
|
+
manifest = req.resolve("expo/package.json");
|
|
216
|
+
} catch (error) {
|
|
217
|
+
if (error.code !== "ERR_PACKAGE_PATH_NOT_EXPORTED") return null;
|
|
218
|
+
manifest = (req.resolve.paths("expo") ?? []).map((modules) => path.join(modules, "expo", "package.json")).find((file) => fs.existsSync(file));
|
|
219
|
+
}
|
|
220
|
+
if (!manifest) return null;
|
|
221
|
+
try {
|
|
222
|
+
const { version } = JSON.parse(fs.readFileSync(manifest, "utf8"));
|
|
223
|
+
return typeof version === "string" ? version : null;
|
|
224
|
+
} catch {
|
|
225
|
+
return null;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* The version of the `expo` the project at `root` uses, or null: the one Node resolves from
|
|
230
|
+
* `root`, else the one a dependency the project declares resolves as its peer. A workspace
|
|
231
|
+
* library that declares only expo-image reaches `expo` that way under an isolated install
|
|
232
|
+
* (pnpm links the peer beside expo-image, not into the library), and a library that uses
|
|
233
|
+
* no Expo package resolves none, whatever another workspace member installs. The plugin
|
|
234
|
+
* and doctor both read it from here.
|
|
235
|
+
*/
|
|
236
|
+
function installedExpoVersion(root) {
|
|
237
|
+
const own = expoVersionFrom(root);
|
|
238
|
+
if (own) return own;
|
|
239
|
+
let manifest;
|
|
240
|
+
try {
|
|
241
|
+
manifest = JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8"));
|
|
242
|
+
} catch {
|
|
243
|
+
return null;
|
|
244
|
+
}
|
|
245
|
+
const req = createRequire(path.join(root, "package.json"));
|
|
246
|
+
for (const field of ["dependencies", "devDependencies"]) {
|
|
247
|
+
const deps = manifest[field];
|
|
248
|
+
if (!deps || typeof deps !== "object") continue;
|
|
249
|
+
for (const name of Object.keys(deps)) try {
|
|
250
|
+
const file = req.resolve(`${name}/package.json`);
|
|
251
|
+
const dep = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
252
|
+
const peers = dep.peerDependencies;
|
|
253
|
+
if (!peers || typeof peers !== "object" || !("expo" in peers)) continue;
|
|
254
|
+
if (dep.peerDependenciesMeta?.expo?.optional === true) continue;
|
|
255
|
+
const version = expoVersionFrom(path.dirname(file));
|
|
256
|
+
if (version) return version;
|
|
257
|
+
} catch {}
|
|
258
|
+
}
|
|
259
|
+
return null;
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* Why the installed Expo SDK is not supported, or null when it is, or when the version is
|
|
263
|
+
* not one this can read. A warning, not an error: an Expo app on an older SDK mostly runs,
|
|
264
|
+
* and failing it at startup would stop the tests that do.
|
|
265
|
+
*/
|
|
266
|
+
function unsupportedExpoSdkMessage(expoVersion) {
|
|
267
|
+
const match = /^(\d+)\.\d+\.\d+(?:[-+].*)?$/.exec(expoVersion);
|
|
268
|
+
if (!match) return null;
|
|
269
|
+
const sdk = Number(match[1]);
|
|
270
|
+
const { minimum, maximum } = SUPPORTED_EXPO_SDKS;
|
|
271
|
+
if (sdk >= minimum && sdk <= maximum) return null;
|
|
272
|
+
const supported = `vitest-native supports Expo SDK ${expoSdkList("and")}`;
|
|
273
|
+
return sdk < minimum ? `Expo SDK ${sdk} (expo ${expoVersion}) is not supported: ${supported}. Upgrade to Expo SDK ${expoSdkList("or")}; on an older SDK, tests that load Expo modules can fail.` : `Expo SDK ${sdk} (expo ${expoVersion}) is newer than this release supports: ${supported}. Check for a newer vitest-native.`;
|
|
274
|
+
}
|
|
275
|
+
/**
|
|
276
|
+
* The React Native releases the native engine supports: 0.86 (Expo SDK 57's) to 0.88, the
|
|
277
|
+
* rows of the CI matrix (.github/rn-matrix.json). Below the floor the native engine stops
|
|
278
|
+
* with UNSUPPORTED_PEER; a newer minor only warns. The mock engine reimplements React
|
|
279
|
+
* Native and does not load it, so the range does not apply there.
|
|
280
|
+
*/
|
|
281
|
+
const SUPPORTED_REACT_NATIVE = {
|
|
282
|
+
minimumMinor: 86,
|
|
283
|
+
maximumMinor: 88
|
|
284
|
+
};
|
|
285
|
+
/** The minor of a 0.x React Native version ("0.86.3" → 86), or null. */
|
|
286
|
+
function reactNativeMinorOf(version) {
|
|
287
|
+
const match = /^0\.(\d+)\.\d+(?:[-+].*)?$/.exec(version);
|
|
288
|
+
return match ? Number(match[1]) : null;
|
|
289
|
+
}
|
|
290
|
+
/** Whether a React Native version is older than the supported range. */
|
|
291
|
+
function isBelowSupportedReactNative(version) {
|
|
292
|
+
const minor = reactNativeMinorOf(version);
|
|
293
|
+
return minor !== null && minor < SUPPORTED_REACT_NATIVE.minimumMinor;
|
|
294
|
+
}
|
|
295
|
+
/** Why a React Native version is outside the supported range, or null. */
|
|
296
|
+
function unsupportedReactNativeMessage(version) {
|
|
297
|
+
const minor = reactNativeMinorOf(version);
|
|
298
|
+
if (minor === null) return null;
|
|
299
|
+
const { minimumMinor, maximumMinor } = SUPPORTED_REACT_NATIVE;
|
|
300
|
+
if (minor >= minimumMinor && minor <= maximumMinor) return null;
|
|
301
|
+
const supported = `the native engine supports react-native 0.${minimumMinor}–0.${maximumMinor}`;
|
|
302
|
+
return minor < minimumMinor ? `react-native ${version} is not supported: ${supported}. Upgrade react-native to 0.${minimumMinor} or later (Expo SDK ${SUPPORTED_EXPO_SDKS.minimum} or later).` : `react-native ${version} is newer than this release supports: ${supported}. Check for a newer vitest-native.`;
|
|
303
|
+
}
|
|
304
|
+
// src/node-range.ts
|
|
305
|
+
/**
|
|
306
|
+
* The Node versions this package runs on: `engines.node`, which a test holds this
|
|
307
|
+
* constant to. Each line starts where Node's in-thread module hooks
|
|
308
|
+
* (`module.registerHooks`) carry the engine. Before 22.22.3 and 24.12 they fail it
|
|
309
|
+
* (expo-router's elements do not load, and the hot runtime's CommonJS reset stops
|
|
310
|
+
* mattering). Lines from 26 on are admitted, and added to CI as they ship.
|
|
311
|
+
*/
|
|
312
|
+
const SUPPORTED_NODE = ">=22.22.3 <23 || >=24.12.0 <25 || >=26.0.0";
|
|
313
|
+
/** Each supported line's first release, for the message on a release below it. */
|
|
314
|
+
const LINE_FLOORS = {
|
|
315
|
+
22: "22.22.3",
|
|
316
|
+
24: "24.12.0"
|
|
317
|
+
};
|
|
318
|
+
const versionParts = (version) => {
|
|
319
|
+
const [major = 0, minor = 0, patch = 0] = version.replace(/^v/, "").split(/[.-]/).map((part) => Number.parseInt(part, 10) || 0);
|
|
320
|
+
return [
|
|
321
|
+
major,
|
|
322
|
+
minor,
|
|
323
|
+
patch
|
|
324
|
+
];
|
|
325
|
+
};
|
|
326
|
+
const compareVersions = (a, b) => {
|
|
327
|
+
const [x, y] = [versionParts(a), versionParts(b)];
|
|
328
|
+
return x[0] - y[0] || x[1] - y[1] || x[2] - y[2];
|
|
329
|
+
};
|
|
330
|
+
/** A prerelease (`22.22.3-rc.1`) comes before its release, as in semver. */
|
|
331
|
+
const isPrerelease = (version) => /^v?\d+\.\d+\.\d+-/.test(version);
|
|
332
|
+
/**
|
|
333
|
+
* Whether `version` is in `range`: `||`-separated sets of space-separated comparators
|
|
334
|
+
* (`>=`, `>`, `<=`, `<`, `=`), the forms `engines.node` uses. A version missing parts
|
|
335
|
+
* reads them as 0 (`<23` is `<23.0.0`). A prerelease compares below its release, so
|
|
336
|
+
* `22.22.3-rc.1` is not `>=22.22.3`.
|
|
337
|
+
*/
|
|
338
|
+
function satisfiesNodeRange(version, range) {
|
|
339
|
+
return range.split("||").some((set) => set.trim().split(/\s+/).filter(Boolean).every((comparator) => {
|
|
340
|
+
const match = /^(>=|<=|>|<|=)?\s*v?(\d[\w.-]*)$/.exec(comparator);
|
|
341
|
+
if (!match) return false;
|
|
342
|
+
let order = compareVersions(version, match[2]);
|
|
343
|
+
if (order === 0 && isPrerelease(version) && !isPrerelease(match[2])) order = -1;
|
|
344
|
+
switch (match[1] ?? "=") {
|
|
345
|
+
case ">=": return order >= 0;
|
|
346
|
+
case ">": return order > 0;
|
|
347
|
+
case "<=": return order <= 0;
|
|
348
|
+
case "<": return order < 0;
|
|
349
|
+
default: return order === 0;
|
|
350
|
+
}
|
|
351
|
+
}));
|
|
352
|
+
}
|
|
353
|
+
/** Why `version` is unsupported, and what to install instead. */
|
|
354
|
+
function unsupportedNodeMessage(version) {
|
|
355
|
+
const major = versionParts(version)[0];
|
|
356
|
+
const floor = LINE_FLOORS[major];
|
|
357
|
+
if (floor !== void 0) return `Node ${version} is not supported: vitest-native needs Node ${floor} or later on Node ${major}. An update within your Node major is enough, for example \`nvm install ${major}\`.`;
|
|
358
|
+
return `Node ${version} is not supported. vitest-native runs on Node 22.22.3 or later on Node 22, 24.12.0 or later on Node 24, or Node 26 and later (engines.node: ${SUPPORTED_NODE}).`;
|
|
359
|
+
}
|
|
360
|
+
/** Fail at startup, by name, on a Node this package does not run on. */
|
|
361
|
+
function assertSupportedNode(version = process.versions.node) {
|
|
362
|
+
if (satisfiesNodeRange(version, ">=22.22.3 <23 || >=24.12.0 <25 || >=26.0.0")) return;
|
|
363
|
+
throw new VitestNativeError("UNSUPPORTED_NODE", unsupportedNodeMessage(version));
|
|
364
|
+
}
|
|
365
|
+
// src/fs-module-cache.ts
|
|
366
|
+
/**
|
|
367
|
+
* Vitest's persistent transform cache (`fsModuleCache`), keyed for what this plugin
|
|
368
|
+
* contributes.
|
|
369
|
+
*
|
|
370
|
+
* Vitest 5 can keep transformed modules on disk between runs, as Jest keeps its
|
|
371
|
+
* transform cache. Measured on a 104-file production Expo suite, it cut warm runs by
|
|
372
|
+
* about 11%. Vitest keys each entry on the module's id and source, the config file's
|
|
373
|
+
* contents, the plugin NAMES, `resolve`, NODE_ENV and its own version — not on plugin
|
|
374
|
+
* versions, nor on anything a plugin reads from disk. This plugin's output depends on
|
|
375
|
+
* both: its own version, and the installed packages (which presets are detected, which
|
|
376
|
+
* packages compile). Vitest's official extension point, a cache key generator, carries
|
|
377
|
+
* that part of the key:
|
|
378
|
+
* - the vitest-native version,
|
|
379
|
+
* - the plugin's resolved options and the environment it hands to workers,
|
|
380
|
+
* - the project's lockfile(s), so any dependency change invalidates the cache;
|
|
381
|
+
* - the project's root Babel config, which `projectBabel` compiles project source with.
|
|
382
|
+
* Without a lockfile the root package.json stands in for it.
|
|
383
|
+
*/
|
|
384
|
+
const LOCKFILES = [
|
|
385
|
+
"bun.lock",
|
|
386
|
+
"bun.lockb",
|
|
387
|
+
"package-lock.json",
|
|
388
|
+
"npm-shrinkwrap.json",
|
|
389
|
+
"pnpm-lock.yaml",
|
|
390
|
+
"yarn.lock"
|
|
391
|
+
];
|
|
392
|
+
const sha1 = (value) => createHash("sha1").update(value).digest("hex");
|
|
393
|
+
/** A digest of the nearest lockfiles at or above `root`, else of its package.json. */
|
|
394
|
+
function dependencyFingerprint(root) {
|
|
395
|
+
for (let dir = path.resolve(root);; dir = path.dirname(dir)) {
|
|
396
|
+
const found = LOCKFILES.map((name) => path.join(dir, name)).filter((file) => fs.existsSync(file));
|
|
397
|
+
if (found.length > 0) {
|
|
398
|
+
const hash = createHash("sha1");
|
|
399
|
+
for (const file of found) hash.update(file).update(fs.readFileSync(file));
|
|
400
|
+
return hash.digest("hex");
|
|
401
|
+
}
|
|
402
|
+
if (path.dirname(dir) === dir) break;
|
|
403
|
+
}
|
|
404
|
+
try {
|
|
405
|
+
return sha1(fs.readFileSync(path.join(root, "package.json")));
|
|
406
|
+
} catch {
|
|
407
|
+
return "no-manifest";
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
/** The version of the package rooted at `packageDir`. */
|
|
411
|
+
function packageVersionAt(packageDir) {
|
|
412
|
+
try {
|
|
413
|
+
const manifest = JSON.parse(fs.readFileSync(path.join(packageDir, "package.json"), "utf8"));
|
|
414
|
+
return typeof manifest.version === "string" ? manifest.version : "unknown";
|
|
415
|
+
} catch {
|
|
416
|
+
return "unknown";
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
/** This plugin's contribution to a module's cache key in one project. */
|
|
420
|
+
function fsModuleCacheKey(ownPackageDir, projectRoot, pluginState) {
|
|
421
|
+
const state = JSON.stringify(pluginState, (_key, value) => typeof value === "function" || value instanceof RegExp ? String(value) : value);
|
|
422
|
+
return sha1(`vitest-native@${packageVersionAt(ownPackageDir)}\0${dependencyFingerprint(projectRoot)}\0${babelConfigFingerprint(projectRoot)}\0${state}`);
|
|
423
|
+
}
|
|
424
|
+
/**
|
|
425
|
+
* Whether to turn the cache on: the user has not chosen either way, in either spelling
|
|
426
|
+
* (`test.fsModuleCache`, or `test.experimental.fsModuleCache` carried over from a
|
|
427
|
+
* Vitest 4 config).
|
|
428
|
+
*/
|
|
429
|
+
function shouldDefaultFsModuleCache(userTest) {
|
|
430
|
+
return userTest?.fsModuleCache === void 0 && userTest?.experimental?.fsModuleCache === void 0;
|
|
431
|
+
}
|
|
432
|
+
const CONFIG_FILES = [
|
|
433
|
+
"babel.config.js",
|
|
434
|
+
"babel.config.cjs",
|
|
435
|
+
"babel.config.mjs",
|
|
436
|
+
"babel.config.json",
|
|
437
|
+
"babel.config.cts",
|
|
438
|
+
"babel.config.ts",
|
|
439
|
+
".babelrc",
|
|
440
|
+
".babelrc.js",
|
|
441
|
+
".babelrc.cjs",
|
|
442
|
+
".babelrc.mjs",
|
|
443
|
+
".babelrc.json"
|
|
444
|
+
];
|
|
445
|
+
/** The project's root Babel config, by file name (or `package.json#babel`), or null. */
|
|
446
|
+
function rootBabelConfigFile(root) {
|
|
447
|
+
const found = CONFIG_FILES.find((name) => fs.existsSync(path.join(root, name)));
|
|
448
|
+
if (found) return found;
|
|
449
|
+
const manifestFile = path.join(root, "package.json");
|
|
450
|
+
if (!fs.existsSync(manifestFile)) return null;
|
|
451
|
+
return JSON.parse(fs.readFileSync(manifestFile, "utf8")).babel !== void 0 ? "package.json#babel" : null;
|
|
452
|
+
}
|
|
453
|
+
/**
|
|
454
|
+
* A digest of the project's root Babel config (its files, and package.json's `babel`
|
|
455
|
+
* field), so editing it invalidates Vitest's transform cache. A `.babelrc` in a
|
|
456
|
+
* subdirectory is not covered.
|
|
457
|
+
*/
|
|
458
|
+
function babelConfigFingerprint(root) {
|
|
459
|
+
const hash = createHash("sha1");
|
|
460
|
+
for (const name of CONFIG_FILES) {
|
|
461
|
+
const file = path.join(root, name);
|
|
462
|
+
if (fs.existsSync(file)) hash.update(name).update(fs.readFileSync(file));
|
|
463
|
+
}
|
|
464
|
+
const manifestFile = path.join(root, "package.json");
|
|
465
|
+
if (fs.existsSync(manifestFile)) {
|
|
466
|
+
const manifest = JSON.parse(fs.readFileSync(manifestFile, "utf8"));
|
|
467
|
+
if (manifest.babel !== void 0) hash.update(JSON.stringify(manifest.babel));
|
|
468
|
+
}
|
|
469
|
+
return hash.digest("hex");
|
|
470
|
+
}
|
|
471
|
+
/**
|
|
472
|
+
* The native engine's dependencies that do NOT resolve from the project root.
|
|
473
|
+
*
|
|
474
|
+
* react-native itself is part of the check: the Babel toolchain alone chose
|
|
475
|
+
* native mode in a project with the preset installed but no react-native — an
|
|
476
|
+
* incomplete install, a babel-only workspace — which then failed later at RN
|
|
477
|
+
* resolution with nothing pointing at the cause. Resolution, not declaration:
|
|
478
|
+
* every check walks node_modules upward from the root — so a hoisted workspace
|
|
479
|
+
* install or Expo's transitive react-native counts, and a project does not need
|
|
480
|
+
* react-native in its own manifest.
|
|
481
|
+
*/
|
|
482
|
+
function missingNativeDeps(projectRoot) {
|
|
483
|
+
const req = createRequire(path.join(projectRoot, "package.json"));
|
|
484
|
+
const missing = [];
|
|
485
|
+
if (!reactNativeInstalledNear(projectRoot)) missing.push("react-native");
|
|
486
|
+
if (resolveTransformPreset(projectRoot) === null) missing.push("@react-native/babel-preset");
|
|
487
|
+
try {
|
|
488
|
+
req.resolve("@babel/core");
|
|
489
|
+
} catch {
|
|
490
|
+
missing.push("@babel/core");
|
|
491
|
+
}
|
|
492
|
+
return missing;
|
|
493
|
+
}
|
|
494
|
+
/** Does node_modules/react-native exist in projectRoot or any ancestor? */
|
|
495
|
+
function reactNativeInstalledNear(projectRoot) {
|
|
496
|
+
let dir = path.resolve(projectRoot);
|
|
497
|
+
for (;;) {
|
|
498
|
+
if (fs.existsSync(path.join(dir, "node_modules", "react-native", "package.json"))) return true;
|
|
499
|
+
const parent = path.dirname(dir);
|
|
500
|
+
if (parent === dir) return false;
|
|
501
|
+
dir = parent;
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
/** Resolve the concrete engine for a run. Pure; never throws. */
|
|
505
|
+
function detectEngine(requested, projectRoot, opts) {
|
|
506
|
+
const missing = missingNativeDeps(projectRoot);
|
|
507
|
+
const nativeAvailable = missing.length === 0;
|
|
508
|
+
if (requested === "native") return {
|
|
509
|
+
engine: "native",
|
|
510
|
+
nativeAvailable,
|
|
511
|
+
missing,
|
|
512
|
+
notice: null
|
|
513
|
+
};
|
|
514
|
+
if (requested === "mock") return {
|
|
515
|
+
engine: "mock",
|
|
516
|
+
nativeAvailable,
|
|
517
|
+
missing,
|
|
518
|
+
notice: null
|
|
519
|
+
};
|
|
520
|
+
const prefersNative = opts?.autoPrefersNative ?? true;
|
|
521
|
+
if (prefersNative && nativeAvailable) return {
|
|
522
|
+
engine: "native",
|
|
523
|
+
nativeAvailable,
|
|
524
|
+
missing,
|
|
525
|
+
notice: null
|
|
526
|
+
};
|
|
527
|
+
if (prefersNative) return {
|
|
528
|
+
engine: "mock",
|
|
529
|
+
nativeAvailable: false,
|
|
530
|
+
missing,
|
|
531
|
+
notice: `[vitest-native] ${missing.join(", ")} not found — using the mock engine. Install what's missing to run real React Native, or set engine:'mock' to silence this.`
|
|
532
|
+
};
|
|
533
|
+
return {
|
|
534
|
+
engine: "mock",
|
|
535
|
+
nativeAvailable,
|
|
536
|
+
missing,
|
|
537
|
+
notice: null
|
|
538
|
+
};
|
|
539
|
+
}
|
|
540
|
+
// src/installed-manifest.ts
|
|
541
|
+
/**
|
|
542
|
+
* A package's manifest as the package manager wrote it (see cli/manifest.ts for why
|
|
543
|
+
* this reads the file instead of resolving it).
|
|
544
|
+
*/
|
|
545
|
+
/** A package's manifest, found by walking node_modules upward from root, or null. */
|
|
546
|
+
function installedManifest(root, pkg) {
|
|
547
|
+
for (let dir = path.resolve(root);; dir = path.dirname(dir)) {
|
|
548
|
+
const file = path.join(dir, "node_modules", pkg, "package.json");
|
|
549
|
+
if (fs.existsSync(file)) try {
|
|
550
|
+
return JSON.parse(fs.readFileSync(file, "utf8"));
|
|
551
|
+
} catch {
|
|
552
|
+
return null;
|
|
553
|
+
}
|
|
554
|
+
if (path.dirname(dir) === dir) return null;
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
// src/babel-plugins.ts
|
|
558
|
+
/**
|
|
559
|
+
* Babel plugin classification shared by the engine (projectBabel) and the CLI (doctor,
|
|
560
|
+
* migrate): what a project's Babel plugins do under vitest-native.
|
|
561
|
+
*/
|
|
562
|
+
/**
|
|
563
|
+
* @babel/core's `standardizeName` (lib/config/files/plugins.js), rule for rule except that a name
|
|
564
|
+
* starting with `.` is taken as a relative path: `foo` →
|
|
565
|
+
* `babel-plugin-foo`, `@babel/foo` → `@babel/plugin-foo` (`@babel/plugin-foo` unchanged),
|
|
566
|
+
* `@scope/foo` → `@scope/babel-plugin-foo`, `@scope` → `@scope/babel-plugin`, `module:foo` →
|
|
567
|
+
* `foo`. A relative or absolute path is returned as written.
|
|
568
|
+
*/
|
|
569
|
+
function normalizeBabelName(name, kind = "plugin") {
|
|
570
|
+
if (name.startsWith(".") || path.isAbsolute(name)) return name;
|
|
571
|
+
const prefix = new RegExp(`^(?!@|module:|[^/]+/|babel-${kind}-)`);
|
|
572
|
+
const babelOrg = new RegExp(`^(@babel/)(?!${kind}-|[^/]+/)`);
|
|
573
|
+
const otherOrg = new RegExp(`^(@(?!babel/)[^/]+/)(?![^/]*babel-${kind}(?:-|/|$)|[^/]+/)`);
|
|
574
|
+
return name.replace(prefix, `babel-${kind}-`).replace(babelOrg, `$1${kind}-`).replace(otherOrg, `$1babel-${kind}-`).replace(/^(@(?!babel$)[^/]+)$/, `$1/babel-${kind}`).replace(/^module:/, "");
|
|
575
|
+
}
|
|
576
|
+
/**
|
|
577
|
+
* Whether the generated config runs Reanimated as its own mock: the native engine (as
|
|
578
|
+
* `engine: 'auto'` resolves it) with Reanimated 4.7+ and Worklets 0.9+ (libraryMockUsable).
|
|
579
|
+
* That mock runs Reanimated's real hooks, which need the worklets Babel plugin; only the
|
|
580
|
+
* preset's own module (the mock engine, or an older Reanimated) makes the plugin unneeded.
|
|
581
|
+
*/
|
|
582
|
+
function reanimatedRunsItsOwnMock(root, active) {
|
|
583
|
+
return active.includes("reanimated") && detectEngine("auto", root).engine === "native" && libraryMockUsable(root);
|
|
584
|
+
}
|
|
585
|
+
/** Why a worklet plugin is not needed — only when the preset replacing its library is active. */
|
|
586
|
+
function workletReason(pkg, active, root) {
|
|
587
|
+
const preset = presetShadowing(pkg);
|
|
588
|
+
if (preset && active.includes(preset)) return `transforms worklets for ${pkg}; the active ${preset} preset (auto-detected from ${Object.entries(AUTO_DETECT_PRESETS).filter(([, name]) => name === preset).map(([detect]) => detect).join(", ")}) replaces ${pkg} with a mock, so no worklet runs.`;
|
|
589
|
+
if (!installedManifest(root, pkg)) return `transforms worklets for ${pkg}, which is not installed.`;
|
|
590
|
+
return null;
|
|
591
|
+
}
|
|
592
|
+
/** Whether `name` is one of the plugins this module knows by name. */
|
|
593
|
+
const isKnownPlugin = (name) => KNOWN_PLUGINS.some((known) => known.names.includes(name));
|
|
594
|
+
const KNOWN_PLUGINS = [
|
|
595
|
+
{
|
|
596
|
+
names: ["babel-plugin-macros", "@lingui/babel-plugin-lingui-macro"],
|
|
597
|
+
verdict: "required",
|
|
598
|
+
reason: (e) => `${e.written} compiles macro imports away at build time; without it the macro module is imported for real and fails (e.g. "Cannot find module 'babel-plugin-macros'").`
|
|
599
|
+
},
|
|
600
|
+
{
|
|
601
|
+
names: ["babel-plugin-module-resolver"],
|
|
602
|
+
verdict: "alias",
|
|
603
|
+
reason: () => `module-resolver rewrites import paths; its aliases map onto resolve.alias.`
|
|
604
|
+
},
|
|
605
|
+
{
|
|
606
|
+
names: ["react-native-worklets/plugin"],
|
|
607
|
+
verdict: "unneeded",
|
|
608
|
+
reason: () => ""
|
|
609
|
+
},
|
|
610
|
+
{
|
|
611
|
+
names: ["react-native-reanimated/plugin"],
|
|
612
|
+
verdict: "unneeded",
|
|
613
|
+
reason: () => ""
|
|
614
|
+
},
|
|
615
|
+
{
|
|
616
|
+
names: ["babel-plugin-react-compiler"],
|
|
617
|
+
verdict: "unneeded",
|
|
618
|
+
reason: () => "React Compiler only adds memoization to components that follow the Rules of React (react.dev/learn/react-compiler); they render the same without it."
|
|
619
|
+
}
|
|
620
|
+
];
|
|
621
|
+
const unknownReason = (e) => `${e.written} ran on every file under babel-jest and does not run under vitest-native; check whether tests depend on what it does.`;
|
|
622
|
+
function classifyBabelPlugins(report, root, active) {
|
|
623
|
+
return report.plugins.map((entry) => {
|
|
624
|
+
const worklets = /^(react-native-worklets|react-native-reanimated)\/plugin$/.exec(entry.name);
|
|
625
|
+
if (worklets && reanimatedRunsItsOwnMock(root, active)) return {
|
|
626
|
+
...entry,
|
|
627
|
+
verdict: "required",
|
|
628
|
+
reason: `${entry.written} gives Reanimated's hooks their dependencies. Under the native engine, Reanimated runs as its own mock, whose useAnimatedStyle throws without it ("used without a dependency array or Babel plugin").`
|
|
629
|
+
};
|
|
630
|
+
if (worklets) {
|
|
631
|
+
const reason = workletReason(worklets[1], active, root);
|
|
632
|
+
return reason ? {
|
|
633
|
+
...entry,
|
|
634
|
+
verdict: "unneeded",
|
|
635
|
+
reason
|
|
636
|
+
} : {
|
|
637
|
+
...entry,
|
|
638
|
+
verdict: "unknown",
|
|
639
|
+
reason: unknownReason(entry)
|
|
640
|
+
};
|
|
641
|
+
}
|
|
642
|
+
const known = KNOWN_PLUGINS.find((k) => k.names.includes(entry.name));
|
|
643
|
+
if (known) return {
|
|
644
|
+
...entry,
|
|
645
|
+
verdict: known.verdict,
|
|
646
|
+
reason: known.reason(entry, active)
|
|
647
|
+
};
|
|
648
|
+
if (/(^|[/-])macros?($|[/-])/.test(entry.name)) return {
|
|
649
|
+
...entry,
|
|
650
|
+
verdict: "required",
|
|
651
|
+
reason: `${entry.written} looks like a macro plugin; macros are compiled away at build time and fail when imported for real.`
|
|
652
|
+
};
|
|
653
|
+
return {
|
|
654
|
+
...entry,
|
|
655
|
+
verdict: "unknown",
|
|
656
|
+
reason: unknownReason(entry)
|
|
657
|
+
};
|
|
658
|
+
});
|
|
659
|
+
}
|
|
660
|
+
// src/project-babel.ts
|
|
661
|
+
/**
|
|
662
|
+
* The project's own Babel config for project source Vite compiles (`projectBabel`, #579).
|
|
663
|
+
*
|
|
664
|
+
* Metro and babel-jest compile every project file with the project's Babel config. Vite
|
|
665
|
+
* compiles it with Oxc, which covers TypeScript, JSX, Flow-free standard syntax and the
|
|
666
|
+
* React Native presets' own transforms, but not what a plugin adds: legacy decorators
|
|
667
|
+
* (WatermelonDB models), macros, `react-native-dotenv`'s `@env`, worklets when Reanimated
|
|
668
|
+
* runs as its own mock, a custom plugin.
|
|
669
|
+
*
|
|
670
|
+
* The config decides WHICH of its entries matter (classifyProjectBabelEntry); a cheap
|
|
671
|
+
* test of each file's source decides WHETHER the file needs one. Only a file that does
|
|
672
|
+
* compiles with Babel, with the project's config and its module transforms taken out so
|
|
673
|
+
* the output stays an ES module for Vite. An entry this does not know applies to every
|
|
674
|
+
* file, and is named at startup.
|
|
675
|
+
*/
|
|
676
|
+
const COVERED = { kind: "covered" };
|
|
677
|
+
const STRIP = { kind: "strip" };
|
|
678
|
+
const needed = (reason, applies) => ({
|
|
679
|
+
kind: "needed",
|
|
680
|
+
reason,
|
|
681
|
+
applies
|
|
682
|
+
});
|
|
683
|
+
const unknownEntry = (reason, entryKind) => ({
|
|
684
|
+
kind: "needed",
|
|
685
|
+
reason,
|
|
686
|
+
applies: null,
|
|
687
|
+
unknown: true,
|
|
688
|
+
entryKind
|
|
689
|
+
});
|
|
690
|
+
const has = (re) => (source) => re.test(source);
|
|
691
|
+
const DECORATOR_AT = /(?:^|[^\w$@./'"`])@\s*[A-Za-z_$][\w$.]*/gm;
|
|
692
|
+
/**
|
|
693
|
+
* Whether the line before an `@` puts it in a comment a decorator can never be in: after
|
|
694
|
+
* `//`, on a JSDoc line (` * @param`), or after a `/*` the line does not close. Only that
|
|
695
|
+
* line is read, so nothing that spans lines or strings can hide a real decorator; a tag
|
|
696
|
+
* in a block comment whose lines do not start with `*` still counts (a Babel compile).
|
|
697
|
+
*/
|
|
698
|
+
function inLineComment(line) {
|
|
699
|
+
const before = line.replace(/'(?:\\.|[^'\\])*'|"(?:\\.|[^"\\])*"|`(?:\\.|[^`\\])*`/g, "\"\"");
|
|
700
|
+
if (before.includes("//") || /^\s*\*/.test(before)) return true;
|
|
701
|
+
const open = before.lastIndexOf("/*");
|
|
702
|
+
return open !== -1 && !before.includes("*/", open + 2);
|
|
703
|
+
}
|
|
704
|
+
const DECORATOR = (source) => {
|
|
705
|
+
for (const match of source.matchAll(DECORATOR_AT)) {
|
|
706
|
+
const at = match.index + match[0].indexOf("@");
|
|
707
|
+
const lineStart = source.lastIndexOf("\n", at - 1) + 1;
|
|
708
|
+
if (!inLineComment(source.slice(lineStart, at))) return true;
|
|
709
|
+
}
|
|
710
|
+
return false;
|
|
711
|
+
};
|
|
712
|
+
const MACRO_IMPORT = has(/['"][^'"\n]*[./]macro(?:\/index)?(?:\.[cm]?[jt]sx?)?['"]/);
|
|
713
|
+
const WORKLET = has(/['"]worklet['"]|\buse(?:Animated\w*|DerivedValue|FrameCallback)\b|\brunOn(?:UI|JS|Runtime)\b|\bscheduleOnUI\b|\bGesture\.\w+\(/);
|
|
714
|
+
const JSX = (source, file) => !/\.[cm]?ts$/.test(file) && /<[A-Za-z>]/.test(source);
|
|
715
|
+
const CLASS = has(/\bclass\b(?:\s+[A-Za-z_$][\w$]*)?\s*(?:<|extends\b|implements\b|\{)/);
|
|
716
|
+
const CONSOLE = has(/\bconsole\s*\./);
|
|
717
|
+
const USES_PROCESS_ENVIRONMENT = has(/\bprocess\.env\b/);
|
|
718
|
+
const UNISTYLES = has(/react-native-unistyles|from\s+['"]react-native['"]/);
|
|
719
|
+
const IMPORTS_TAMAGUI = has(/['"](?:tamagui|@tamagui\/[^'"]+)['"]/);
|
|
720
|
+
const IMPORTS_PAPER = has(/['"]react-native-paper(?:\/[^'"]*)?['"]/);
|
|
721
|
+
const JS_FILE = (file) => /\.[cm]?jsx?$/.test(file);
|
|
722
|
+
const importOf = (moduleName) => {
|
|
723
|
+
const quoted = moduleName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
724
|
+
return has(new RegExp(`['"]${quoted}['"]`));
|
|
725
|
+
};
|
|
726
|
+
const RN_PRESET_OPTIONS = /* @__PURE__ */ new Set([
|
|
727
|
+
"disableImportExportTransform",
|
|
728
|
+
"enableBabelRuntime",
|
|
729
|
+
"unstable_transformProfile",
|
|
730
|
+
"disableStaticViewConfigsCodegen",
|
|
731
|
+
"dev",
|
|
732
|
+
"withDevTools",
|
|
733
|
+
"lazyImportExportTransform"
|
|
734
|
+
]);
|
|
735
|
+
const EXPO_PRESET_OPTIONS = /* @__PURE__ */ new Set([
|
|
736
|
+
...RN_PRESET_OPTIONS,
|
|
737
|
+
"jsxRuntime",
|
|
738
|
+
"lazyImports",
|
|
739
|
+
"react-compiler",
|
|
740
|
+
"reanimated",
|
|
741
|
+
"worklets",
|
|
742
|
+
"minifyTypeofWindow",
|
|
743
|
+
"decorators",
|
|
744
|
+
"web",
|
|
745
|
+
"native"
|
|
746
|
+
]);
|
|
747
|
+
const PRESET_OPTIONS = /* @__PURE__ */ new Map([
|
|
748
|
+
["@react-native/babel-preset", RN_PRESET_OPTIONS],
|
|
749
|
+
["metro-react-native-babel-preset", RN_PRESET_OPTIONS],
|
|
750
|
+
["babel-preset-expo", EXPO_PRESET_OPTIONS],
|
|
751
|
+
["@babel/preset-typescript", /* @__PURE__ */ new Set([
|
|
752
|
+
"allowDeclareFields",
|
|
753
|
+
"onlyRemoveTypeImports",
|
|
754
|
+
"isTSX",
|
|
755
|
+
"allExtensions",
|
|
756
|
+
"optimizeConstEnums",
|
|
757
|
+
"rewriteImportExtensions"
|
|
758
|
+
])],
|
|
759
|
+
["@babel/preset-react", /* @__PURE__ */ new Set([
|
|
760
|
+
"runtime",
|
|
761
|
+
"development",
|
|
762
|
+
"useBuiltIns",
|
|
763
|
+
"useSpread"
|
|
764
|
+
])],
|
|
765
|
+
["@babel/preset-flow", /* @__PURE__ */ new Set()],
|
|
766
|
+
["@babel/preset-env", /* @__PURE__ */ new Set([
|
|
767
|
+
"targets",
|
|
768
|
+
"modules",
|
|
769
|
+
"useBuiltIns",
|
|
770
|
+
"corejs",
|
|
771
|
+
"bugfixes",
|
|
772
|
+
"include",
|
|
773
|
+
"exclude",
|
|
774
|
+
"shippedProposals",
|
|
775
|
+
"debug",
|
|
776
|
+
"browserslistEnv",
|
|
777
|
+
"ignoreBrowserslistConfig"
|
|
778
|
+
])]
|
|
779
|
+
]);
|
|
780
|
+
const OXC_SYNTAX = /* @__PURE__ */ new Set([
|
|
781
|
+
"class-properties",
|
|
782
|
+
"private-methods",
|
|
783
|
+
"private-property-in-object",
|
|
784
|
+
"class-static-block",
|
|
785
|
+
"optional-chaining",
|
|
786
|
+
"nullish-coalescing-operator",
|
|
787
|
+
"logical-assignment-operators",
|
|
788
|
+
"numeric-separator",
|
|
789
|
+
"object-rest-spread",
|
|
790
|
+
"optional-catch-binding",
|
|
791
|
+
"async-generator-functions",
|
|
792
|
+
"async-to-generator",
|
|
793
|
+
"export-namespace-from",
|
|
794
|
+
"arrow-functions",
|
|
795
|
+
"block-scoping",
|
|
796
|
+
"block-scoped-functions",
|
|
797
|
+
"classes",
|
|
798
|
+
"computed-properties",
|
|
799
|
+
"destructuring",
|
|
800
|
+
"duplicate-keys",
|
|
801
|
+
"for-of",
|
|
802
|
+
"function-name",
|
|
803
|
+
"literals",
|
|
804
|
+
"member-expression-literals",
|
|
805
|
+
"parameters",
|
|
806
|
+
"property-literals",
|
|
807
|
+
"shorthand-properties",
|
|
808
|
+
"spread",
|
|
809
|
+
"sticky-regex",
|
|
810
|
+
"template-literals",
|
|
811
|
+
"typeof-symbol",
|
|
812
|
+
"unicode-escapes",
|
|
813
|
+
"unicode-regex",
|
|
814
|
+
"unicode-property-regex",
|
|
815
|
+
"dotall-regex",
|
|
816
|
+
"named-capturing-groups-regex",
|
|
817
|
+
"exponentiation-operator",
|
|
818
|
+
"regenerator",
|
|
819
|
+
"json-strings",
|
|
820
|
+
"new-target",
|
|
821
|
+
"object-super",
|
|
822
|
+
"reserved-words",
|
|
823
|
+
"react-jsx",
|
|
824
|
+
"react-jsx-development",
|
|
825
|
+
"react-display-name",
|
|
826
|
+
"react-jsx-self",
|
|
827
|
+
"react-jsx-source",
|
|
828
|
+
"react-pure-annotations",
|
|
829
|
+
"typescript",
|
|
830
|
+
"flow-strip-types",
|
|
831
|
+
"dynamic-import",
|
|
832
|
+
"jsx",
|
|
833
|
+
"flow",
|
|
834
|
+
"top-level-await",
|
|
835
|
+
"import-meta",
|
|
836
|
+
"class-static-block",
|
|
837
|
+
"import-attributes",
|
|
838
|
+
"runtime"
|
|
839
|
+
]);
|
|
840
|
+
const UNPARSED_SYNTAX = {
|
|
841
|
+
"pipeline-operator": has(/\|>/),
|
|
842
|
+
"do-expressions": has(/\bdo\s*\{/),
|
|
843
|
+
"function-bind": has(/::/),
|
|
844
|
+
"export-default-from": has(/\bexport\s+[A-Za-z_$][\w$]*\s*(?:,|\s+from\b)/),
|
|
845
|
+
"throw-expressions": has(/[=(,:?]\s*throw\b/),
|
|
846
|
+
"partial-application": has(/\?\s*[,)]/)
|
|
847
|
+
};
|
|
848
|
+
const SEMANTIC_OPTIONS = [
|
|
849
|
+
"loose",
|
|
850
|
+
"spec",
|
|
851
|
+
"assumptions",
|
|
852
|
+
"pragma",
|
|
853
|
+
"pragmaFrag",
|
|
854
|
+
"importSource",
|
|
855
|
+
"all",
|
|
856
|
+
"jsxPragma"
|
|
857
|
+
];
|
|
858
|
+
const STRIPPED = /* @__PURE__ */ new Set([
|
|
859
|
+
"@babel/plugin-transform-modules-commonjs",
|
|
860
|
+
"@babel/plugin-transform-modules-amd",
|
|
861
|
+
"@babel/plugin-transform-modules-umd",
|
|
862
|
+
"@babel/plugin-transform-modules-systemjs",
|
|
863
|
+
"babel-plugin-dynamic-import-node",
|
|
864
|
+
"@babel/plugin-transform-dynamic-import",
|
|
865
|
+
"@babel/plugin-proposal-dynamic-import",
|
|
866
|
+
"babel-plugin-transform-import-meta",
|
|
867
|
+
"babel-plugin-istanbul"
|
|
868
|
+
]);
|
|
869
|
+
const optionKeys = (options) => options && typeof options === "object" ? Object.keys(options) : [];
|
|
870
|
+
const semanticOption = (options) => optionKeys(options).find((key) => SEMANTIC_OPTIONS.includes(key));
|
|
871
|
+
/**
|
|
872
|
+
* What `entry` means for project source under Vite. `active` is the run's active
|
|
873
|
+
* presets: the worklets plugins are needed exactly when Reanimated runs as its own mock.
|
|
874
|
+
*/
|
|
875
|
+
function classifyProjectBabelEntry(entry, root, active) {
|
|
876
|
+
const { name, options } = entry;
|
|
877
|
+
if (entry.kind === "preset") {
|
|
878
|
+
if (name === "nativewind/babel") return needed(name, JSX);
|
|
879
|
+
const allowed = PRESET_OPTIONS.get(name);
|
|
880
|
+
if (!allowed) return unknownEntry(`the preset ${name}`, "preset");
|
|
881
|
+
const opts = options ?? {};
|
|
882
|
+
if (name === "@babel/preset-flow" && opts.all) return needed(`${name}'s \`all\` option`, null);
|
|
883
|
+
const jsxOption = [
|
|
884
|
+
"jsxPragma",
|
|
885
|
+
"jsxPragmaFrag",
|
|
886
|
+
"pragma",
|
|
887
|
+
"pragmaFrag",
|
|
888
|
+
"importSource"
|
|
889
|
+
].find((key) => opts[key] !== void 0);
|
|
890
|
+
if (jsxOption && (name === "@babel/preset-typescript" || name === "@babel/preset-react")) return needed(`${name}'s \`${jsxOption}\` option`, JSX);
|
|
891
|
+
if (opts.jsxImportSource !== void 0) return needed(`${name}'s \`jsxImportSource\``, JSX);
|
|
892
|
+
const changes = optionKeys(options).find((key) => !allowed.has(key));
|
|
893
|
+
if (changes) return needed(`${name}'s \`${changes}\` option`, null);
|
|
894
|
+
if (name === "babel-preset-expo" && opts.worklets !== false && opts.reanimated !== false && reanimatedRunsItsOwnMock(root, active)) return needed("babel-preset-expo's worklets plugin", WORKLET);
|
|
895
|
+
return COVERED;
|
|
896
|
+
}
|
|
897
|
+
if (STRIPPED.has(name)) return STRIP;
|
|
898
|
+
if (name === "babel-plugin-syntax-hermes-parser" || name === "babel-plugin-transform-flow-enums") return COVERED;
|
|
899
|
+
const standard = /^@babel\/plugin-(?:transform|syntax|proposal)-(.+)$/.exec(name);
|
|
900
|
+
if (standard) {
|
|
901
|
+
const feature = standard[1];
|
|
902
|
+
if (feature === "decorators") return needed(name, DECORATOR);
|
|
903
|
+
const unparsed = UNPARSED_SYNTAX[feature];
|
|
904
|
+
if (unparsed) return needed(name, unparsed);
|
|
905
|
+
if (!OXC_SYNTAX.has(feature)) return needed(name, null);
|
|
906
|
+
const semantic = semanticOption(options);
|
|
907
|
+
if (!semantic) return COVERED;
|
|
908
|
+
const reason = `${name}'s \`${semantic}\` option`;
|
|
909
|
+
if (feature === "class-properties" || feature === "private-methods") return needed(reason, CLASS);
|
|
910
|
+
if (feature.startsWith("react-jsx")) return needed(reason, JSX);
|
|
911
|
+
if (feature === "flow-strip-types") return needed(reason, (source) => /:\s*\w/.test(source));
|
|
912
|
+
return needed(reason, null);
|
|
913
|
+
}
|
|
914
|
+
if (name === "react-native-dotenv" || name === "module:react-native-dotenv") {
|
|
915
|
+
const moduleName = options?.moduleName ?? "@env";
|
|
916
|
+
return needed(name, importOf(moduleName));
|
|
917
|
+
}
|
|
918
|
+
if (/^(?:babel-plugin-)?transform-inline-environment-variables$/.test(name)) return needed(name, USES_PROCESS_ENVIRONMENT);
|
|
919
|
+
if (name === "react-native-unistyles/plugin") return needed(name, UNISTYLES);
|
|
920
|
+
if (name === "babel-plugin-transform-remove-console") return needed(name, CONSOLE);
|
|
921
|
+
if (name === "@tamagui/babel-plugin") return needed(name, IMPORTS_TAMAGUI);
|
|
922
|
+
if (name === "react-native-paper/babel") return needed(name, IMPORTS_PAPER);
|
|
923
|
+
const [classified] = classifyBabelPlugins({
|
|
924
|
+
source: null,
|
|
925
|
+
evaluated: true,
|
|
926
|
+
presets: [],
|
|
927
|
+
lazyImports: [],
|
|
928
|
+
plugins: [{
|
|
929
|
+
written: name,
|
|
930
|
+
name,
|
|
931
|
+
options
|
|
932
|
+
}]
|
|
933
|
+
}, root, active);
|
|
934
|
+
if (classified.verdict === "unneeded" || classified.verdict === "alias") return COVERED;
|
|
935
|
+
if (/^react-native-(?:worklets|reanimated)\/plugin$/.test(name)) return needed(name, WORKLET);
|
|
936
|
+
if (classified.verdict === "required") return needed(name, MACRO_IMPORT);
|
|
937
|
+
return unknownEntry(name, "plugin");
|
|
938
|
+
}
|
|
939
|
+
/**
|
|
940
|
+
* Why the engine applies `entry` to project source (to the files that need it), or null
|
|
941
|
+
* when Oxc and the engine already do what it does or it is taken out. `doctor` and
|
|
942
|
+
* `migrate` report from this.
|
|
943
|
+
*/
|
|
944
|
+
function projectBabelTrigger(entry, root, active) {
|
|
945
|
+
const classified = classifyProjectBabelEntry(entry, root, active);
|
|
946
|
+
return classified.kind === "needed" ? classified.reason : null;
|
|
947
|
+
}
|
|
948
|
+
const KNOWN_PRESET_PACKAGES = [
|
|
949
|
+
"@react-native/babel-preset",
|
|
950
|
+
"metro-react-native-babel-preset",
|
|
951
|
+
"babel-preset-expo"
|
|
952
|
+
];
|
|
953
|
+
const PRESET_INLINE_KEY = /[\\/](@react-native[\\/]babel-preset|metro-react-native-babel-preset|babel-preset-expo)[\\/].*?\.[cm]?js((?:\.overrides\[\d+\])?(?:\$\d+)*)$/;
|
|
954
|
+
/** A resolved plugin's key, the same for every copy of the presets above. */
|
|
955
|
+
function normalizePluginKey(key) {
|
|
956
|
+
const inline = PRESET_INLINE_KEY.exec(key);
|
|
957
|
+
return inline ? `${inline[1].replace(/\\/g, "/")}${inline[2]}` : key;
|
|
958
|
+
}
|
|
959
|
+
const KEY_PACKAGES = {
|
|
960
|
+
"syntax-hermes-parser": "babel-plugin-syntax-hermes-parser",
|
|
961
|
+
"transform-flow-enums": "babel-plugin-transform-flow-enums"
|
|
962
|
+
};
|
|
963
|
+
/** The package a resolved plugin key names, for classification. */
|
|
964
|
+
function pluginNameOfKey(key) {
|
|
965
|
+
if (KEY_PACKAGES[key]) return KEY_PACKAGES[key];
|
|
966
|
+
return /^(?:transform|syntax|proposal)-/.test(key) ? `@babel/plugin-${key}` : key;
|
|
967
|
+
}
|
|
968
|
+
const optionsKey = (options) => JSON.stringify(options ?? {}, (_, value) => typeof value === "function" ? "[function]" : value);
|
|
969
|
+
/**
|
|
970
|
+
* A React Native or Expo preset's options with its module transform off. Expo's preset
|
|
971
|
+
* also takes per-platform options (`native`, `web`) that override the top-level one, so
|
|
972
|
+
* those are set too: `native: { disableImportExportTransform: false }` would otherwise
|
|
973
|
+
* bring the CommonJS transform back.
|
|
974
|
+
*/
|
|
975
|
+
function esmPresetOptions(options) {
|
|
976
|
+
const given = options ?? {};
|
|
977
|
+
const result = {
|
|
978
|
+
...given,
|
|
979
|
+
disableImportExportTransform: true
|
|
980
|
+
};
|
|
981
|
+
for (const platform of ["native", "web"]) {
|
|
982
|
+
const nested = given[platform];
|
|
983
|
+
if (nested && typeof nested === "object") result[platform] = {
|
|
984
|
+
...nested,
|
|
985
|
+
disableImportExportTransform: true
|
|
986
|
+
};
|
|
987
|
+
}
|
|
988
|
+
return result;
|
|
989
|
+
}
|
|
990
|
+
/** The package name of a config item, as `doctor` names it, or its path. */
|
|
991
|
+
function configItemName(item, kind) {
|
|
992
|
+
const request = item.file?.request;
|
|
993
|
+
if (!request) return item.name ?? `an inline ${kind}`;
|
|
994
|
+
if (request.startsWith("module:")) return request.slice(7);
|
|
995
|
+
if (path.isAbsolute(request)) {
|
|
996
|
+
const parts = request.split(/[\\/]/);
|
|
997
|
+
const at = parts.lastIndexOf("node_modules");
|
|
998
|
+
if (at !== -1 && parts[at + 1]) {
|
|
999
|
+
const scoped = parts[at + 1].startsWith("@");
|
|
1000
|
+
const pkg = scoped ? `${parts[at + 1]}/${parts[at + 2]}` : parts[at + 1];
|
|
1001
|
+
const sub = parts.slice(at + (scoped ? 3 : 2)).join("/").replace(/(?:^|\/)(?:(?:lib|dist|build|src)\/)?index\.[cm]?js$/, "").replace(/\.[cm]?js$/, "");
|
|
1002
|
+
return sub === "" || /^(?:lib|dist|build|src)$/.test(sub) ? pkg : `${pkg}/${sub}`;
|
|
1003
|
+
}
|
|
1004
|
+
return request;
|
|
1005
|
+
}
|
|
1006
|
+
if (request.startsWith(".")) return request;
|
|
1007
|
+
return normalizeBabelName(request, kind);
|
|
1008
|
+
}
|
|
1009
|
+
const LEADING_COMMENTS = /^(?:\s*(?:\/\/[^\n]*|\/\*[\s\S]*?\*\/))*/;
|
|
1010
|
+
/** Whether a file's leading comments carry `@flow`. */
|
|
1011
|
+
const hasFlowPragma = (code) => /@flow\b/.test(LEADING_COMMENTS.exec(code)?.[0] ?? "");
|
|
1012
|
+
const PROJECT_SOURCE = /\.(?:[cm]?js|jsx|[cm]?ts|tsx)$/;
|
|
1013
|
+
const NODE_MODULES = /[\\/]node_modules[\\/]/;
|
|
1014
|
+
/** A project source file this may compile: absolute, no query, outside node_modules. */
|
|
1015
|
+
function isProjectSourceFile(id) {
|
|
1016
|
+
return PROJECT_SOURCE.test(id) && !id.includes("?") && path.isAbsolute(id) && !NODE_MODULES.test(id);
|
|
1017
|
+
}
|
|
1018
|
+
const asking = new AsyncLocalStorage();
|
|
1019
|
+
const ESM_PRESETS = /* @__PURE__ */ new Set([
|
|
1020
|
+
"@react-native/babel-preset",
|
|
1021
|
+
"metro-react-native-babel-preset",
|
|
1022
|
+
"babel-preset-expo"
|
|
1023
|
+
]);
|
|
1024
|
+
const MODULE_TRANSFORM = /^transform-modules-(?:commonjs|amd|umd|systemjs)$|^(?:transform|proposal)-dynamic-import$|dynamic-import-node/;
|
|
1025
|
+
const COMMONJS_OUTPUT = /Object\.defineProperty\(exports,\s*["']__esModule["']|^\s*module\.exports\s*=/m;
|
|
1026
|
+
/**
|
|
1027
|
+
* The warning for a project whose root Babel config cannot be applied because
|
|
1028
|
+
* `@babel/core` does not resolve from it, or null. Only the mock engine can get here: the
|
|
1029
|
+
* native engine requires @babel/core.
|
|
1030
|
+
*/
|
|
1031
|
+
function missingBabelCoreNotice(root, mode) {
|
|
1032
|
+
if (mode === "never") return null;
|
|
1033
|
+
const configFile = rootBabelConfigFile(root);
|
|
1034
|
+
if (configFile === null || installedManifest(root, "@babel/core") !== null) return null;
|
|
1035
|
+
return `[vitest-native] projectBabel: ${configFile} is not applied, because @babel/core is not installed in the project. Project source compiles with Oxc only, so a plugin it needs (decorators, a macro) does not run. Add @babel/core as a dev dependency, or set projectBabel: 'never' to silence this.`;
|
|
1036
|
+
}
|
|
1037
|
+
/**
|
|
1038
|
+
* The project's Babel route, or null when it has no `@babel/core` or the mode is `never`.
|
|
1039
|
+
* `active` is the run's active presets; `hasExpo` and `platform` choose the caller, the
|
|
1040
|
+
* same one Node's require of project source uses (native/babel-caller.mjs).
|
|
1041
|
+
*/
|
|
1042
|
+
function createProjectBabel(root, mode, options, announce = () => {}) {
|
|
1043
|
+
if (mode === "never") return null;
|
|
1044
|
+
if (installedManifest(root, "@babel/core") === null) return null;
|
|
1045
|
+
const babel = createRequire(path.join(root, "package.json"))("@babel/core");
|
|
1046
|
+
const caller = projectBabelCaller({
|
|
1047
|
+
hasExpo: options.hasExpo,
|
|
1048
|
+
platform: options.platform,
|
|
1049
|
+
esm: true
|
|
1050
|
+
});
|
|
1051
|
+
const partialFor = (filename, babelRoot = root) => babel.loadPartialConfig({
|
|
1052
|
+
filename,
|
|
1053
|
+
cwd: root,
|
|
1054
|
+
root: babelRoot,
|
|
1055
|
+
caller
|
|
1056
|
+
});
|
|
1057
|
+
const expand = (presets) => babel.loadOptions({
|
|
1058
|
+
filename: path.join(root, "index.js"),
|
|
1059
|
+
cwd: root,
|
|
1060
|
+
root,
|
|
1061
|
+
babelrc: false,
|
|
1062
|
+
configFile: false,
|
|
1063
|
+
caller,
|
|
1064
|
+
presets
|
|
1065
|
+
})?.plugins.map((plugin) => ({
|
|
1066
|
+
key: normalizePluginKey(plugin.key),
|
|
1067
|
+
options: plugin.options
|
|
1068
|
+
})) ?? [];
|
|
1069
|
+
let knownPlugins;
|
|
1070
|
+
const knownPresetPlugins = () => {
|
|
1071
|
+
if (knownPlugins) return knownPlugins;
|
|
1072
|
+
knownPlugins = /* @__PURE__ */ new Map();
|
|
1073
|
+
const req = createRequire(path.join(root, "package.json"));
|
|
1074
|
+
for (const preset of KNOWN_PRESET_PACKAGES) {
|
|
1075
|
+
if (installedManifest(root, preset) === null) continue;
|
|
1076
|
+
for (const plugin of expand([req.resolve(preset)])) knownPlugins.set(plugin.key, optionsKey(plugin.options));
|
|
1077
|
+
}
|
|
1078
|
+
return knownPlugins;
|
|
1079
|
+
};
|
|
1080
|
+
/**
|
|
1081
|
+
* What a preset expands to beyond React Native's and Expo's presets: plugins they do not
|
|
1082
|
+
* add, and plugins they add with other options. Null when neither preset is installed.
|
|
1083
|
+
*/
|
|
1084
|
+
const addedByPreset = (item) => {
|
|
1085
|
+
if (!item.value) return null;
|
|
1086
|
+
const known = knownPresetPlugins();
|
|
1087
|
+
if (known.size === 0) return null;
|
|
1088
|
+
return expand([[item.value, item.options ?? {}]]).filter((plugin) => known.get(plugin.key) !== optionsKey(plugin.options));
|
|
1089
|
+
};
|
|
1090
|
+
/** A config plugin's resolved key, as Babel's loaded options carry it. */
|
|
1091
|
+
const keyOfPlugin = (item) => {
|
|
1092
|
+
const plugin = babel.loadOptions({
|
|
1093
|
+
filename: path.join(root, "index.js"),
|
|
1094
|
+
cwd: root,
|
|
1095
|
+
root,
|
|
1096
|
+
babelrc: false,
|
|
1097
|
+
configFile: false,
|
|
1098
|
+
caller,
|
|
1099
|
+
plugins: [item]
|
|
1100
|
+
})?.plugins[0];
|
|
1101
|
+
return plugin ? normalizePluginKey(plugin.key) : void 0;
|
|
1102
|
+
};
|
|
1103
|
+
const plans = /* @__PURE__ */ new Map();
|
|
1104
|
+
const planOf = (loaded) => {
|
|
1105
|
+
const presets = loaded.presets ?? [];
|
|
1106
|
+
const plugins = loaded.plugins ?? [];
|
|
1107
|
+
const key = JSON.stringify([
|
|
1108
|
+
presets.map((p) => [configItemName(p, "preset"), p.options]),
|
|
1109
|
+
plugins.map((p) => [configItemName(p, "plugin"), p.options]),
|
|
1110
|
+
loaded.assumptions ?? {}
|
|
1111
|
+
], (_, value) => typeof value === "function" ? "[function]" : value);
|
|
1112
|
+
let plan = plans.get(key);
|
|
1113
|
+
if (plan) return plan;
|
|
1114
|
+
plan = {
|
|
1115
|
+
needs: [],
|
|
1116
|
+
presets: [],
|
|
1117
|
+
plugins: []
|
|
1118
|
+
};
|
|
1119
|
+
for (const item of presets) {
|
|
1120
|
+
const name = configItemName(item, "preset");
|
|
1121
|
+
const classified = classifyProjectBabelEntry({
|
|
1122
|
+
name,
|
|
1123
|
+
kind: "preset",
|
|
1124
|
+
options: item.options
|
|
1125
|
+
}, root, options.active);
|
|
1126
|
+
if (classified.kind === "needed") {
|
|
1127
|
+
const adds = classified.unknown ? addedByPreset(item) : null;
|
|
1128
|
+
if (adds === null) plan.needs.push(classified);
|
|
1129
|
+
else for (const { key: pluginKey, options: pluginOptions } of adds) {
|
|
1130
|
+
const added = classifyProjectBabelEntry({
|
|
1131
|
+
name: pluginNameOfKey(pluginKey),
|
|
1132
|
+
kind: "plugin",
|
|
1133
|
+
options: pluginOptions
|
|
1134
|
+
}, root, options.active);
|
|
1135
|
+
if (added.kind !== "needed") continue;
|
|
1136
|
+
plan.needs.push(added.unknown ? {
|
|
1137
|
+
...classified,
|
|
1138
|
+
reason: `${classified.reason} (adds ${pluginKey})`,
|
|
1139
|
+
key: pluginKey
|
|
1140
|
+
} : {
|
|
1141
|
+
...added,
|
|
1142
|
+
reason: `${added.reason} (from the preset ${name})`
|
|
1143
|
+
});
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
if (ESM_PRESETS.has(name) && item.value) plan.presets.push([item.value, esmPresetOptions(item.options)]);
|
|
1147
|
+
else if (name === "@babel/preset-env" && item.value) plan.presets.push([item.value, {
|
|
1148
|
+
...item.options,
|
|
1149
|
+
modules: false
|
|
1150
|
+
}]);
|
|
1151
|
+
else plan.presets.push(item);
|
|
1152
|
+
}
|
|
1153
|
+
for (const item of plugins) {
|
|
1154
|
+
const classified = classifyProjectBabelEntry({
|
|
1155
|
+
name: configItemName(item, "plugin"),
|
|
1156
|
+
kind: "plugin",
|
|
1157
|
+
options: item.options
|
|
1158
|
+
}, root, options.active);
|
|
1159
|
+
if (classified.kind === "strip") continue;
|
|
1160
|
+
if (classified.kind === "needed") plan.needs.push(classified.unknown ? {
|
|
1161
|
+
...classified,
|
|
1162
|
+
key: keyOfPlugin(item)
|
|
1163
|
+
} : classified);
|
|
1164
|
+
plan.plugins.push(item);
|
|
1165
|
+
}
|
|
1166
|
+
if (loaded.assumptions && Object.keys(loaded.assumptions).length > 0) plan.needs.push({
|
|
1167
|
+
reason: "the config's `assumptions`",
|
|
1168
|
+
applies: null
|
|
1169
|
+
});
|
|
1170
|
+
plans.set(key, plan);
|
|
1171
|
+
return plan;
|
|
1172
|
+
};
|
|
1173
|
+
const announced = /* @__PURE__ */ new Set();
|
|
1174
|
+
const fallbackWarned = /* @__PURE__ */ new Set();
|
|
1175
|
+
const announceOnce = (reasons) => {
|
|
1176
|
+
const fresh = reasons.filter((reason) => !announced.has(reason));
|
|
1177
|
+
if (fresh.length === 0) return;
|
|
1178
|
+
for (const reason of fresh) announced.add(reason);
|
|
1179
|
+
announce(fresh);
|
|
1180
|
+
};
|
|
1181
|
+
const projectRootOf = (id) => isProjectSourceFile(id) ? rootSpellingOf(root, path.normalize(id)) : null;
|
|
1182
|
+
const versionOf = (item) => {
|
|
1183
|
+
const file = item.file?.resolved;
|
|
1184
|
+
if (!file) return "inline";
|
|
1185
|
+
if (NODE_MODULES.test(file)) {
|
|
1186
|
+
const manifest = installedManifest(root, configItemName(item, "plugin"));
|
|
1187
|
+
if (typeof manifest?.version === "string") return manifest.version;
|
|
1188
|
+
}
|
|
1189
|
+
if (!fs.existsSync(file)) return "missing";
|
|
1190
|
+
return crypto.createHash("sha1").update(fs.readFileSync(file)).digest("hex");
|
|
1191
|
+
};
|
|
1192
|
+
return {
|
|
1193
|
+
announceRoot() {
|
|
1194
|
+
const partial = partialFor(path.join(root, "index.js"));
|
|
1195
|
+
if (!partial?.hasFilesystemConfig()) return;
|
|
1196
|
+
const plan = planOf(partial.options);
|
|
1197
|
+
announceOnce(mode === "always" ? ["projectBabel: 'always'"] : plan.needs.map((n) => n.reason));
|
|
1198
|
+
},
|
|
1199
|
+
cacheKey(id, source) {
|
|
1200
|
+
const babelRoot = projectRootOf(id);
|
|
1201
|
+
if (babelRoot === null) return "";
|
|
1202
|
+
const partial = partialFor(id, babelRoot);
|
|
1203
|
+
if (!partial?.hasFilesystemConfig()) return "";
|
|
1204
|
+
const presets = partial.options.presets ?? [];
|
|
1205
|
+
const plugins = partial.options.plugins ?? [];
|
|
1206
|
+
const names = [...presets.map((item) => configItemName(item, "preset")), ...plugins.map((item) => configItemName(item, "plugin"))];
|
|
1207
|
+
const dotenv = plugins.find((item) => configItemName(item, "plugin").endsWith("react-native-dotenv"));
|
|
1208
|
+
const inlinesEnv = names.some((name) => name.endsWith("transform-inline-environment-variables"));
|
|
1209
|
+
return JSON.stringify([
|
|
1210
|
+
babel.version,
|
|
1211
|
+
[...presets, ...plugins].map((item, i) => [
|
|
1212
|
+
names[i],
|
|
1213
|
+
versionOf(item),
|
|
1214
|
+
item.options
|
|
1215
|
+
]),
|
|
1216
|
+
process.env.BABEL_ENV ?? "",
|
|
1217
|
+
process.env.NODE_ENV ?? "",
|
|
1218
|
+
dotenv ? envFilesHash(root, dotenv.options?.path) : "",
|
|
1219
|
+
inlinesEnv && source ? [...new Set([...source.matchAll(/\bprocess\.env\.([A-Za-z_$][\w$]*)/g)].map((m) => m[1]))].sort().map((name) => [name, process.env[name] ?? null]) : ""
|
|
1220
|
+
], (_, value) => typeof value === "function" ? "[function]" : value);
|
|
1221
|
+
},
|
|
1222
|
+
async load(id, chain) {
|
|
1223
|
+
const babelRoot = projectRootOf(id);
|
|
1224
|
+
if (babelRoot === null) return void 0;
|
|
1225
|
+
if (asking.getStore() === id) return void 0;
|
|
1226
|
+
const partial = partialFor(id, babelRoot);
|
|
1227
|
+
if (!partial?.hasFilesystemConfig()) return void 0;
|
|
1228
|
+
const plan = planOf(partial.options);
|
|
1229
|
+
const code = await fs.promises.readFile(id, "utf8");
|
|
1230
|
+
let matched = [];
|
|
1231
|
+
const reasons = mode === "always" ? ["projectBabel: 'always'"] : (matched = plan.needs.filter((need) => need.applies === null || need.applies(code, id))).map((need) => need.reason);
|
|
1232
|
+
if (reasons.length === 0 && JS_FILE(id) && hasFlowPragma(code)) reasons.push("Flow syntax");
|
|
1233
|
+
if (reasons.length === 0) return void 0;
|
|
1234
|
+
announceOnce(reasons);
|
|
1235
|
+
const file = relativeToRoot(root, path.normalize(id));
|
|
1236
|
+
options.onCompile?.(file.split(path.sep).join("/"), reasons);
|
|
1237
|
+
if (chain) {
|
|
1238
|
+
const other = await asking.run(id, () => chain.load(id));
|
|
1239
|
+
if (other != null) return other;
|
|
1240
|
+
}
|
|
1241
|
+
const knownWriter = matched.find((need) => need.unknown && need.key === plan.commonjsWriter);
|
|
1242
|
+
if (plan.commonjsWriter && knownWriter) {
|
|
1243
|
+
if (matched.length === 1) return void 0;
|
|
1244
|
+
throw commonjsError(file, plan.commonjsWriter, knownWriter, matched);
|
|
1245
|
+
}
|
|
1246
|
+
const loaded = babel.loadOptions({
|
|
1247
|
+
...partial.options,
|
|
1248
|
+
presets: plan.presets,
|
|
1249
|
+
plugins: plan.plugins,
|
|
1250
|
+
filename: id,
|
|
1251
|
+
sourceMaps: true,
|
|
1252
|
+
caller
|
|
1253
|
+
});
|
|
1254
|
+
if (!loaded) return void 0;
|
|
1255
|
+
const compile = (without) => babel.transformAsync(code, {
|
|
1256
|
+
...loaded,
|
|
1257
|
+
plugins: loaded.plugins.filter((plugin) => !MODULE_TRANSFORM.test(plugin.key) && normalizePluginKey(plugin.key) !== without)
|
|
1258
|
+
});
|
|
1259
|
+
const result = await compile();
|
|
1260
|
+
if (!result?.code) return void 0;
|
|
1261
|
+
if (COMMONJS_OUTPUT.test(result.code)) {
|
|
1262
|
+
let emitter;
|
|
1263
|
+
for (const plugin of loaded.plugins) {
|
|
1264
|
+
const key = normalizePluginKey(plugin.key);
|
|
1265
|
+
if (knownPresetPlugins().has(key) || MODULE_TRANSFORM.test(plugin.key)) continue;
|
|
1266
|
+
const without = await compile(key);
|
|
1267
|
+
if (without?.code && !COMMONJS_OUTPUT.test(without.code)) {
|
|
1268
|
+
emitter = key;
|
|
1269
|
+
break;
|
|
1270
|
+
}
|
|
1271
|
+
}
|
|
1272
|
+
const emitterNeed = matched.find((need) => need.unknown && need.key === emitter);
|
|
1273
|
+
if (emitter && emitterNeed) plan.commonjsWriter = emitter;
|
|
1274
|
+
if (emitter && emitterNeed && matched.length === 1) {
|
|
1275
|
+
if (!fallbackWarned.has(emitter)) {
|
|
1276
|
+
fallbackWarned.add(emitter);
|
|
1277
|
+
console.warn(`[vitest-native] projectBabel: ${emitterNeed.reason} writes CommonJS, which Vite's module runner cannot run, so files only it applies to (${file} first) compile with Oxc, without it. Leave it out of the config for tests, or set projectBabel: 'never'.`);
|
|
1278
|
+
}
|
|
1279
|
+
return;
|
|
1280
|
+
}
|
|
1281
|
+
throw commonjsError(file, emitter, emitterNeed, matched);
|
|
1282
|
+
}
|
|
1283
|
+
return {
|
|
1284
|
+
code: result.code,
|
|
1285
|
+
map: result.map
|
|
1286
|
+
};
|
|
1287
|
+
}
|
|
1288
|
+
};
|
|
1289
|
+
}
|
|
1290
|
+
/** PROJECT_BABEL_COMMONJS for `file`, naming the plugin that writes CommonJS if found. */
|
|
1291
|
+
function commonjsError(file, emitter, emitterNeed, matched) {
|
|
1292
|
+
const what = emitterNeed ? `the ${emitterNeed.entryKind ?? "plugin"} ${emitterNeed.reason.replace(/^the preset /, "")}` : emitter ? `the plugin ${emitter}` : "a plugin or preset in it";
|
|
1293
|
+
return new VitestNativeError("PROJECT_BABEL_COMMONJS", `projectBabel: the project's Babel config compiled ${file} to CommonJS, which Vite's module runner cannot run. vitest-native takes the module transforms it knows out of this compile; ${what} writes CommonJS some other way. The file also needs ${matched.map((need) => need.reason).join(", ")}, so it cannot fall back to Oxc without losing what they do. Leave the CommonJS writer out of the config for tests, or set projectBabel: 'never'.`);
|
|
1294
|
+
}
|
|
1295
|
+
/**
|
|
1296
|
+
* A digest of the project's `.env*` files, and of the file a dotenv plugin's `path`
|
|
1297
|
+
* option names, which a dotenv plugin inlines.
|
|
1298
|
+
*/
|
|
1299
|
+
function envFilesHash(root, configured) {
|
|
1300
|
+
const hash = crypto.createHash("sha1");
|
|
1301
|
+
const files = fs.readdirSync(root).filter((name) => name.startsWith(".env")).map((name) => path.join(root, name));
|
|
1302
|
+
if (configured) files.push(path.resolve(root, configured));
|
|
1303
|
+
for (const file of [...new Set(files)].sort()) if (fs.existsSync(file)) hash.update(file).update(fs.readFileSync(file));
|
|
1304
|
+
return hash.digest("hex");
|
|
1305
|
+
}
|
|
1306
|
+
// src/native/plain-javascript.ts
|
|
1307
|
+
/**
|
|
1308
|
+
* Whether a file is standard JavaScript, read with the project's own Babel parser and no
|
|
1309
|
+
* syntax plugins: JSX and Flow are not, ES-module syntax is. Shared by detection
|
|
1310
|
+
* (ecosystem.ts, the react-native field check) and `migrate` (cli/untranspiled.ts).
|
|
1311
|
+
*/
|
|
1312
|
+
function babelParser(root) {
|
|
1313
|
+
const req = createRequire(path.join(root, "package.json"));
|
|
1314
|
+
for (const from of [() => req, () => createRequire(req.resolve("@babel/core"))]) try {
|
|
1315
|
+
return from()("@babel/parser").parse;
|
|
1316
|
+
} catch {}
|
|
1317
|
+
return null;
|
|
1318
|
+
}
|
|
1319
|
+
/** Whether `file` parses as standard JavaScript: no JSX, no Flow. */
|
|
1320
|
+
function isPlainJavaScript(parse, file) {
|
|
1321
|
+
try {
|
|
1322
|
+
parse(fs.readFileSync(file, "utf8"), {
|
|
1323
|
+
sourceType: "unambiguous",
|
|
1324
|
+
allowReturnOutsideFunction: true,
|
|
1325
|
+
allowAwaitOutsideFunction: true
|
|
1326
|
+
});
|
|
1327
|
+
return true;
|
|
1328
|
+
} catch {
|
|
1329
|
+
return false;
|
|
1330
|
+
}
|
|
1331
|
+
}
|
|
1332
|
+
// src/native/ecosystem.ts
|
|
1333
|
+
/** A path inside a node_modules directory: an installed package's, not a workspace member's. */
|
|
1334
|
+
const NODE_MODULES_DIR = /[\\/]node_modules[\\/]/;
|
|
1335
|
+
/**
|
|
1336
|
+
* Packages that must never be auto-inlined even though they depend on React
|
|
1337
|
+
* Native. The test library and the renderers underneath it are infrastructure the
|
|
1338
|
+
* engine itself wires up; pulling a second copy of them into the module graph has
|
|
1339
|
+
* corrupted rendering before, in ways that surface as unrelated act() and
|
|
1340
|
+
* host-component failures.
|
|
1341
|
+
*
|
|
1342
|
+
* This list is one clause of the ownership rule; the whole of it is written down in
|
|
1343
|
+
* the header of native/apply.ts, which is the file to read before changing what ends
|
|
1344
|
+
* up in either graph.
|
|
1345
|
+
*/
|
|
1346
|
+
const NEVER_INLINE = /* @__PURE__ */ new Set([
|
|
1347
|
+
"@testing-library/react-native",
|
|
1348
|
+
"react-test-renderer",
|
|
1349
|
+
"test-renderer",
|
|
1350
|
+
"react-native",
|
|
1351
|
+
"react",
|
|
1352
|
+
"react-is"
|
|
1353
|
+
]);
|
|
1354
|
+
/** Does this manifest offer a React Native build, by legacy field or export condition? */
|
|
1355
|
+
function hasReactNativeBuild(manifest) {
|
|
1356
|
+
if (typeof manifest["react-native"] === "string") return true;
|
|
1357
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1358
|
+
const search = (node) => {
|
|
1359
|
+
if (!node || typeof node !== "object" || seen.has(node)) return false;
|
|
1360
|
+
seen.add(node);
|
|
1361
|
+
for (const [key, value] of Object.entries(node)) {
|
|
1362
|
+
if (key === "react-native") return true;
|
|
1363
|
+
if (search(value)) return true;
|
|
1364
|
+
}
|
|
1365
|
+
return false;
|
|
1366
|
+
};
|
|
1367
|
+
return search(manifest.exports);
|
|
1368
|
+
}
|
|
1369
|
+
/**
|
|
1370
|
+
* A package that ships ES modules and nothing React Native.
|
|
1371
|
+
*
|
|
1372
|
+
* The closure walk is a guess: a detected package's dependencies MIGHT be untranspiled
|
|
1373
|
+
* React Native source, because the ecosystem publishes that way and the dependency's
|
|
1374
|
+
* own manifest cannot say so. `"type": "module"` is the manifest saying the opposite —
|
|
1375
|
+
* this is runnable ES modules — and with no React Native build anywhere in it, there is
|
|
1376
|
+
* nothing for the preset to do. Compiling it anyway rewrites a package that publishes
|
|
1377
|
+
* ESM into CommonJS and hands it to Node under that format, which is how a dependency
|
|
1378
|
+
* reached this way (`zod`) failed to parse and took fourteen test files down with it.
|
|
1379
|
+
*
|
|
1380
|
+
* A genuine React Native library is unaffected: declaring `react-native` by field or
|
|
1381
|
+
* export condition keeps it in the closure however it publishes.
|
|
1382
|
+
*
|
|
1383
|
+
* Only closure MEMBERS are judged this way. A package detected on its own manifest, or
|
|
1384
|
+
* named in `transform: [...]`, was asked for explicitly and is still compiled.
|
|
1385
|
+
*/
|
|
1386
|
+
function publishesOnlyEsm(manifest) {
|
|
1387
|
+
return manifest.type === "module" && !hasReactNativeBuild(manifest);
|
|
1388
|
+
}
|
|
1389
|
+
/**
|
|
1390
|
+
* Extensions of a `react-native` field's file that plain JavaScript must parse.
|
|
1391
|
+
* TypeScript is not among them: the require hooks load it as it is.
|
|
1392
|
+
*/
|
|
1393
|
+
const PLAIN_SOURCE = [
|
|
1394
|
+
".js",
|
|
1395
|
+
".jsx",
|
|
1396
|
+
".mjs",
|
|
1397
|
+
".cjs"
|
|
1398
|
+
];
|
|
1399
|
+
const SPECIFIER = /(?:\brequire\s*\(\s*|\bimport\s*\(\s*|\bfrom\s*|\bimport\s*)["']([^"'\n]+)["']/g;
|
|
1400
|
+
const COMMENT = /\/\*[\s\S]*?\*\/|(^|[^:"'`\\])\/\/[^\n]*/g;
|
|
1401
|
+
const TYPE_ONLY = /\b(?:import|export)\s+type\b[^;]*?\bfrom\s*["'][^"']+["']/g;
|
|
1402
|
+
const RUNTIME_EXTENSIONS = [
|
|
1403
|
+
".native.js",
|
|
1404
|
+
".ios.js",
|
|
1405
|
+
".js",
|
|
1406
|
+
".mjs",
|
|
1407
|
+
".cjs",
|
|
1408
|
+
".jsx",
|
|
1409
|
+
".native.ts",
|
|
1410
|
+
".ios.ts",
|
|
1411
|
+
".ts",
|
|
1412
|
+
".native.tsx",
|
|
1413
|
+
".ios.tsx",
|
|
1414
|
+
".tsx"
|
|
1415
|
+
];
|
|
1416
|
+
const MAX_RUNTIME_FILES = 5e3;
|
|
1417
|
+
const PACKAGE_SPECIFIER = /^(?:@[\w.-]+\/)?[\w][\w.-]*(?:\/|$)/;
|
|
1418
|
+
const runtimeMemo = /* @__PURE__ */ new Map();
|
|
1419
|
+
/** The file a relative specifier names from `fromDir`, as Metro and Node find it, or null. */
|
|
1420
|
+
function runtimeFile(base) {
|
|
1421
|
+
const isFile = (file) => fs.statSync(file, { throwIfNoEntry: false })?.isFile() === true;
|
|
1422
|
+
if (isFile(base)) return base;
|
|
1423
|
+
for (const ext of RUNTIME_EXTENSIONS) if (isFile(base + ext)) return base + ext;
|
|
1424
|
+
for (const ext of RUNTIME_EXTENSIONS) {
|
|
1425
|
+
const index = path.join(base, `index${ext}`);
|
|
1426
|
+
if (isFile(index)) return index;
|
|
1427
|
+
}
|
|
1428
|
+
return null;
|
|
1429
|
+
}
|
|
1430
|
+
/** Every string target of a manifest's `exports` root (all conditions), or none. */
|
|
1431
|
+
function exportTargets(exportsField) {
|
|
1432
|
+
if (typeof exportsField === "string") return [exportsField];
|
|
1433
|
+
if (!exportsField || typeof exportsField !== "object") return [];
|
|
1434
|
+
const node = exportsField;
|
|
1435
|
+
const root = "." in node ? node["."] : Object.keys(node).every((k) => !k.startsWith(".")) ? node : null;
|
|
1436
|
+
const out = [];
|
|
1437
|
+
const collect = (value) => {
|
|
1438
|
+
if (typeof value === "string") out.push(value);
|
|
1439
|
+
else if (value && typeof value === "object") Object.values(value).forEach(collect);
|
|
1440
|
+
};
|
|
1441
|
+
collect(root);
|
|
1442
|
+
return out;
|
|
1443
|
+
}
|
|
1444
|
+
/**
|
|
1445
|
+
* The packages a package loads when it runs, by name: the bare specifiers in the files
|
|
1446
|
+
* reachable from its runtime entries (its `react-native` field, `main` and `exports`
|
|
1447
|
+
* root) through relative requires and imports, with comments and type-only imports left
|
|
1448
|
+
* out. Its config plugin, scripts and type declarations are not reached, so a package
|
|
1449
|
+
* that names another only there (expo-constants' `expo`, from `expo/config`) does not
|
|
1450
|
+
* load it. Read once per directory and process. For the peer edge only (see the closure
|
|
1451
|
+
* walk).
|
|
1452
|
+
*/
|
|
1453
|
+
function runtimeImports(dir, manifest) {
|
|
1454
|
+
let names = runtimeMemo.get(dir);
|
|
1455
|
+
if (names) return names;
|
|
1456
|
+
names = /* @__PURE__ */ new Set();
|
|
1457
|
+
const entries = [
|
|
1458
|
+
typeof manifest["react-native"] === "string" ? manifest["react-native"] : null,
|
|
1459
|
+
typeof manifest.main === "string" ? manifest.main : null,
|
|
1460
|
+
...exportTargets(manifest.exports)
|
|
1461
|
+
].filter((entry) => entry !== null);
|
|
1462
|
+
if (entries.length === 0) entries.push("index");
|
|
1463
|
+
const pending = entries.map((entry) => runtimeFile(path.resolve(dir, entry))).filter((file) => file !== null && containsPath(dir, file));
|
|
1464
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1465
|
+
while (pending.length > 0 && seen.size < MAX_RUNTIME_FILES) {
|
|
1466
|
+
const file = pending.pop();
|
|
1467
|
+
if (seen.has(file) || file.endsWith(".json")) continue;
|
|
1468
|
+
seen.add(file);
|
|
1469
|
+
const code = fs.readFileSync(file, "utf8").replace(COMMENT, "$1").replace(TYPE_ONLY, "");
|
|
1470
|
+
for (const match of code.matchAll(SPECIFIER)) {
|
|
1471
|
+
const specifier = match[1];
|
|
1472
|
+
if (specifier.startsWith(".")) {
|
|
1473
|
+
const target = runtimeFile(path.resolve(path.dirname(file), specifier));
|
|
1474
|
+
if (target !== null && containsPath(dir, target) && !NODE_MODULES_DIR.test(path.relative(dir, target))) pending.push(target);
|
|
1475
|
+
} else if (PACKAGE_SPECIFIER.test(specifier)) {
|
|
1476
|
+
const parts = specifier.split("/");
|
|
1477
|
+
names.add(specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0]);
|
|
1478
|
+
}
|
|
1479
|
+
}
|
|
1480
|
+
}
|
|
1481
|
+
runtimeMemo.set(dir, names);
|
|
1482
|
+
return names;
|
|
1483
|
+
}
|
|
1484
|
+
/** Manifest fields that make a package part of the React Native ecosystem. */
|
|
1485
|
+
function dependsOnReactNative(manifest) {
|
|
1486
|
+
for (const field of ["dependencies", "peerDependencies"]) {
|
|
1487
|
+
const deps = manifest[field];
|
|
1488
|
+
if (deps && typeof deps === "object" && "react-native" in deps) return true;
|
|
1489
|
+
}
|
|
1490
|
+
return false;
|
|
1491
|
+
}
|
|
1492
|
+
/**
|
|
1493
|
+
* Every package manifest from the project up to the filesystem root.
|
|
1494
|
+
*
|
|
1495
|
+
* A workspace does not always declare its dependencies where the tests run: an app
|
|
1496
|
+
* package may inherit React Native libraries from the repository root, and a Vitest
|
|
1497
|
+
* `root` can point at a directory above or below the package that owns them. Reading
|
|
1498
|
+
* only the project's own manifest silently found nothing in those layouts and sent
|
|
1499
|
+
* the user back to maintaining `transform: [...]` by hand.
|
|
1500
|
+
*
|
|
1501
|
+
* Over-collecting is safe and under-collecting is not: a package that is listed but
|
|
1502
|
+
* never imported costs nothing, because inlining only applies to files that are
|
|
1503
|
+
* actually loaded.
|
|
1504
|
+
*/
|
|
1505
|
+
/**
|
|
1506
|
+
* Directories of the workspace members a manifest declares, plus any listed in a
|
|
1507
|
+
* sibling pnpm-workspace.yaml.
|
|
1508
|
+
*
|
|
1509
|
+
* Needed because `manifestsFrom` only walks UP. In a workspace the run root is
|
|
1510
|
+
* frequently ABOVE the package under test — Nx invokes tasks from the workspace
|
|
1511
|
+
* root, and Vitest's root defaults to the working directory — so the app's own
|
|
1512
|
+
* dependencies are declared in a manifest that walking up never reaches. The
|
|
1513
|
+
* package then misses auto-detection and stays in Vite's graph while Node loads it
|
|
1514
|
+
* too, which is the dual-ownership failure reproducing from nothing but a different
|
|
1515
|
+
* working directory.
|
|
1516
|
+
*
|
|
1517
|
+
* Only the two glob shapes workspace fields actually use are expanded (`dir/*` and a
|
|
1518
|
+
* literal path). Over-collecting is safe here — an unimported package costs nothing —
|
|
1519
|
+
* so a shape that is not understood is skipped rather than approximated.
|
|
1520
|
+
*/
|
|
1521
|
+
function workspaceMemberDirs(dir, manifest) {
|
|
1522
|
+
const patterns = [];
|
|
1523
|
+
const declared = manifest.workspaces;
|
|
1524
|
+
if (Array.isArray(declared)) patterns.push(...declared.filter((p) => typeof p === "string"));
|
|
1525
|
+
else if (declared && typeof declared === "object" && Array.isArray(declared.packages)) patterns.push(...declared.packages.filter((p) => typeof p === "string"));
|
|
1526
|
+
try {
|
|
1527
|
+
const yaml = fs.readFileSync(path.join(dir, "pnpm-workspace.yaml"), "utf8");
|
|
1528
|
+
for (const line of yaml.split(/\r?\n/)) {
|
|
1529
|
+
const entry = /^\s*-\s*["']?([^"'#]+?)["']?\s*$/.exec(line);
|
|
1530
|
+
if (entry) patterns.push(entry[1]);
|
|
1531
|
+
}
|
|
1532
|
+
} catch {}
|
|
1533
|
+
const dirs = [];
|
|
1534
|
+
for (const pattern of patterns) if (pattern.endsWith("/*")) {
|
|
1535
|
+
const parent = path.join(dir, pattern.slice(0, -2));
|
|
1536
|
+
try {
|
|
1537
|
+
for (const entry of fs.readdirSync(parent, { withFileTypes: true })) if (entry.isDirectory()) dirs.push(path.join(parent, entry.name));
|
|
1538
|
+
} catch {}
|
|
1539
|
+
} else if (!pattern.includes("*")) dirs.push(path.join(dir, pattern));
|
|
1540
|
+
return dirs;
|
|
1541
|
+
}
|
|
1542
|
+
function manifestsFrom(projectRoot) {
|
|
1543
|
+
const manifests = [];
|
|
1544
|
+
let dir = path.resolve(projectRoot);
|
|
1545
|
+
for (;;) {
|
|
1546
|
+
try {
|
|
1547
|
+
const raw = fs.readFileSync(path.join(dir, "package.json"), "utf8");
|
|
1548
|
+
const manifest = JSON.parse(raw);
|
|
1549
|
+
manifests.push({
|
|
1550
|
+
dir,
|
|
1551
|
+
manifest
|
|
1552
|
+
});
|
|
1553
|
+
for (const member of workspaceMemberDirs(dir, manifest)) try {
|
|
1554
|
+
manifests.push({
|
|
1555
|
+
dir: member,
|
|
1556
|
+
manifest: JSON.parse(fs.readFileSync(path.join(member, "package.json"), "utf8"))
|
|
1557
|
+
});
|
|
1558
|
+
} catch {}
|
|
1559
|
+
} catch {}
|
|
1560
|
+
const parent = path.dirname(dir);
|
|
1561
|
+
if (parent === dir) return manifests;
|
|
1562
|
+
dir = parent;
|
|
1563
|
+
}
|
|
1564
|
+
}
|
|
1565
|
+
/**
|
|
1566
|
+
* The paths a `resolve.alias` config points into, whatever each entry's `find` is: a
|
|
1567
|
+
* string, or a RegExp (an alias Vite applies to imports, which `jest.requireActual`
|
|
1568
|
+
* cannot, so serializableAliases leaves it out of the compat layer's list). These seed
|
|
1569
|
+
* the closure walk through the workspace members that contain them (ReachedPackages).
|
|
1570
|
+
*
|
|
1571
|
+
* A replacement may substitute part of the match (`/abs/packages/ui/src$1`): only the
|
|
1572
|
+
* text before its first substitution is fixed (fixedReplacement), and that part is the
|
|
1573
|
+
* path the alias reaches. A substitution that chooses the member (`/abs/packages/$1`)
|
|
1574
|
+
* leaves a fixed part above every member, so it reaches none: walking every member such
|
|
1575
|
+
* an alias could produce is the "seed from every member" #433 rejected. A `$` that is
|
|
1576
|
+
* not a substitution (`/home/ci/$work`, a `c$` share) is part of the path. A replacement
|
|
1577
|
+
* starting with `.` is taken from `root`, as the compat layer takes it; anything else
|
|
1578
|
+
* that is not absolute (a package name) reaches no member.
|
|
1579
|
+
*
|
|
1580
|
+
* Plugins that resolve through `resolveId` (vite-tsconfig-paths, nxViteTsPaths) add no
|
|
1581
|
+
* alias entry, so they are out of reach here by construction.
|
|
1582
|
+
*/
|
|
1583
|
+
function aliasReachedPaths(alias, root) {
|
|
1584
|
+
const list = Array.isArray(alias) ? alias : alias && typeof alias === "object" ? Object.entries(alias).map(([find, replacement]) => ({
|
|
1585
|
+
find,
|
|
1586
|
+
replacement
|
|
1587
|
+
})) : [];
|
|
1588
|
+
const reached = [];
|
|
1589
|
+
for (const item of list) {
|
|
1590
|
+
const entry = item;
|
|
1591
|
+
const replacement = entry?.replacement;
|
|
1592
|
+
if (typeof replacement !== "string") continue;
|
|
1593
|
+
const fixed = fixedReplacement(replacement, entry?.find instanceof RegExp);
|
|
1594
|
+
const target = fixed.startsWith(".") ? path.resolve(root, fixed) : fixed;
|
|
1595
|
+
if (target && path.isAbsolute(target)) reached.push(target);
|
|
1596
|
+
}
|
|
1597
|
+
return reached;
|
|
1598
|
+
}
|
|
1599
|
+
/**
|
|
1600
|
+
* The text of an alias replacement up to its first substitution, with `$$` read as `$`.
|
|
1601
|
+
* Vite applies an alias with `String.prototype.replace`, which substitutes `$&`, `` $` ``
|
|
1602
|
+
* and `$'` for any pattern, and `$n` and `$<name>` for a RegExp; every other `$` is
|
|
1603
|
+
* literal (with a string pattern, `$1` is too).
|
|
1604
|
+
*/
|
|
1605
|
+
function fixedReplacement(replacement, regExp) {
|
|
1606
|
+
let fixed = "";
|
|
1607
|
+
for (let i = 0; i < replacement.length; i++) {
|
|
1608
|
+
const char = replacement[i];
|
|
1609
|
+
if (char !== "$") {
|
|
1610
|
+
fixed += char;
|
|
1611
|
+
continue;
|
|
1612
|
+
}
|
|
1613
|
+
const next = replacement[i + 1] ?? "";
|
|
1614
|
+
if (next === "$") {
|
|
1615
|
+
fixed += "$";
|
|
1616
|
+
i++;
|
|
1617
|
+
} else if (next === "&" || next === "`" || next === "'") break;
|
|
1618
|
+
else if (regExp && (/[0-9]/.test(next) || next === "<")) break;
|
|
1619
|
+
else fixed += "$";
|
|
1620
|
+
}
|
|
1621
|
+
return fixed;
|
|
1622
|
+
}
|
|
1623
|
+
/**
|
|
1624
|
+
* Packages in the project that declare React Native in their own manifest.
|
|
1625
|
+
*
|
|
1626
|
+
* These are the ones published the way the React Native ecosystem publishes:
|
|
1627
|
+
* untranspiled JSX, Flow, or TypeScript, on the assumption that Metro will compile
|
|
1628
|
+
* them. Node cannot run that source, which is why they previously had to be listed
|
|
1629
|
+
* by hand in `transform: [...]` — a list every project had to discover the hard way,
|
|
1630
|
+
* one `SyntaxError: Unexpected token '<'` at a time.
|
|
1631
|
+
*
|
|
1632
|
+
* A package's own manifest is the authority here rather than a heuristic on its
|
|
1633
|
+
* name: `react-native-*` misses `@gorhom/bottom-sheet` and would wrongly claim
|
|
1634
|
+
* `react-native` itself, while the manifest states the relationship exactly.
|
|
1635
|
+
*
|
|
1636
|
+
* Declared dependencies are read from the project and every manifest above it, so a
|
|
1637
|
+
* workspace that declares its React Native libraries at the repository root is covered
|
|
1638
|
+
* too. Resolving each name is cheap and package-manager-agnostic, where walking the
|
|
1639
|
+
* installed tree depends on the store layout. Transitive dependencies that nothing
|
|
1640
|
+
* declares stay available through `transform: [...]`.
|
|
1641
|
+
*
|
|
1642
|
+
* Excluded: packages a preset already shadows (their real source never loads), the
|
|
1643
|
+
* test infrastructure in NEVER_INLINE, and anything the consumer listed explicitly
|
|
1644
|
+
* in `transform` — that option keeps its existing meaning and takes precedence.
|
|
1645
|
+
*
|
|
1646
|
+
* `dirOf` finds a dependency's directory from a directory: `dependencyDirOf`, or a
|
|
1647
|
+
* memoized copy of it (memoizePackageDirOf). Not `packageDirOf`, whose answer for a
|
|
1648
|
+
* workspace member differs (see dependencyDirOf).
|
|
1649
|
+
*
|
|
1650
|
+
* `reachedPaths` adds the workspace members an alias reaches; see ReachedPackages.
|
|
1651
|
+
*/
|
|
1652
|
+
function detectEcosystemPackages(projectRoot, explicit = [], testRoots = [], neverTransform = [], activePresets, dirOf = dependencyDirOf, { reachedPaths = [], onReachedUndeclared, compileReactNativeFieldSource } = {}) {
|
|
1653
|
+
runtimeMemo.clear();
|
|
1654
|
+
const roots = (Array.isArray(projectRoot) ? projectRoot : [projectRoot]).filter(Boolean);
|
|
1655
|
+
const shadowed = Object.entries(AUTO_DETECT_PRESETS).filter(([, presetName]) => activePresets === void 0 || activePresets.includes(presetName)).map(([pkg]) => pkg);
|
|
1656
|
+
const skip = /* @__PURE__ */ new Set([
|
|
1657
|
+
...NEVER_INLINE,
|
|
1658
|
+
...shadowed,
|
|
1659
|
+
...explicit,
|
|
1660
|
+
...neverTransform
|
|
1661
|
+
]);
|
|
1662
|
+
const candidates = /* @__PURE__ */ new Set();
|
|
1663
|
+
const found = roots.flatMap((root) => manifestsFrom(root));
|
|
1664
|
+
const declaringDirs = [...new Set(found.map((entry) => entry.dir))];
|
|
1665
|
+
for (const { manifest } of found) for (const field of [
|
|
1666
|
+
"dependencies",
|
|
1667
|
+
"devDependencies",
|
|
1668
|
+
"optionalDependencies"
|
|
1669
|
+
]) {
|
|
1670
|
+
const deps = manifest[field];
|
|
1671
|
+
if (deps && typeof deps === "object") for (const name of Object.keys(deps)) candidates.add(name);
|
|
1672
|
+
}
|
|
1673
|
+
if (candidates.size === 0) return [];
|
|
1674
|
+
const installedFrom = (fromDir, name) => {
|
|
1675
|
+
const dir = dirOf(name, fromDir);
|
|
1676
|
+
if (!dir) return null;
|
|
1677
|
+
try {
|
|
1678
|
+
return {
|
|
1679
|
+
manifest: JSON.parse(fs.readFileSync(path.join(dir, "package.json"), "utf8")),
|
|
1680
|
+
dir
|
|
1681
|
+
};
|
|
1682
|
+
} catch {
|
|
1683
|
+
return null;
|
|
1684
|
+
}
|
|
1685
|
+
};
|
|
1686
|
+
/** Resolve a package's manifest from whichever root can see it. */
|
|
1687
|
+
const installedOf = (name) => {
|
|
1688
|
+
for (const dir of declaringDirs) {
|
|
1689
|
+
const installed = installedFrom(dir, name);
|
|
1690
|
+
if (installed) return installed;
|
|
1691
|
+
}
|
|
1692
|
+
return null;
|
|
1693
|
+
};
|
|
1694
|
+
const manifestOf = (name) => installedOf(name)?.manifest ?? null;
|
|
1695
|
+
const dependencyOf = (parent, name) => installedFrom(parent.dir, name);
|
|
1696
|
+
/**
|
|
1697
|
+
* The packages the run itself lives in — the project, in other words.
|
|
1698
|
+
*
|
|
1699
|
+
* In a workspace, the package under test is usually declared as a dependency by a
|
|
1700
|
+
* sibling or by the repository root, so it appears in the candidate set like any
|
|
1701
|
+
* third-party library — and it declares React Native, because it is React Native
|
|
1702
|
+
* code. Detecting it would claim the project's own source: its directory becomes a
|
|
1703
|
+
* `server.deps.external` pattern, so Vitest hands every file under it to Node,
|
|
1704
|
+
* where the loader compiles it to CommonJS. A test file's own
|
|
1705
|
+
* `import { it } from 'vitest'` becomes `require('vitest')`, which throws
|
|
1706
|
+
* "Vitest cannot be imported in a CommonJS module using require()" — a failure that
|
|
1707
|
+
* appears in one workspace package and not another for no visible reason.
|
|
1708
|
+
*
|
|
1709
|
+
* A package cannot be its own dependency, so a manifest whose directory contains a
|
|
1710
|
+
* run root belongs to the project. Read straight off the manifests already walked,
|
|
1711
|
+
* which is both cheaper than resolving each candidate and independent of how a
|
|
1712
|
+
* package manager happens to lay out its store — under pnpm every workspace member
|
|
1713
|
+
* is additionally linked into a hidden directory on NODE_PATH, so a package can
|
|
1714
|
+
* resolve its own name from its own directory, but nothing here depends on that.
|
|
1715
|
+
*
|
|
1716
|
+
* Workspace libraries the project merely depends on sit beside a run root rather
|
|
1717
|
+
* than above it and are unaffected — detecting those is the point of the
|
|
1718
|
+
* workspace-member walk above.
|
|
1719
|
+
*/
|
|
1720
|
+
const ownerRoots = [...roots, ...testRoots];
|
|
1721
|
+
const runOwners = new Set(found.filter(({ dir }) => ownerRoots.some((root) => containsPath(dir, root))).map(({ manifest }) => manifest.name).filter((name) => typeof name === "string"));
|
|
1722
|
+
const ownsTheRun = (name) => runOwners.has(name);
|
|
1723
|
+
const detected = [];
|
|
1724
|
+
for (const name of candidates) {
|
|
1725
|
+
if (skip.has(name) || name.startsWith("@react-native/")) continue;
|
|
1726
|
+
const pkg = manifestOf(name);
|
|
1727
|
+
if (pkg && dependsOnReactNative(pkg) && !ownsTheRun(name)) detected.push(name);
|
|
1728
|
+
}
|
|
1729
|
+
const rnOwned = new Set(Object.keys(manifestOf("react-native")?.dependencies ?? {}));
|
|
1730
|
+
/** Every package reachable from `starts` through runtime dependencies. */
|
|
1731
|
+
const closureOf = (starts) => {
|
|
1732
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1733
|
+
const pending = [...starts];
|
|
1734
|
+
while (pending.length > 0) {
|
|
1735
|
+
const [name, installed] = pending.pop();
|
|
1736
|
+
if (seen.has(name)) continue;
|
|
1737
|
+
seen.add(name);
|
|
1738
|
+
const deps = installed?.manifest.dependencies;
|
|
1739
|
+
if (!installed || !deps || typeof deps !== "object") continue;
|
|
1740
|
+
for (const dep of Object.keys(deps)) if (!seen.has(dep)) pending.push([dep, dependencyOf(installed, dep)]);
|
|
1741
|
+
}
|
|
1742
|
+
return seen;
|
|
1743
|
+
};
|
|
1744
|
+
const reactNativeInstalled = installedOf("react-native");
|
|
1745
|
+
const expoInstalled = installedOf("expo");
|
|
1746
|
+
const seed = (name) => [name, installedOf(name) ?? (reactNativeInstalled && dependencyOf(reactNativeInstalled, name)) ?? (expoInstalled && dependencyOf(expoInstalled, name))];
|
|
1747
|
+
const toolchain = closureOf([
|
|
1748
|
+
seed("@babel/core"),
|
|
1749
|
+
seed("@react-native/babel-preset"),
|
|
1750
|
+
seed("babel-preset-expo"),
|
|
1751
|
+
seed("@babel/runtime"),
|
|
1752
|
+
seed("metro"),
|
|
1753
|
+
seed("@expo/metro")
|
|
1754
|
+
]);
|
|
1755
|
+
const projectDeclared = /* @__PURE__ */ new Set();
|
|
1756
|
+
for (const { dir, manifest } of found) {
|
|
1757
|
+
if (!ownerRoots.some((root) => containsPath(dir, root))) continue;
|
|
1758
|
+
for (const field of [
|
|
1759
|
+
"dependencies",
|
|
1760
|
+
"devDependencies",
|
|
1761
|
+
"optionalDependencies"
|
|
1762
|
+
]) {
|
|
1763
|
+
const deps = manifest[field];
|
|
1764
|
+
if (deps && typeof deps === "object") for (const name of Object.keys(deps)) projectDeclared.add(name);
|
|
1765
|
+
}
|
|
1766
|
+
}
|
|
1767
|
+
const detectedSet = new Set(detected);
|
|
1768
|
+
const inClosure = new Set(detected);
|
|
1769
|
+
const walked = /* @__PURE__ */ new Set();
|
|
1770
|
+
const queue = [];
|
|
1771
|
+
const reach = (name, installed) => {
|
|
1772
|
+
inClosure.add(name);
|
|
1773
|
+
if (walked.has(name)) return;
|
|
1774
|
+
walked.add(name);
|
|
1775
|
+
queue.push(installed);
|
|
1776
|
+
};
|
|
1777
|
+
for (const name of detected) {
|
|
1778
|
+
if (!projectDeclared.has(name)) continue;
|
|
1779
|
+
const installed = installedOf(name);
|
|
1780
|
+
if (installed) reach(name, installed);
|
|
1781
|
+
}
|
|
1782
|
+
const neverSeeded = /* @__PURE__ */ new Set([...shadowed, ...neverTransform]);
|
|
1783
|
+
for (const name of explicit) {
|
|
1784
|
+
if (neverSeeded.has(name)) continue;
|
|
1785
|
+
const installed = installedOf(name);
|
|
1786
|
+
if (!installed || walked.has(name)) continue;
|
|
1787
|
+
walked.add(name);
|
|
1788
|
+
queue.push(installed);
|
|
1789
|
+
}
|
|
1790
|
+
/** A dependency or peer the walk may not take, whatever its manifest says. */
|
|
1791
|
+
const excluded = (dep) => skip.has(dep) || dep.startsWith("@react-native/") || rnOwned.has(dep) || toolchain.has(dep) || ownsTheRun(dep);
|
|
1792
|
+
/**
|
|
1793
|
+
* Walk the queue. With `installedOnly`, only installed packages (a real path inside a
|
|
1794
|
+
* node_modules directory) are added: see "Workspace members the run reaches" below.
|
|
1795
|
+
*/
|
|
1796
|
+
const walk = (installedOnly) => {
|
|
1797
|
+
const admits = (installed) => !installedOnly || NODE_MODULES_DIR.test(installed.dir);
|
|
1798
|
+
while (queue.length > 0) {
|
|
1799
|
+
const pkg = queue.pop();
|
|
1800
|
+
const deps = pkg.manifest.dependencies;
|
|
1801
|
+
for (const dep of deps && typeof deps === "object" ? Object.keys(deps) : []) {
|
|
1802
|
+
if (walked.has(dep) || excluded(dep)) continue;
|
|
1803
|
+
const installed = dependencyOf(pkg, dep);
|
|
1804
|
+
if (!installed) continue;
|
|
1805
|
+
if (!inClosure.has(dep) && publishesOnlyEsm(installed.manifest)) continue;
|
|
1806
|
+
if (admits(installed)) reach(dep, installed);
|
|
1807
|
+
}
|
|
1808
|
+
const peers = pkg.manifest.peerDependencies;
|
|
1809
|
+
const peersMeta = pkg.manifest.peerDependenciesMeta;
|
|
1810
|
+
for (const peer of peers && typeof peers === "object" ? Object.keys(peers) : []) {
|
|
1811
|
+
if (walked.has(peer) || excluded(peer)) continue;
|
|
1812
|
+
const installed = dependencyOf(pkg, peer);
|
|
1813
|
+
if (!installed || !admits(installed)) continue;
|
|
1814
|
+
const loadedReactNativePeer = !detectedSet.has(peer) && peersMeta?.[peer]?.optional !== true && dependsOnReactNative(installed.manifest) && runtimeImports(pkg.dir, pkg.manifest).has(peer);
|
|
1815
|
+
if (detectedSet.has(peer) || loadedReactNativePeer) reach(peer, installed);
|
|
1816
|
+
}
|
|
1817
|
+
}
|
|
1818
|
+
};
|
|
1819
|
+
walk(false);
|
|
1820
|
+
const members = found.filter(({ dir, manifest }) => typeof manifest.name === "string" && !ownerRoots.some((root) => containsPath(dir, root)));
|
|
1821
|
+
const memberByName = new Map(members.map((m) => [m.manifest.name, m]));
|
|
1822
|
+
const reachedMembers = /* @__PURE__ */ new Map();
|
|
1823
|
+
const reachMember = (member) => {
|
|
1824
|
+
if (reachedMembers.has(member.dir)) return;
|
|
1825
|
+
reachedMembers.set(member.dir, member);
|
|
1826
|
+
const deps = member.manifest.dependencies;
|
|
1827
|
+
for (const dep of deps && typeof deps === "object" ? Object.keys(deps) : []) {
|
|
1828
|
+
const other = memberByName.get(dep);
|
|
1829
|
+
if (other) reachMember(other);
|
|
1830
|
+
}
|
|
1831
|
+
};
|
|
1832
|
+
for (const name of projectDeclared) {
|
|
1833
|
+
const member = memberByName.get(name);
|
|
1834
|
+
if (member) reachMember(member);
|
|
1835
|
+
}
|
|
1836
|
+
for (const target of reachedPaths) {
|
|
1837
|
+
const member = members.filter(({ dir }) => containsPath(dir, target)).sort((a, b) => b.dir.length - a.dir.length)[0];
|
|
1838
|
+
if (!member) continue;
|
|
1839
|
+
if (!reachedMembers.has(member.dir)) onReachedUndeclared?.(member.manifest.name, member.dir);
|
|
1840
|
+
reachMember(member);
|
|
1841
|
+
}
|
|
1842
|
+
for (const member of reachedMembers.values()) {
|
|
1843
|
+
const deps = member.manifest.dependencies;
|
|
1844
|
+
for (const dep of deps && typeof deps === "object" ? Object.keys(deps) : []) {
|
|
1845
|
+
if (walked.has(dep) || excluded(dep) || !detectedSet.has(dep)) continue;
|
|
1846
|
+
const installed = installedFrom(member.dir, dep);
|
|
1847
|
+
if (installed) reach(dep, installed);
|
|
1848
|
+
}
|
|
1849
|
+
}
|
|
1850
|
+
walk(true);
|
|
1851
|
+
if (compileReactNativeFieldSource) {
|
|
1852
|
+
let parse;
|
|
1853
|
+
for (const name of projectDeclared) {
|
|
1854
|
+
if (inClosure.has(name) || excluded(name) || ownsTheRun(name)) continue;
|
|
1855
|
+
if (compileReactNativeFieldSource.resolvedToMain?.includes(name)) continue;
|
|
1856
|
+
const installed = installedOf(name);
|
|
1857
|
+
if (!installed || !NODE_MODULES_DIR.test(installed.dir)) continue;
|
|
1858
|
+
if (installed.manifest.exports != null) continue;
|
|
1859
|
+
const field = installed.manifest["react-native"];
|
|
1860
|
+
if (typeof field !== "string") continue;
|
|
1861
|
+
const file = mainFieldFile(path.resolve(installed.dir, field), compileReactNativeFieldSource.platform, compileReactNativeFieldSource.sourceExts);
|
|
1862
|
+
parse ??= babelParser(roots[0]) ?? false;
|
|
1863
|
+
if (file && PLAIN_SOURCE.includes(path.extname(file)) && parse && !isPlainJavaScript(parse, file)) inClosure.add(name);
|
|
1864
|
+
}
|
|
1865
|
+
}
|
|
1866
|
+
return [...inClosure].sort();
|
|
1867
|
+
}
|
|
1868
|
+
// src/host.ts
|
|
1869
|
+
/** The running Vite's version, and where it was read, for messages that name it. */
|
|
1870
|
+
async function runningVite(context) {
|
|
1871
|
+
const fromHost = context?.meta?.viteVersion;
|
|
1872
|
+
return typeof fromHost === "string" ? {
|
|
1873
|
+
version: fromHost,
|
|
1874
|
+
source: "the running Vite"
|
|
1875
|
+
} : null;
|
|
1876
|
+
}
|
|
1877
|
+
/**
|
|
1878
|
+
* The version of Vite installed where `root` resolves it, read from the module, for
|
|
1879
|
+
* diagnostics that run without a Vite process (`doctor`, `migrate`). Falls back to the
|
|
1880
|
+
* manifest, preferring the Vite version a wrapper records it bundles.
|
|
1881
|
+
*/
|
|
1882
|
+
function installedViteVersion(root) {
|
|
1883
|
+
const req = createRequire(path.join(root, "package.json"));
|
|
1884
|
+
try {
|
|
1885
|
+
const version = req("vite").version;
|
|
1886
|
+
if (typeof version === "string") return version;
|
|
1887
|
+
} catch {}
|
|
1888
|
+
try {
|
|
1889
|
+
const manifest = req("vite/package.json");
|
|
1890
|
+
return manifest.bundledVersions?.vite ?? manifest.version ?? null;
|
|
1891
|
+
} catch {
|
|
1892
|
+
return null;
|
|
1893
|
+
}
|
|
1894
|
+
}
|
|
1895
|
+
/** Whether the project at `root` runs its tests through Vite+. */
|
|
1896
|
+
function usesVitePlus(root) {
|
|
1897
|
+
try {
|
|
1898
|
+
createRequire(path.join(root, "package.json")).resolve("vite-plus/package.json");
|
|
1899
|
+
return true;
|
|
1900
|
+
} catch {
|
|
1901
|
+
return false;
|
|
1902
|
+
}
|
|
1903
|
+
}
|
|
1904
|
+
/** The `vitest` package this package's own files resolve by name, or null. */
|
|
1905
|
+
function ownVitestPackage() {
|
|
1906
|
+
try {
|
|
1907
|
+
const req = createRequire(import.meta.url);
|
|
1908
|
+
const manifest = req.resolve("vitest/package.json");
|
|
1909
|
+
const { version } = req(manifest);
|
|
1910
|
+
return {
|
|
1911
|
+
root: realPath(path.dirname(manifest)),
|
|
1912
|
+
version
|
|
1913
|
+
};
|
|
1914
|
+
} catch {
|
|
1915
|
+
return null;
|
|
1916
|
+
}
|
|
1917
|
+
}
|
|
1918
|
+
/**
|
|
1919
|
+
* A path's canonical spelling. `realpathSync.native` asks the OS, which returns the long
|
|
1920
|
+
* on-disk spelling (no 8.3 short names) and the on-disk case on Windows and macOS. It is
|
|
1921
|
+
* what the error messages show.
|
|
1922
|
+
*/
|
|
1923
|
+
function realPath(file) {
|
|
1924
|
+
return fs.realpathSync.native(file);
|
|
1925
|
+
}
|
|
1926
|
+
/** Whether two canonical paths are one directory: without case on Windows, as NTFS looks up. */
|
|
1927
|
+
function samePath(a, b) {
|
|
1928
|
+
return process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b;
|
|
1929
|
+
}
|
|
1930
|
+
/** The directory of the package that contains `file`, by its nearest package.json. */
|
|
1931
|
+
function packageRootOf(file) {
|
|
1932
|
+
let dir = realPath(file);
|
|
1933
|
+
const start = dir;
|
|
1934
|
+
for (;;) {
|
|
1935
|
+
if (fs.existsSync(path.join(dir, "package.json"))) return dir;
|
|
1936
|
+
const parent = path.dirname(dir);
|
|
1937
|
+
if (parent === dir) return start;
|
|
1938
|
+
dir = parent;
|
|
1939
|
+
}
|
|
1940
|
+
}
|
|
1941
|
+
function twinError(running, other, via, alternative = "") {
|
|
1942
|
+
return new VitestNativeError("VITEST_TWIN_INSTANCE", `Two copies of Vitest are installed, and ${via} loads the one that is not running.\n running: vitest@${running.version} at ${running.root}\n loaded: ${other}\nSuites register with a Vitest that is not collecting them, so every test file would fail. Install one Vitest that both resolve, for example by removing the project's own \`vitest\` when a wrapper such as Vite+ provides it, or by deduplicating the install.` + alternative);
|
|
1943
|
+
}
|
|
1944
|
+
/**
|
|
1945
|
+
* Fail fast when what the host actually loads for vitest-native's own `import 'vitest'`
|
|
1946
|
+
* is not the running Vitest.
|
|
1947
|
+
*
|
|
1948
|
+
* A second physical copy is not a problem by itself: Vitest's own resolver maps every
|
|
1949
|
+
* `vitest` import in a module it runs (setup files included) to the running copy, which
|
|
1950
|
+
* is how peer-variant installs (two copies of the same version) work. So the question is
|
|
1951
|
+
* put to the host, through the project's Vite resolver, for the file that imports it.
|
|
1952
|
+
*/
|
|
1953
|
+
async function assertHostResolvesRunningVitest(running, resolveId, importer) {
|
|
1954
|
+
const resolved = await resolveId("vitest", importer);
|
|
1955
|
+
const id = typeof resolved === "string" ? resolved : resolved?.id;
|
|
1956
|
+
if (!id || !path.isAbsolute(id) || !fs.existsSync(id)) return;
|
|
1957
|
+
const runningRoot = packageRootOf(running.distPath);
|
|
1958
|
+
const loadedRoot = packageRootOf(id);
|
|
1959
|
+
if (samePath(loadedRoot, runningRoot)) return;
|
|
1960
|
+
throw twinError({
|
|
1961
|
+
root: runningRoot,
|
|
1962
|
+
version: running.version
|
|
1963
|
+
}, loadedRoot, "the Vite resolver, for vitest-native's setup file,");
|
|
1964
|
+
}
|
|
1965
|
+
/**
|
|
1966
|
+
* Fail fast when the hot runtime's worker, which Node loads directly and so outside
|
|
1967
|
+
* Vitest's resolver, would import a different physical copy of Vitest from the running
|
|
1968
|
+
* one.
|
|
1969
|
+
*/
|
|
1970
|
+
function assertHotWorkerLoadsRunningVitest(running, workerEntry) {
|
|
1971
|
+
let manifest;
|
|
1972
|
+
try {
|
|
1973
|
+
manifest = createRequire(workerEntry).resolve("vitest/package.json");
|
|
1974
|
+
} catch {
|
|
1975
|
+
return;
|
|
1976
|
+
}
|
|
1977
|
+
const runningRoot = packageRootOf(running.distPath);
|
|
1978
|
+
const loadedRoot = realPath(path.dirname(manifest));
|
|
1979
|
+
if (samePath(loadedRoot, runningRoot)) return;
|
|
1980
|
+
throw twinError({
|
|
1981
|
+
root: runningRoot,
|
|
1982
|
+
version: running.version
|
|
1983
|
+
}, loadedRoot, "the hot runtime's worker", " Or set `hotRuntime: false`: per-file isolation loads Vitest through Vitest's own resolver, which reaches the running copy.");
|
|
1984
|
+
}
|
|
1985
|
+
export { unsupportedExpoSdkMessage as A, assertSupportedNode as C, SUPPORTED_EXPO_SDKS as D, PEER_REQUIREMENTS as E, validateOptions as M, validatePeerDependency as N, installedExpoVersion as O, warnUnknownOptions as P, SUPPORTED_NODE as S, unsupportedNodeMessage as T, normalizeBabelName as _, runningVite as a, fsModuleCacheKey as b, detectEcosystemPackages as c, createProjectBabel as d, isProjectSourceFile as f, isKnownPlugin as g, classifyBabelPlugins as h, ownVitestPackage as i, unsupportedReactNativeMessage as j, isBelowSupportedReactNative as k, babelParser as l, projectBabelTrigger as m, assertHotWorkerLoadsRunningVitest as n, usesVitePlus as o, missingBabelCoreNotice as p, installedViteVersion as r, aliasReachedPaths as s, assertHostResolvesRunningVitest as t, isPlainJavaScript as u, installedManifest as v, satisfiesNodeRange as w, shouldDefaultFsModuleCache as x, detectEngine as y };
|