vitest-native 0.14.0-rc.9 → 0.14.0
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 +76 -60
- package/dist/cli.d.mts +1 -3
- package/dist/cli.mjs +175 -63
- package/dist/context.d.mts +45 -0
- package/dist/context.mjs +243 -0
- package/dist/errors.d.mts +3 -0
- package/dist/helpers.cjs +53 -4
- package/dist/helpers.d.cts +1 -3
- package/dist/helpers.d.mts +1 -3
- package/dist/helpers.mjs +2 -3
- package/dist/host-5o48Ujzs.mjs +939 -0
- package/dist/{index-CzQazgp9.d.cts → index-DqU4YO3D.d.mts} +27 -49
- package/dist/index.d.mts +1 -3
- package/dist/index.mjs +463 -595
- package/dist/jest-compat/error-equality.mjs +127 -0
- package/dist/jest-compat/jest-object.mjs +149 -4
- package/dist/jest-compat/node-registry.mjs +233 -58
- package/dist/jest-compat/setup.mjs +28 -4
- package/dist/jest-compat.cjs +227 -52
- package/dist/jest-compat.d.cts +5 -6
- package/dist/jest-compat.d.mts +5 -6
- package/dist/jest-compat.mjs +204 -52
- package/dist/matchers.cjs +1 -2
- package/dist/matchers.d.cts +0 -2
- package/dist/matchers.d.mts +0 -2
- package/dist/matchers.mjs +1 -2
- package/dist/{memory-FYbP0_gg.mjs → memory-Couw0Esx.mjs} +31 -6
- package/dist/native/assets.d.mts +2 -0
- package/dist/native/assets.mjs +34 -0
- package/dist/native/babel-toolchain.mjs +190 -0
- package/dist/native/babel-worker.mjs +47 -0
- package/dist/native/boundary.mjs +23 -8
- package/dist/native/compile-cache.mjs +21 -9
- package/dist/native/coverage-v8.mjs +287 -0
- package/dist/native/esm-interop.mjs +216 -0
- package/dist/native/expo-native-modules.mjs +7 -1
- package/dist/native/globals.mjs +104 -6
- package/dist/native/hooks.mjs +271 -60
- package/dist/native/loader.mjs +378 -20
- package/dist/native/match.d.mts +24 -2
- package/dist/native/match.mjs +117 -12
- package/dist/native/metro-profile-compiler.mjs +2 -31
- package/dist/native/module-reset.mjs +37 -5
- package/dist/native/native-modules.d.mts +2 -3
- package/dist/native/native-modules.mjs +22 -21
- package/dist/native/ownership.d.mts +10 -0
- package/dist/native/ownership.mjs +96 -9
- package/dist/native/registry-compiler.mjs +6 -0
- package/dist/native/registry.mjs +138 -119
- package/dist/native/resident-health.mjs +133 -0
- package/dist/native/resolve.d.mts +6 -0
- package/dist/native/resolve.mjs +100 -9
- package/dist/native/rntl-hooks.mjs +157 -6
- package/dist/native/rntl-text-host.mjs +64 -0
- package/dist/native/runner.mjs +73 -0
- package/dist/native/setup.mjs +96 -70
- package/dist/native/state-manifest.mjs +14 -8
- package/dist/native/transform.d.mts +2 -0
- package/dist/native/transform.mjs +476 -59
- package/dist/native/worker.mjs +65 -36
- package/dist/{pool-DjpOjOf3.mjs → pool-CFSpNfyw.mjs} +37 -11
- package/dist/{preset-map-BlBriTA0.mjs → preset-map-CogjYmSw.mjs} +4 -19
- package/dist/preset-modules.mjs +2 -11
- package/dist/{presets--zrEWQC2.mjs → presets-CXDyg51l.mjs} +65 -82
- package/dist/presets.d.mts +1 -1
- package/dist/presets.mjs +1 -1
- package/dist/report-error.d.mts +20 -0
- package/dist/report-error.mjs +145 -0
- package/dist/rntl-support.d.mts +12 -0
- package/dist/rntl-support.mjs +189 -0
- package/dist/{rolldown-runtime-BhDjJH2R.mjs → rolldown-runtime-D70C1uOS.mjs} +1 -2
- package/dist/serializer.cjs +1 -2
- package/dist/serializer.d.cts +1 -3
- package/dist/serializer.d.mts +1 -3
- package/dist/serializer.mjs +1 -2
- package/dist/setup.mjs +95 -156
- package/dist/{worker-vitest-BGPo0ek6.mjs → worker-vitest-CILPFeRX.mjs} +2 -3
- package/docs/migrating-from-jest.md +76 -12
- package/docs/release-readiness.md +1 -1
- package/package.json +119 -102
- package/CHANGELOG.md +0 -2491
- package/dist/cli.cjs +0 -1951
- package/dist/cli.d.cts +0 -3
- package/dist/ecosystem-D6e1OVOg.mjs +0 -1019
- package/dist/ecosystem-MFwkbnaC.cjs +0 -1099
- package/dist/errors-B3lJK46O.cjs +0 -75
- package/dist/errors-CxoBUfVJ.mjs +0 -64
- package/dist/index-xw43lBlv.d.mts +0 -481
- package/dist/memory-6EPHrJA1.cjs +0 -144
- package/dist/pool-B4yesGhI.cjs +0 -121
- package/dist/preset-map-jSFsNy1Q.cjs +0 -241
- package/dist/preset-modules-BoLkaeEN.cjs +0 -53
- package/dist/preset-modules-CG8-G82P.mjs +0 -36
- package/dist/presets-9f83H0WW.cjs +0 -3939
- package/dist/rolldown-runtime-C0BPl7ul.cjs +0 -43
- package/dist/worker-vitest-BfiQB8ND.cjs +0 -62
- package/docs/hot-default-design.md +0 -216
|
@@ -0,0 +1,939 @@
|
|
|
1
|
+
import { t as AUTO_DETECT_PRESETS } from "./preset-map-CogjYmSw.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 { createHash } from "node:crypto";
|
|
7
|
+
import { resolveTransformPreset } from "./native/babel-preset.mjs";
|
|
8
|
+
import { containsPath, dependencyDirOf } from "./native/match.mjs";
|
|
9
|
+
// src/validate.ts
|
|
10
|
+
const KNOWN_OPTIONS = [
|
|
11
|
+
"platform",
|
|
12
|
+
"presets",
|
|
13
|
+
"mocks",
|
|
14
|
+
"diagnostics",
|
|
15
|
+
"assetExts",
|
|
16
|
+
"metroConfig",
|
|
17
|
+
"engine",
|
|
18
|
+
"transform",
|
|
19
|
+
"hotRuntime",
|
|
20
|
+
"nativeModules"
|
|
21
|
+
];
|
|
22
|
+
const KNOWN_HOT_RUNTIME_OPTIONS = [
|
|
23
|
+
"mode",
|
|
24
|
+
"recycleAfterFiles",
|
|
25
|
+
"memoryLimit",
|
|
26
|
+
"allowUnboundedMemory",
|
|
27
|
+
"preserveGlobals",
|
|
28
|
+
"esmGeneration"
|
|
29
|
+
];
|
|
30
|
+
const KNOWN_METRO_CONFIG_OPTIONS = ["configFile"];
|
|
31
|
+
function assertStringArray(value, option) {
|
|
32
|
+
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.`);
|
|
33
|
+
}
|
|
34
|
+
function assertNonNegativeInteger(value, option) {
|
|
35
|
+
if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw new VitestNativeTypeError("INVALID_OPTION", `"${option}" must be a non-negative safe integer.`);
|
|
36
|
+
}
|
|
37
|
+
function validateOptions(options) {
|
|
38
|
+
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".`);
|
|
39
|
+
if (options.platform !== void 0 && options.platform !== "ios" && options.platform !== "android") throw new VitestNativeTypeError("INVALID_OPTION", `"platform" must be "ios" or "android".`);
|
|
40
|
+
if (options.nativeModules !== void 0 && options.nativeModules !== "device" && options.nativeModules !== "permissive") throw new VitestNativeTypeError("INVALID_OPTION", `"nativeModules" must be "device" or "permissive".`);
|
|
41
|
+
if (options.diagnostics !== void 0 && typeof options.diagnostics !== "boolean") throw new VitestNativeTypeError("INVALID_OPTION", `"diagnostics" must be a boolean.`);
|
|
42
|
+
if (options.assetExts !== void 0) assertStringArray(options.assetExts, "assetExts");
|
|
43
|
+
if (options.metroConfig !== void 0 && typeof options.metroConfig !== "boolean") {
|
|
44
|
+
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.`);
|
|
45
|
+
const metro = options.metroConfig;
|
|
46
|
+
const unknown = Object.keys(metro).filter((key) => !KNOWN_METRO_CONFIG_OPTIONS.includes(key));
|
|
47
|
+
if (unknown.length > 0) throw new VitestNativeTypeError("UNKNOWN_OPTION", `Unknown metroConfig option "${unknown[0]}". Valid options: ${KNOWN_METRO_CONFIG_OPTIONS.join(", ")}.`);
|
|
48
|
+
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.`);
|
|
49
|
+
}
|
|
50
|
+
if (options.transform !== void 0) {
|
|
51
|
+
if (Array.isArray(options.transform)) assertStringArray(options.transform, "transform");
|
|
52
|
+
else if (options.transform !== null && typeof options.transform === "object") {
|
|
53
|
+
const shape = options.transform;
|
|
54
|
+
const unknownKeys = Object.keys(shape).filter((k) => k !== "include" && k !== "exclude");
|
|
55
|
+
if (unknownKeys.length > 0) throw new VitestNativeTypeError("INVALID_OPTION", `"transform" accepts only "include" and "exclude"; received ${unknownKeys.map((k) => `"${k}"`).join(", ")}.`);
|
|
56
|
+
if (shape.include !== void 0) assertStringArray(shape.include, "transform.include");
|
|
57
|
+
if (shape.exclude !== void 0) assertStringArray(shape.exclude, "transform.exclude");
|
|
58
|
+
} else throw new VitestNativeTypeError("INVALID_OPTION", `"transform" must be an array of package names, or an object with "include" and/or "exclude".`);
|
|
59
|
+
}
|
|
60
|
+
if (options.presets !== void 0 && !Array.isArray(options.presets)) {
|
|
61
|
+
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 }).");
|
|
62
|
+
}
|
|
63
|
+
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.`);
|
|
64
|
+
const hotRuntime = options.hotRuntime;
|
|
65
|
+
if (hotRuntime === void 0 || typeof hotRuntime === "boolean" || hotRuntime === "auto") return;
|
|
66
|
+
if (hotRuntime === null || Array.isArray(hotRuntime) || typeof hotRuntime !== "object") throw new VitestNativeTypeError("INVALID_OPTION", `"hotRuntime" must be a boolean, "auto", or an options object.`);
|
|
67
|
+
const hotOptions = hotRuntime;
|
|
68
|
+
for (const key of Object.keys(hotOptions)) if (!KNOWN_HOT_RUNTIME_OPTIONS.includes(key)) {
|
|
69
|
+
const suggestion = findClosest(key, KNOWN_HOT_RUNTIME_OPTIONS);
|
|
70
|
+
throw new VitestNativeTypeError("UNKNOWN_OPTION", `Unknown hotRuntime option "${key}".` + (suggestion ? ` Did you mean '${suggestion}'?` : "") + ` Valid options: ${KNOWN_HOT_RUNTIME_OPTIONS.join(", ")}.`);
|
|
71
|
+
}
|
|
72
|
+
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.`);
|
|
73
|
+
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.");
|
|
74
|
+
if (hotOptions.recycleAfterFiles !== void 0) assertNonNegativeInteger(hotOptions.recycleAfterFiles, "hotRuntime.recycleAfterFiles");
|
|
75
|
+
if (hotOptions.memoryLimit !== void 0) assertNonNegativeInteger(hotOptions.memoryLimit, "hotRuntime.memoryLimit");
|
|
76
|
+
if (hotOptions.allowUnboundedMemory !== void 0 && typeof hotOptions.allowUnboundedMemory !== "boolean") throw new VitestNativeTypeError("INVALID_OPTION", `"hotRuntime.allowUnboundedMemory" must be a boolean.`);
|
|
77
|
+
if (hotOptions.preserveGlobals !== void 0) assertStringArray(hotOptions.preserveGlobals, "hotRuntime.preserveGlobals");
|
|
78
|
+
if (hotOptions.esmGeneration !== void 0 && typeof hotOptions.esmGeneration !== "boolean") throw new VitestNativeTypeError("INVALID_OPTION", `"hotRuntime.esmGeneration" must be a boolean.`);
|
|
79
|
+
}
|
|
80
|
+
function satisfiesMinimum(version, minimum) {
|
|
81
|
+
const parse = (v) => v.replace(/^[^0-9]*/, "").split(/[-+]/)[0].split(".").map(Number);
|
|
82
|
+
const [aMaj, aMin = 0, aPat = 0] = parse(version);
|
|
83
|
+
const [bMaj, bMin = 0, bPat = 0] = parse(minimum);
|
|
84
|
+
if (aMaj !== bMaj) return aMaj > bMaj;
|
|
85
|
+
if (aMin !== bMin) return aMin > bMin;
|
|
86
|
+
return aPat >= bPat;
|
|
87
|
+
}
|
|
88
|
+
function validatePeerDependency(pkgName, minimumVersion, projectRoot, maximumMajorExclusive, minimumByMajor, runningVersion, runningSource) {
|
|
89
|
+
const req = createRequire(path.join(projectRoot, "package.json"));
|
|
90
|
+
try {
|
|
91
|
+
const version = runningVersion ?? req(req.resolve(`${pkgName}/package.json`)).version;
|
|
92
|
+
const major = Number(version.replace(/^[^0-9]*/, "").split(".")[0]);
|
|
93
|
+
const requiredMinimum = minimumByMajor?.[major] ?? minimumVersion;
|
|
94
|
+
if (!satisfiesMinimum(version, requiredMinimum)) return `vitest-native requires ${pkgName} >= ${requiredMinimum} for ${major}.x, but found ${version}${runningVersion && runningSource ? ` (${runningSource})` : ""}. Please upgrade.`;
|
|
95
|
+
if (maximumMajorExclusive !== void 0 && major >= maximumMajorExclusive) return `vitest-native supports ${pkgName} >= ${minimumVersion} and < ${maximumMajorExclusive}, but found ${version}.`;
|
|
96
|
+
return null;
|
|
97
|
+
} catch {
|
|
98
|
+
return `vitest-native requires ${pkgName} >= ${minimumVersion}, but it was not found. Please install it.`;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
function warnUnknownOptions(options) {
|
|
102
|
+
for (const key of Object.keys(options)) if (!KNOWN_OPTIONS.includes(key)) {
|
|
103
|
+
const suggestion = findClosest(key, KNOWN_OPTIONS);
|
|
104
|
+
const hint = suggestion ? ` Did you mean '${suggestion}'?` : "";
|
|
105
|
+
console.warn(`[vitest-native] Unknown option '${key}'.${hint}`);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
function findClosest(input, candidates) {
|
|
109
|
+
let best = null;
|
|
110
|
+
let bestDist = Infinity;
|
|
111
|
+
for (const c of candidates) {
|
|
112
|
+
const d = levenshtein(input.toLowerCase(), c.toLowerCase());
|
|
113
|
+
if (d < bestDist && d <= 3) {
|
|
114
|
+
bestDist = d;
|
|
115
|
+
best = c;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
return best;
|
|
119
|
+
}
|
|
120
|
+
function levenshtein(a, b) {
|
|
121
|
+
const m = a.length;
|
|
122
|
+
const n = b.length;
|
|
123
|
+
const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
|
|
124
|
+
for (let i = 0; i <= m; i++) dp[i][0] = i;
|
|
125
|
+
for (let j = 0; j <= n; j++) dp[0][j] = j;
|
|
126
|
+
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]);
|
|
127
|
+
return dp[m][n];
|
|
128
|
+
}
|
|
129
|
+
// src/peer-requirements.ts
|
|
130
|
+
const PEER_REQUIREMENTS = [
|
|
131
|
+
{
|
|
132
|
+
name: "vitest",
|
|
133
|
+
minimum: "4.0.0",
|
|
134
|
+
maximumMajor: 6
|
|
135
|
+
},
|
|
136
|
+
{
|
|
137
|
+
name: "vite",
|
|
138
|
+
minimum: "6.4.2",
|
|
139
|
+
maximumMajor: 9,
|
|
140
|
+
minimumByMajor: {
|
|
141
|
+
6: "6.4.2",
|
|
142
|
+
7: "7.3.2",
|
|
143
|
+
8: "8.0.5"
|
|
144
|
+
}
|
|
145
|
+
},
|
|
146
|
+
{
|
|
147
|
+
name: "react",
|
|
148
|
+
minimum: "18.0.0"
|
|
149
|
+
},
|
|
150
|
+
{
|
|
151
|
+
name: "@testing-library/react-native",
|
|
152
|
+
minimum: "12.0.0",
|
|
153
|
+
maximumMajor: 15,
|
|
154
|
+
optional: true
|
|
155
|
+
}
|
|
156
|
+
];
|
|
157
|
+
/**
|
|
158
|
+
* The Expo SDKs this release supports: the ones CI installs as packed Expo apps (SDK 57
|
|
159
|
+
* and 58). Expo is not a peer of this package, so it is not in PEER_REQUIREMENTS, but the
|
|
160
|
+
* plugin's startup check and doctor read the range from here, as they do the peers'.
|
|
161
|
+
*/
|
|
162
|
+
const SUPPORTED_EXPO_SDKS = {
|
|
163
|
+
minimum: 57,
|
|
164
|
+
maximum: 58
|
|
165
|
+
};
|
|
166
|
+
/** The SDKs from `minimum` to `maximum` as a list: "57 and 58", "57, 58 or 59". */
|
|
167
|
+
function expoSdkList(conjunction, { minimum, maximum } = SUPPORTED_EXPO_SDKS) {
|
|
168
|
+
const sdks = [];
|
|
169
|
+
for (let sdk = minimum; sdk <= maximum; sdk++) sdks.push(sdk);
|
|
170
|
+
return sdks.length === 1 ? String(sdks[0]) : `${sdks.slice(0, -1).join(", ")} ${conjunction} ${sdks.at(-1)}`;
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* The version in the `expo/package.json` Node resolves from `dir`, or null. Where expo's
|
|
174
|
+
* `exports` leaves its manifest out, the package directory Node would load `expo` from,
|
|
175
|
+
* found along Node's own lookup paths.
|
|
176
|
+
*/
|
|
177
|
+
function expoVersionFrom(dir) {
|
|
178
|
+
const req = createRequire(path.join(dir, "package.json"));
|
|
179
|
+
let manifest;
|
|
180
|
+
try {
|
|
181
|
+
manifest = req.resolve("expo/package.json");
|
|
182
|
+
} catch (error) {
|
|
183
|
+
if (error.code !== "ERR_PACKAGE_PATH_NOT_EXPORTED") return null;
|
|
184
|
+
manifest = (req.resolve.paths("expo") ?? []).map((modules) => path.join(modules, "expo", "package.json")).find((file) => fs.existsSync(file));
|
|
185
|
+
}
|
|
186
|
+
if (!manifest) return null;
|
|
187
|
+
try {
|
|
188
|
+
const { version } = JSON.parse(fs.readFileSync(manifest, "utf8"));
|
|
189
|
+
return typeof version === "string" ? version : null;
|
|
190
|
+
} catch {
|
|
191
|
+
return null;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* The version of the `expo` the project at `root` uses, or null: the one Node resolves from
|
|
196
|
+
* `root`, else the one a dependency the project declares resolves as its peer. A workspace
|
|
197
|
+
* library that declares only expo-image reaches `expo` that way under an isolated install
|
|
198
|
+
* (pnpm links the peer beside expo-image, not into the library), and a library that uses
|
|
199
|
+
* no Expo package resolves none, whatever another workspace member installs. The plugin
|
|
200
|
+
* and doctor both read it from here.
|
|
201
|
+
*/
|
|
202
|
+
function installedExpoVersion(root) {
|
|
203
|
+
const own = expoVersionFrom(root);
|
|
204
|
+
if (own) return own;
|
|
205
|
+
let manifest;
|
|
206
|
+
try {
|
|
207
|
+
manifest = JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8"));
|
|
208
|
+
} catch {
|
|
209
|
+
return null;
|
|
210
|
+
}
|
|
211
|
+
const req = createRequire(path.join(root, "package.json"));
|
|
212
|
+
for (const field of ["dependencies", "devDependencies"]) {
|
|
213
|
+
const deps = manifest[field];
|
|
214
|
+
if (!deps || typeof deps !== "object") continue;
|
|
215
|
+
for (const name of Object.keys(deps)) try {
|
|
216
|
+
const file = req.resolve(`${name}/package.json`);
|
|
217
|
+
const dep = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
218
|
+
const peers = dep.peerDependencies;
|
|
219
|
+
if (!peers || typeof peers !== "object" || !("expo" in peers)) continue;
|
|
220
|
+
if (dep.peerDependenciesMeta?.expo?.optional === true) continue;
|
|
221
|
+
const version = expoVersionFrom(path.dirname(file));
|
|
222
|
+
if (version) return version;
|
|
223
|
+
} catch {}
|
|
224
|
+
}
|
|
225
|
+
return null;
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Why the installed Expo SDK is not supported, or null when it is, or when the version is
|
|
229
|
+
* not one this can read. A warning, not an error: an Expo app on an older SDK mostly runs,
|
|
230
|
+
* and failing it at startup would stop the tests that do.
|
|
231
|
+
*/
|
|
232
|
+
function unsupportedExpoSdkMessage(expoVersion) {
|
|
233
|
+
const match = /^(\d+)\.\d+\.\d+(?:[-+].*)?$/.exec(expoVersion);
|
|
234
|
+
if (!match) return null;
|
|
235
|
+
const sdk = Number(match[1]);
|
|
236
|
+
const { minimum, maximum } = SUPPORTED_EXPO_SDKS;
|
|
237
|
+
if (sdk >= minimum && sdk <= maximum) return null;
|
|
238
|
+
const supported = `vitest-native supports Expo SDK ${expoSdkList("and")}`;
|
|
239
|
+
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.`;
|
|
240
|
+
}
|
|
241
|
+
// src/fs-module-cache.ts
|
|
242
|
+
/**
|
|
243
|
+
* Vitest's persistent transform cache (`fsModuleCache`), keyed for what this plugin
|
|
244
|
+
* contributes.
|
|
245
|
+
*
|
|
246
|
+
* Vitest 5 can keep transformed modules on disk between runs, as Jest keeps its
|
|
247
|
+
* transform cache. Measured on a 104-file production Expo suite, it cut warm runs by
|
|
248
|
+
* about 11%. Vitest keys each entry on the module's id and source, the config file's
|
|
249
|
+
* contents, the plugin NAMES, `resolve`, NODE_ENV and its own version — not on plugin
|
|
250
|
+
* versions, nor on anything a plugin reads from disk. This plugin's output depends on
|
|
251
|
+
* both: its own version, and the installed packages (which presets are detected, which
|
|
252
|
+
* packages compile). Vitest's official extension point, a cache key generator, carries
|
|
253
|
+
* that part of the key:
|
|
254
|
+
* - the vitest-native version,
|
|
255
|
+
* - the plugin's resolved options and the environment it hands to workers,
|
|
256
|
+
* - the project's lockfile(s), so any dependency change invalidates the cache.
|
|
257
|
+
* Without a lockfile the root package.json stands in for it.
|
|
258
|
+
*/
|
|
259
|
+
const LOCKFILES = [
|
|
260
|
+
"bun.lock",
|
|
261
|
+
"bun.lockb",
|
|
262
|
+
"package-lock.json",
|
|
263
|
+
"npm-shrinkwrap.json",
|
|
264
|
+
"pnpm-lock.yaml",
|
|
265
|
+
"yarn.lock"
|
|
266
|
+
];
|
|
267
|
+
const sha1 = (value) => createHash("sha1").update(value).digest("hex");
|
|
268
|
+
/** A digest of the nearest lockfiles at or above `root`, else of its package.json. */
|
|
269
|
+
function dependencyFingerprint(root) {
|
|
270
|
+
for (let dir = path.resolve(root);; dir = path.dirname(dir)) {
|
|
271
|
+
const found = LOCKFILES.map((name) => path.join(dir, name)).filter((file) => fs.existsSync(file));
|
|
272
|
+
if (found.length > 0) {
|
|
273
|
+
const hash = createHash("sha1");
|
|
274
|
+
for (const file of found) hash.update(file).update(fs.readFileSync(file));
|
|
275
|
+
return hash.digest("hex");
|
|
276
|
+
}
|
|
277
|
+
if (path.dirname(dir) === dir) break;
|
|
278
|
+
}
|
|
279
|
+
try {
|
|
280
|
+
return sha1(fs.readFileSync(path.join(root, "package.json")));
|
|
281
|
+
} catch {
|
|
282
|
+
return "no-manifest";
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
/** The version of the package rooted at `packageDir`. */
|
|
286
|
+
function packageVersionAt(packageDir) {
|
|
287
|
+
try {
|
|
288
|
+
const manifest = JSON.parse(fs.readFileSync(path.join(packageDir, "package.json"), "utf8"));
|
|
289
|
+
return typeof manifest.version === "string" ? manifest.version : "unknown";
|
|
290
|
+
} catch {
|
|
291
|
+
return "unknown";
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
/** This plugin's contribution to a module's cache key in one project. */
|
|
295
|
+
function fsModuleCacheKey(ownPackageDir, projectRoot, pluginState) {
|
|
296
|
+
const state = JSON.stringify(pluginState, (_key, value) => typeof value === "function" || value instanceof RegExp ? String(value) : value);
|
|
297
|
+
return sha1(`vitest-native@${packageVersionAt(ownPackageDir)}\0${dependencyFingerprint(projectRoot)}\0${state}`);
|
|
298
|
+
}
|
|
299
|
+
/**
|
|
300
|
+
* Whether the plugin turns the cache on for this Vitest major when the user has not
|
|
301
|
+
* chosen: from Vitest 5, where `fsModuleCache` is a top-level option. Vitest 4 has it
|
|
302
|
+
* only as `experimental.fsModuleCache` (from 4.0.11), and it is left to the user there.
|
|
303
|
+
* `vitest-native doctor` reads this too, so its Vitest 4 advisory cannot drift from
|
|
304
|
+
* what the plugin does.
|
|
305
|
+
*/
|
|
306
|
+
function fsModuleCacheOnByDefault(vitestMajor) {
|
|
307
|
+
return vitestMajor >= 5;
|
|
308
|
+
}
|
|
309
|
+
/**
|
|
310
|
+
* Whether to turn the cache on: a Vitest the plugin defaults it on for, and the user
|
|
311
|
+
* has not chosen either way, in either spelling.
|
|
312
|
+
*/
|
|
313
|
+
function shouldDefaultFsModuleCache(vitestMajor, userTest) {
|
|
314
|
+
if (!fsModuleCacheOnByDefault(vitestMajor)) return false;
|
|
315
|
+
return userTest?.fsModuleCache === void 0 && userTest?.experimental?.fsModuleCache === void 0;
|
|
316
|
+
}
|
|
317
|
+
/**
|
|
318
|
+
* The native engine's dependencies that do NOT resolve from the project root.
|
|
319
|
+
*
|
|
320
|
+
* react-native itself is part of the check: the Babel toolchain alone chose
|
|
321
|
+
* native mode in a project with the preset installed but no react-native — an
|
|
322
|
+
* incomplete install, a babel-only workspace — which then failed later at RN
|
|
323
|
+
* resolution with nothing pointing at the cause. Resolution, not declaration:
|
|
324
|
+
* every check walks node_modules upward from the root — so a hoisted workspace
|
|
325
|
+
* install or Expo's transitive react-native counts, and a project does not need
|
|
326
|
+
* react-native in its own manifest.
|
|
327
|
+
*/
|
|
328
|
+
function missingNativeDeps(projectRoot) {
|
|
329
|
+
const req = createRequire(path.join(projectRoot, "package.json"));
|
|
330
|
+
const missing = [];
|
|
331
|
+
if (!reactNativeInstalledNear(projectRoot)) missing.push("react-native");
|
|
332
|
+
if (resolveTransformPreset(projectRoot) === null) missing.push("@react-native/babel-preset");
|
|
333
|
+
try {
|
|
334
|
+
req.resolve("@babel/core");
|
|
335
|
+
} catch {
|
|
336
|
+
missing.push("@babel/core");
|
|
337
|
+
}
|
|
338
|
+
return missing;
|
|
339
|
+
}
|
|
340
|
+
/** Does node_modules/react-native exist in projectRoot or any ancestor? */
|
|
341
|
+
function reactNativeInstalledNear(projectRoot) {
|
|
342
|
+
let dir = path.resolve(projectRoot);
|
|
343
|
+
for (;;) {
|
|
344
|
+
if (fs.existsSync(path.join(dir, "node_modules", "react-native", "package.json"))) return true;
|
|
345
|
+
const parent = path.dirname(dir);
|
|
346
|
+
if (parent === dir) return false;
|
|
347
|
+
dir = parent;
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
/** Resolve the concrete engine for a run. Pure; never throws. */
|
|
351
|
+
function detectEngine(requested, projectRoot, opts) {
|
|
352
|
+
const missing = missingNativeDeps(projectRoot);
|
|
353
|
+
const nativeAvailable = missing.length === 0;
|
|
354
|
+
if (requested === "native") return {
|
|
355
|
+
engine: "native",
|
|
356
|
+
nativeAvailable,
|
|
357
|
+
missing,
|
|
358
|
+
notice: null
|
|
359
|
+
};
|
|
360
|
+
if (requested === "mock") return {
|
|
361
|
+
engine: "mock",
|
|
362
|
+
nativeAvailable,
|
|
363
|
+
missing,
|
|
364
|
+
notice: null
|
|
365
|
+
};
|
|
366
|
+
const prefersNative = opts?.autoPrefersNative ?? true;
|
|
367
|
+
if (prefersNative && nativeAvailable) return {
|
|
368
|
+
engine: "native",
|
|
369
|
+
nativeAvailable,
|
|
370
|
+
missing,
|
|
371
|
+
notice: null
|
|
372
|
+
};
|
|
373
|
+
if (prefersNative) return {
|
|
374
|
+
engine: "mock",
|
|
375
|
+
nativeAvailable: false,
|
|
376
|
+
missing,
|
|
377
|
+
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.`
|
|
378
|
+
};
|
|
379
|
+
return {
|
|
380
|
+
engine: "mock",
|
|
381
|
+
nativeAvailable,
|
|
382
|
+
missing,
|
|
383
|
+
notice: null
|
|
384
|
+
};
|
|
385
|
+
}
|
|
386
|
+
// src/native/ecosystem.ts
|
|
387
|
+
/** A path inside a node_modules directory: an installed package's, not a workspace member's. */
|
|
388
|
+
const NODE_MODULES_DIR = /[\\/]node_modules[\\/]/;
|
|
389
|
+
/**
|
|
390
|
+
* Packages that must never be auto-inlined even though they depend on React
|
|
391
|
+
* Native. The test library and the renderers underneath it are infrastructure the
|
|
392
|
+
* engine itself wires up; pulling a second copy of them into the module graph has
|
|
393
|
+
* corrupted rendering before, in ways that surface as unrelated act() and
|
|
394
|
+
* host-component failures.
|
|
395
|
+
*
|
|
396
|
+
* This list is one clause of the ownership rule; the whole of it is written down in
|
|
397
|
+
* the header of native/apply.ts, which is the file to read before changing what ends
|
|
398
|
+
* up in either graph.
|
|
399
|
+
*/
|
|
400
|
+
const NEVER_INLINE = /* @__PURE__ */ new Set([
|
|
401
|
+
"@testing-library/react-native",
|
|
402
|
+
"react-test-renderer",
|
|
403
|
+
"test-renderer",
|
|
404
|
+
"react-native",
|
|
405
|
+
"react",
|
|
406
|
+
"react-is"
|
|
407
|
+
]);
|
|
408
|
+
/** Does this manifest offer a React Native build, by legacy field or export condition? */
|
|
409
|
+
function hasReactNativeBuild(manifest) {
|
|
410
|
+
if (typeof manifest["react-native"] === "string") return true;
|
|
411
|
+
const seen = /* @__PURE__ */ new Set();
|
|
412
|
+
const search = (node) => {
|
|
413
|
+
if (!node || typeof node !== "object" || seen.has(node)) return false;
|
|
414
|
+
seen.add(node);
|
|
415
|
+
for (const [key, value] of Object.entries(node)) {
|
|
416
|
+
if (key === "react-native") return true;
|
|
417
|
+
if (search(value)) return true;
|
|
418
|
+
}
|
|
419
|
+
return false;
|
|
420
|
+
};
|
|
421
|
+
return search(manifest.exports);
|
|
422
|
+
}
|
|
423
|
+
/**
|
|
424
|
+
* A package that ships ES modules and nothing React Native.
|
|
425
|
+
*
|
|
426
|
+
* The closure walk is a guess: a detected package's dependencies MIGHT be untranspiled
|
|
427
|
+
* React Native source, because the ecosystem publishes that way and the dependency's
|
|
428
|
+
* own manifest cannot say so. `"type": "module"` is the manifest saying the opposite —
|
|
429
|
+
* this is runnable ES modules — and with no React Native build anywhere in it, there is
|
|
430
|
+
* nothing for the preset to do. Compiling it anyway rewrites a package that publishes
|
|
431
|
+
* ESM into CommonJS and hands it to Node under that format, which is how a dependency
|
|
432
|
+
* reached this way (`zod`) failed to parse and took fourteen test files down with it.
|
|
433
|
+
*
|
|
434
|
+
* A genuine React Native library is unaffected: declaring `react-native` by field or
|
|
435
|
+
* export condition keeps it in the closure however it publishes.
|
|
436
|
+
*
|
|
437
|
+
* Only closure MEMBERS are judged this way. A package detected on its own manifest, or
|
|
438
|
+
* named in `transform: [...]`, was asked for explicitly and is still compiled.
|
|
439
|
+
*/
|
|
440
|
+
function publishesOnlyEsm(manifest) {
|
|
441
|
+
return manifest.type === "module" && !hasReactNativeBuild(manifest);
|
|
442
|
+
}
|
|
443
|
+
/** Manifest fields that make a package part of the React Native ecosystem. */
|
|
444
|
+
function dependsOnReactNative(manifest) {
|
|
445
|
+
for (const field of ["dependencies", "peerDependencies"]) {
|
|
446
|
+
const deps = manifest[field];
|
|
447
|
+
if (deps && typeof deps === "object" && "react-native" in deps) return true;
|
|
448
|
+
}
|
|
449
|
+
return false;
|
|
450
|
+
}
|
|
451
|
+
/**
|
|
452
|
+
* Every package manifest from the project up to the filesystem root.
|
|
453
|
+
*
|
|
454
|
+
* A workspace does not always declare its dependencies where the tests run: an app
|
|
455
|
+
* package may inherit React Native libraries from the repository root, and a Vitest
|
|
456
|
+
* `root` can point at a directory above or below the package that owns them. Reading
|
|
457
|
+
* only the project's own manifest silently found nothing in those layouts and sent
|
|
458
|
+
* the user back to maintaining `transform: [...]` by hand.
|
|
459
|
+
*
|
|
460
|
+
* Over-collecting is safe and under-collecting is not: a package that is listed but
|
|
461
|
+
* never imported costs nothing, because inlining only applies to files that are
|
|
462
|
+
* actually loaded.
|
|
463
|
+
*/
|
|
464
|
+
/**
|
|
465
|
+
* Directories of the workspace members a manifest declares, plus any listed in a
|
|
466
|
+
* sibling pnpm-workspace.yaml.
|
|
467
|
+
*
|
|
468
|
+
* Needed because `manifestsFrom` only walks UP. In a workspace the run root is
|
|
469
|
+
* frequently ABOVE the package under test — Nx invokes tasks from the workspace
|
|
470
|
+
* root, and Vitest's root defaults to the working directory — so the app's own
|
|
471
|
+
* dependencies are declared in a manifest that walking up never reaches. The
|
|
472
|
+
* package then misses auto-detection and stays in Vite's graph while Node loads it
|
|
473
|
+
* too, which is the dual-ownership failure reproducing from nothing but a different
|
|
474
|
+
* working directory.
|
|
475
|
+
*
|
|
476
|
+
* Only the two glob shapes workspace fields actually use are expanded (`dir/*` and a
|
|
477
|
+
* literal path). Over-collecting is safe here — an unimported package costs nothing —
|
|
478
|
+
* so a shape that is not understood is skipped rather than approximated.
|
|
479
|
+
*/
|
|
480
|
+
function workspaceMemberDirs(dir, manifest) {
|
|
481
|
+
const patterns = [];
|
|
482
|
+
const declared = manifest.workspaces;
|
|
483
|
+
if (Array.isArray(declared)) patterns.push(...declared.filter((p) => typeof p === "string"));
|
|
484
|
+
else if (declared && typeof declared === "object" && Array.isArray(declared.packages)) patterns.push(...declared.packages.filter((p) => typeof p === "string"));
|
|
485
|
+
try {
|
|
486
|
+
const yaml = fs.readFileSync(path.join(dir, "pnpm-workspace.yaml"), "utf8");
|
|
487
|
+
for (const line of yaml.split(/\r?\n/)) {
|
|
488
|
+
const entry = /^\s*-\s*["']?([^"'#]+?)["']?\s*$/.exec(line);
|
|
489
|
+
if (entry) patterns.push(entry[1]);
|
|
490
|
+
}
|
|
491
|
+
} catch {}
|
|
492
|
+
const dirs = [];
|
|
493
|
+
for (const pattern of patterns) if (pattern.endsWith("/*")) {
|
|
494
|
+
const parent = path.join(dir, pattern.slice(0, -2));
|
|
495
|
+
try {
|
|
496
|
+
for (const entry of fs.readdirSync(parent, { withFileTypes: true })) if (entry.isDirectory()) dirs.push(path.join(parent, entry.name));
|
|
497
|
+
} catch {}
|
|
498
|
+
} else if (!pattern.includes("*")) dirs.push(path.join(dir, pattern));
|
|
499
|
+
return dirs;
|
|
500
|
+
}
|
|
501
|
+
function manifestsFrom(projectRoot) {
|
|
502
|
+
const manifests = [];
|
|
503
|
+
let dir = path.resolve(projectRoot);
|
|
504
|
+
for (;;) {
|
|
505
|
+
try {
|
|
506
|
+
const raw = fs.readFileSync(path.join(dir, "package.json"), "utf8");
|
|
507
|
+
const manifest = JSON.parse(raw);
|
|
508
|
+
manifests.push({
|
|
509
|
+
dir,
|
|
510
|
+
manifest
|
|
511
|
+
});
|
|
512
|
+
for (const member of workspaceMemberDirs(dir, manifest)) try {
|
|
513
|
+
manifests.push({
|
|
514
|
+
dir: member,
|
|
515
|
+
manifest: JSON.parse(fs.readFileSync(path.join(member, "package.json"), "utf8"))
|
|
516
|
+
});
|
|
517
|
+
} catch {}
|
|
518
|
+
} catch {}
|
|
519
|
+
const parent = path.dirname(dir);
|
|
520
|
+
if (parent === dir) return manifests;
|
|
521
|
+
dir = parent;
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
/**
|
|
525
|
+
* The paths a `resolve.alias` config points into, whatever each entry's `find` is: a
|
|
526
|
+
* string, or a RegExp (an alias Vite applies to imports, which `jest.requireActual`
|
|
527
|
+
* cannot, so serializableAliases leaves it out of the compat layer's list). These seed
|
|
528
|
+
* the closure walk through the workspace members that contain them (ReachedPackages).
|
|
529
|
+
*
|
|
530
|
+
* A replacement may substitute part of the match (`/abs/packages/ui/src$1`): only the
|
|
531
|
+
* text before its first substitution is fixed (fixedReplacement), and that part is the
|
|
532
|
+
* path the alias reaches. A substitution that chooses the member (`/abs/packages/$1`)
|
|
533
|
+
* leaves a fixed part above every member, so it reaches none: walking every member such
|
|
534
|
+
* an alias could produce is the "seed from every member" #433 rejected. A `$` that is
|
|
535
|
+
* not a substitution (`/home/ci/$work`, a `c$` share) is part of the path. A replacement
|
|
536
|
+
* starting with `.` is taken from `root`, as the compat layer takes it; anything else
|
|
537
|
+
* that is not absolute (a package name) reaches no member.
|
|
538
|
+
*
|
|
539
|
+
* Plugins that resolve through `resolveId` (vite-tsconfig-paths, nxViteTsPaths) add no
|
|
540
|
+
* alias entry, so they are out of reach here by construction.
|
|
541
|
+
*/
|
|
542
|
+
function aliasReachedPaths(alias, root) {
|
|
543
|
+
const list = Array.isArray(alias) ? alias : alias && typeof alias === "object" ? Object.entries(alias).map(([find, replacement]) => ({
|
|
544
|
+
find,
|
|
545
|
+
replacement
|
|
546
|
+
})) : [];
|
|
547
|
+
const reached = [];
|
|
548
|
+
for (const item of list) {
|
|
549
|
+
const entry = item;
|
|
550
|
+
const replacement = entry?.replacement;
|
|
551
|
+
if (typeof replacement !== "string") continue;
|
|
552
|
+
const fixed = fixedReplacement(replacement, entry?.find instanceof RegExp);
|
|
553
|
+
const target = fixed.startsWith(".") ? path.resolve(root, fixed) : fixed;
|
|
554
|
+
if (target && path.isAbsolute(target)) reached.push(target);
|
|
555
|
+
}
|
|
556
|
+
return reached;
|
|
557
|
+
}
|
|
558
|
+
/**
|
|
559
|
+
* The text of an alias replacement up to its first substitution, with `$$` read as `$`.
|
|
560
|
+
* Vite applies an alias with `String.prototype.replace`, which substitutes `$&`, `` $` ``
|
|
561
|
+
* and `$'` for any pattern, and `$n` and `$<name>` for a RegExp; every other `$` is
|
|
562
|
+
* literal (with a string pattern, `$1` is too).
|
|
563
|
+
*/
|
|
564
|
+
function fixedReplacement(replacement, regExp) {
|
|
565
|
+
let fixed = "";
|
|
566
|
+
for (let i = 0; i < replacement.length; i++) {
|
|
567
|
+
const char = replacement[i];
|
|
568
|
+
if (char !== "$") {
|
|
569
|
+
fixed += char;
|
|
570
|
+
continue;
|
|
571
|
+
}
|
|
572
|
+
const next = replacement[i + 1] ?? "";
|
|
573
|
+
if (next === "$") {
|
|
574
|
+
fixed += "$";
|
|
575
|
+
i++;
|
|
576
|
+
} else if (next === "&" || next === "`" || next === "'") break;
|
|
577
|
+
else if (regExp && (/[0-9]/.test(next) || next === "<")) break;
|
|
578
|
+
else fixed += "$";
|
|
579
|
+
}
|
|
580
|
+
return fixed;
|
|
581
|
+
}
|
|
582
|
+
/**
|
|
583
|
+
* Packages in the project that declare React Native in their own manifest.
|
|
584
|
+
*
|
|
585
|
+
* These are the ones published the way the React Native ecosystem publishes:
|
|
586
|
+
* untranspiled JSX, Flow, or TypeScript, on the assumption that Metro will compile
|
|
587
|
+
* them. Node cannot run that source, which is why they previously had to be listed
|
|
588
|
+
* by hand in `transform: [...]` — a list every project had to discover the hard way,
|
|
589
|
+
* one `SyntaxError: Unexpected token '<'` at a time.
|
|
590
|
+
*
|
|
591
|
+
* A package's own manifest is the authority here rather than a heuristic on its
|
|
592
|
+
* name: `react-native-*` misses `@gorhom/bottom-sheet` and would wrongly claim
|
|
593
|
+
* `react-native` itself, while the manifest states the relationship exactly.
|
|
594
|
+
*
|
|
595
|
+
* Declared dependencies are read from the project and every manifest above it, so a
|
|
596
|
+
* workspace that declares its React Native libraries at the repository root is covered
|
|
597
|
+
* too. Resolving each name is cheap and package-manager-agnostic, where walking the
|
|
598
|
+
* installed tree depends on the store layout. Transitive dependencies that nothing
|
|
599
|
+
* declares stay available through `transform: [...]`.
|
|
600
|
+
*
|
|
601
|
+
* Excluded: packages a preset already shadows (their real source never loads), the
|
|
602
|
+
* test infrastructure in NEVER_INLINE, and anything the consumer listed explicitly
|
|
603
|
+
* in `transform` — that option keeps its existing meaning and takes precedence.
|
|
604
|
+
*
|
|
605
|
+
* `dirOf` finds a dependency's directory from a directory: `dependencyDirOf`, or a
|
|
606
|
+
* memoized copy of it (memoizePackageDirOf). Not `packageDirOf`, whose answer for a
|
|
607
|
+
* workspace member differs (see dependencyDirOf).
|
|
608
|
+
*
|
|
609
|
+
* `reachedPaths` adds the workspace members an alias reaches; see ReachedPackages.
|
|
610
|
+
*/
|
|
611
|
+
function detectEcosystemPackages(projectRoot, explicit = [], testRoots = [], neverTransform = [], activePresets, dirOf = dependencyDirOf, { reachedPaths = [], onReachedUndeclared } = {}) {
|
|
612
|
+
const roots = (Array.isArray(projectRoot) ? projectRoot : [projectRoot]).filter(Boolean);
|
|
613
|
+
const shadowed = Object.entries(AUTO_DETECT_PRESETS).filter(([, presetName]) => activePresets === void 0 || activePresets.includes(presetName)).map(([pkg]) => pkg);
|
|
614
|
+
const skip = /* @__PURE__ */ new Set([
|
|
615
|
+
...NEVER_INLINE,
|
|
616
|
+
...shadowed,
|
|
617
|
+
...explicit,
|
|
618
|
+
...neverTransform
|
|
619
|
+
]);
|
|
620
|
+
const candidates = /* @__PURE__ */ new Set();
|
|
621
|
+
const found = roots.flatMap((root) => manifestsFrom(root));
|
|
622
|
+
const declaringDirs = [...new Set(found.map((entry) => entry.dir))];
|
|
623
|
+
for (const { manifest } of found) for (const field of [
|
|
624
|
+
"dependencies",
|
|
625
|
+
"devDependencies",
|
|
626
|
+
"optionalDependencies"
|
|
627
|
+
]) {
|
|
628
|
+
const deps = manifest[field];
|
|
629
|
+
if (deps && typeof deps === "object") for (const name of Object.keys(deps)) candidates.add(name);
|
|
630
|
+
}
|
|
631
|
+
if (candidates.size === 0) return [];
|
|
632
|
+
const installedFrom = (fromDir, name) => {
|
|
633
|
+
const dir = dirOf(name, fromDir);
|
|
634
|
+
if (!dir) return null;
|
|
635
|
+
try {
|
|
636
|
+
return {
|
|
637
|
+
manifest: JSON.parse(fs.readFileSync(path.join(dir, "package.json"), "utf8")),
|
|
638
|
+
dir
|
|
639
|
+
};
|
|
640
|
+
} catch {
|
|
641
|
+
return null;
|
|
642
|
+
}
|
|
643
|
+
};
|
|
644
|
+
/** Resolve a package's manifest from whichever root can see it. */
|
|
645
|
+
const installedOf = (name) => {
|
|
646
|
+
for (const dir of declaringDirs) {
|
|
647
|
+
const installed = installedFrom(dir, name);
|
|
648
|
+
if (installed) return installed;
|
|
649
|
+
}
|
|
650
|
+
return null;
|
|
651
|
+
};
|
|
652
|
+
const manifestOf = (name) => installedOf(name)?.manifest ?? null;
|
|
653
|
+
const dependencyOf = (parent, name) => installedFrom(parent.dir, name);
|
|
654
|
+
/**
|
|
655
|
+
* The packages the run itself lives in — the project, in other words.
|
|
656
|
+
*
|
|
657
|
+
* In a workspace, the package under test is usually declared as a dependency by a
|
|
658
|
+
* sibling or by the repository root, so it appears in the candidate set like any
|
|
659
|
+
* third-party library — and it declares React Native, because it is React Native
|
|
660
|
+
* code. Detecting it would claim the project's own source: its directory becomes a
|
|
661
|
+
* `server.deps.external` pattern, so Vitest hands every file under it to Node,
|
|
662
|
+
* where the loader compiles it to CommonJS. A test file's own
|
|
663
|
+
* `import { it } from 'vitest'` becomes `require('vitest')`, which throws
|
|
664
|
+
* "Vitest cannot be imported in a CommonJS module using require()" — a failure that
|
|
665
|
+
* appears in one workspace package and not another for no visible reason.
|
|
666
|
+
*
|
|
667
|
+
* A package cannot be its own dependency, so a manifest whose directory contains a
|
|
668
|
+
* run root belongs to the project. Read straight off the manifests already walked,
|
|
669
|
+
* which is both cheaper than resolving each candidate and independent of how a
|
|
670
|
+
* package manager happens to lay out its store — under pnpm every workspace member
|
|
671
|
+
* is additionally linked into a hidden directory on NODE_PATH, so a package can
|
|
672
|
+
* resolve its own name from its own directory, but nothing here depends on that.
|
|
673
|
+
*
|
|
674
|
+
* Workspace libraries the project merely depends on sit beside a run root rather
|
|
675
|
+
* than above it and are unaffected — detecting those is the point of the
|
|
676
|
+
* workspace-member walk above.
|
|
677
|
+
*/
|
|
678
|
+
const ownerRoots = [...roots, ...testRoots];
|
|
679
|
+
const runOwners = new Set(found.filter(({ dir }) => ownerRoots.some((root) => containsPath(dir, root))).map(({ manifest }) => manifest.name).filter((name) => typeof name === "string"));
|
|
680
|
+
const ownsTheRun = (name) => runOwners.has(name);
|
|
681
|
+
const detected = [];
|
|
682
|
+
for (const name of candidates) {
|
|
683
|
+
if (skip.has(name) || name.startsWith("@react-native/")) continue;
|
|
684
|
+
const pkg = manifestOf(name);
|
|
685
|
+
if (pkg && dependsOnReactNative(pkg) && !ownsTheRun(name)) detected.push(name);
|
|
686
|
+
}
|
|
687
|
+
const rnOwned = new Set(Object.keys(manifestOf("react-native")?.dependencies ?? {}));
|
|
688
|
+
/** Every package reachable from `starts` through runtime dependencies. */
|
|
689
|
+
const closureOf = (starts) => {
|
|
690
|
+
const seen = /* @__PURE__ */ new Set();
|
|
691
|
+
const pending = [...starts];
|
|
692
|
+
while (pending.length > 0) {
|
|
693
|
+
const [name, installed] = pending.pop();
|
|
694
|
+
if (seen.has(name)) continue;
|
|
695
|
+
seen.add(name);
|
|
696
|
+
const deps = installed?.manifest.dependencies;
|
|
697
|
+
if (!installed || !deps || typeof deps !== "object") continue;
|
|
698
|
+
for (const dep of Object.keys(deps)) if (!seen.has(dep)) pending.push([dep, dependencyOf(installed, dep)]);
|
|
699
|
+
}
|
|
700
|
+
return seen;
|
|
701
|
+
};
|
|
702
|
+
const reactNativeInstalled = installedOf("react-native");
|
|
703
|
+
const expoInstalled = installedOf("expo");
|
|
704
|
+
const seed = (name) => [name, installedOf(name) ?? (reactNativeInstalled && dependencyOf(reactNativeInstalled, name)) ?? (expoInstalled && dependencyOf(expoInstalled, name))];
|
|
705
|
+
const toolchain = closureOf([
|
|
706
|
+
seed("@babel/core"),
|
|
707
|
+
seed("@react-native/babel-preset"),
|
|
708
|
+
seed("babel-preset-expo"),
|
|
709
|
+
seed("@babel/runtime"),
|
|
710
|
+
seed("metro"),
|
|
711
|
+
seed("@expo/metro")
|
|
712
|
+
]);
|
|
713
|
+
const projectDeclared = /* @__PURE__ */ new Set();
|
|
714
|
+
for (const { dir, manifest } of found) {
|
|
715
|
+
if (!ownerRoots.some((root) => containsPath(dir, root))) continue;
|
|
716
|
+
for (const field of [
|
|
717
|
+
"dependencies",
|
|
718
|
+
"devDependencies",
|
|
719
|
+
"optionalDependencies"
|
|
720
|
+
]) {
|
|
721
|
+
const deps = manifest[field];
|
|
722
|
+
if (deps && typeof deps === "object") for (const name of Object.keys(deps)) projectDeclared.add(name);
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
const detectedSet = new Set(detected);
|
|
726
|
+
const inClosure = new Set(detected);
|
|
727
|
+
const walked = /* @__PURE__ */ new Set();
|
|
728
|
+
const queue = [];
|
|
729
|
+
const reach = (name, installed) => {
|
|
730
|
+
inClosure.add(name);
|
|
731
|
+
if (walked.has(name)) return;
|
|
732
|
+
walked.add(name);
|
|
733
|
+
queue.push(installed);
|
|
734
|
+
};
|
|
735
|
+
for (const name of detected) {
|
|
736
|
+
if (!projectDeclared.has(name)) continue;
|
|
737
|
+
const installed = installedOf(name);
|
|
738
|
+
if (installed) reach(name, installed);
|
|
739
|
+
}
|
|
740
|
+
const neverSeeded = /* @__PURE__ */ new Set([...shadowed, ...neverTransform]);
|
|
741
|
+
for (const name of explicit) {
|
|
742
|
+
if (neverSeeded.has(name)) continue;
|
|
743
|
+
const installed = installedOf(name);
|
|
744
|
+
if (!installed || walked.has(name)) continue;
|
|
745
|
+
walked.add(name);
|
|
746
|
+
queue.push(installed);
|
|
747
|
+
}
|
|
748
|
+
/** A dependency or peer the walk may not take, whatever its manifest says. */
|
|
749
|
+
const excluded = (dep) => skip.has(dep) || dep.startsWith("@react-native/") || rnOwned.has(dep) || toolchain.has(dep) || ownsTheRun(dep);
|
|
750
|
+
/**
|
|
751
|
+
* Walk the queue. With `installedOnly`, only installed packages (a real path inside a
|
|
752
|
+
* node_modules directory) are added: see "Workspace members the run reaches" below.
|
|
753
|
+
*/
|
|
754
|
+
const walk = (installedOnly) => {
|
|
755
|
+
const admits = (installed) => !installedOnly || NODE_MODULES_DIR.test(installed.dir);
|
|
756
|
+
while (queue.length > 0) {
|
|
757
|
+
const pkg = queue.pop();
|
|
758
|
+
const deps = pkg.manifest.dependencies;
|
|
759
|
+
for (const dep of deps && typeof deps === "object" ? Object.keys(deps) : []) {
|
|
760
|
+
if (walked.has(dep) || excluded(dep)) continue;
|
|
761
|
+
const installed = dependencyOf(pkg, dep);
|
|
762
|
+
if (!installed) continue;
|
|
763
|
+
if (!inClosure.has(dep) && publishesOnlyEsm(installed.manifest)) continue;
|
|
764
|
+
if (admits(installed)) reach(dep, installed);
|
|
765
|
+
}
|
|
766
|
+
const peers = pkg.manifest.peerDependencies;
|
|
767
|
+
for (const peer of peers && typeof peers === "object" ? Object.keys(peers) : []) {
|
|
768
|
+
if (walked.has(peer) || excluded(peer) || !detectedSet.has(peer)) continue;
|
|
769
|
+
const installed = dependencyOf(pkg, peer);
|
|
770
|
+
if (installed && admits(installed)) reach(peer, installed);
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
};
|
|
774
|
+
walk(false);
|
|
775
|
+
const members = found.filter(({ dir, manifest }) => typeof manifest.name === "string" && !ownerRoots.some((root) => containsPath(dir, root)));
|
|
776
|
+
const memberByName = new Map(members.map((m) => [m.manifest.name, m]));
|
|
777
|
+
const reachedMembers = /* @__PURE__ */ new Map();
|
|
778
|
+
const reachMember = (member) => {
|
|
779
|
+
if (reachedMembers.has(member.dir)) return;
|
|
780
|
+
reachedMembers.set(member.dir, member);
|
|
781
|
+
const deps = member.manifest.dependencies;
|
|
782
|
+
for (const dep of deps && typeof deps === "object" ? Object.keys(deps) : []) {
|
|
783
|
+
const other = memberByName.get(dep);
|
|
784
|
+
if (other) reachMember(other);
|
|
785
|
+
}
|
|
786
|
+
};
|
|
787
|
+
for (const name of projectDeclared) {
|
|
788
|
+
const member = memberByName.get(name);
|
|
789
|
+
if (member) reachMember(member);
|
|
790
|
+
}
|
|
791
|
+
for (const target of reachedPaths) {
|
|
792
|
+
const member = members.filter(({ dir }) => containsPath(dir, target)).sort((a, b) => b.dir.length - a.dir.length)[0];
|
|
793
|
+
if (!member) continue;
|
|
794
|
+
if (!reachedMembers.has(member.dir)) onReachedUndeclared?.(member.manifest.name, member.dir);
|
|
795
|
+
reachMember(member);
|
|
796
|
+
}
|
|
797
|
+
for (const member of reachedMembers.values()) {
|
|
798
|
+
const deps = member.manifest.dependencies;
|
|
799
|
+
for (const dep of deps && typeof deps === "object" ? Object.keys(deps) : []) {
|
|
800
|
+
if (walked.has(dep) || excluded(dep) || !detectedSet.has(dep)) continue;
|
|
801
|
+
const installed = installedFrom(member.dir, dep);
|
|
802
|
+
if (installed) reach(dep, installed);
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
walk(true);
|
|
806
|
+
return [...inClosure].sort();
|
|
807
|
+
}
|
|
808
|
+
// src/host.ts
|
|
809
|
+
/** The running Vite's version, and where it was read, for messages that name it. */
|
|
810
|
+
async function runningVite(context) {
|
|
811
|
+
const fromHost = context?.meta?.viteVersion;
|
|
812
|
+
if (typeof fromHost === "string") return {
|
|
813
|
+
version: fromHost,
|
|
814
|
+
source: "the running Vite"
|
|
815
|
+
};
|
|
816
|
+
try {
|
|
817
|
+
const vite = await import("vite");
|
|
818
|
+
if (typeof vite.version !== "string") return null;
|
|
819
|
+
let at = "";
|
|
820
|
+
try {
|
|
821
|
+
at = ` at ${path.dirname(createRequire(import.meta.url).resolve("vite/package.json"))}`;
|
|
822
|
+
} catch {}
|
|
823
|
+
return {
|
|
824
|
+
version: vite.version,
|
|
825
|
+
source: `the vite module${at}`
|
|
826
|
+
};
|
|
827
|
+
} catch {
|
|
828
|
+
return null;
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
/**
|
|
832
|
+
* The version of Vite installed where `root` resolves it, read from the module, for
|
|
833
|
+
* diagnostics that run without a Vite process (`doctor`, `migrate`). Falls back to the
|
|
834
|
+
* manifest, preferring the Vite version a wrapper records it bundles.
|
|
835
|
+
*/
|
|
836
|
+
function installedViteVersion(root) {
|
|
837
|
+
const req = createRequire(path.join(root, "package.json"));
|
|
838
|
+
try {
|
|
839
|
+
const version = req("vite").version;
|
|
840
|
+
if (typeof version === "string") return version;
|
|
841
|
+
} catch {}
|
|
842
|
+
try {
|
|
843
|
+
const manifest = req("vite/package.json");
|
|
844
|
+
return manifest.bundledVersions?.vite ?? manifest.version ?? null;
|
|
845
|
+
} catch {
|
|
846
|
+
return null;
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
/** Whether the project at `root` runs its tests through Vite+. */
|
|
850
|
+
function usesVitePlus(root) {
|
|
851
|
+
try {
|
|
852
|
+
createRequire(path.join(root, "package.json")).resolve("vite-plus/package.json");
|
|
853
|
+
return true;
|
|
854
|
+
} catch {
|
|
855
|
+
return false;
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
/** The `vitest` package this package's own files resolve by name, or null. */
|
|
859
|
+
function ownVitestPackage() {
|
|
860
|
+
try {
|
|
861
|
+
const req = createRequire(import.meta.url);
|
|
862
|
+
const manifest = req.resolve("vitest/package.json");
|
|
863
|
+
const { version } = req(manifest);
|
|
864
|
+
return {
|
|
865
|
+
root: realPath(path.dirname(manifest)),
|
|
866
|
+
version
|
|
867
|
+
};
|
|
868
|
+
} catch {
|
|
869
|
+
return null;
|
|
870
|
+
}
|
|
871
|
+
}
|
|
872
|
+
/**
|
|
873
|
+
* A path's canonical spelling. `realpathSync.native` asks the OS, which returns the long
|
|
874
|
+
* on-disk spelling (no 8.3 short names) and the on-disk case on Windows and macOS. It is
|
|
875
|
+
* what the error messages show.
|
|
876
|
+
*/
|
|
877
|
+
function realPath(file) {
|
|
878
|
+
return fs.realpathSync.native(file);
|
|
879
|
+
}
|
|
880
|
+
/** Whether two canonical paths are one directory: without case on Windows, as NTFS looks up. */
|
|
881
|
+
function samePath(a, b) {
|
|
882
|
+
return process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b;
|
|
883
|
+
}
|
|
884
|
+
/** The directory of the package that contains `file`, by its nearest package.json. */
|
|
885
|
+
function packageRootOf(file) {
|
|
886
|
+
let dir = realPath(file);
|
|
887
|
+
const start = dir;
|
|
888
|
+
for (;;) {
|
|
889
|
+
if (fs.existsSync(path.join(dir, "package.json"))) return dir;
|
|
890
|
+
const parent = path.dirname(dir);
|
|
891
|
+
if (parent === dir) return start;
|
|
892
|
+
dir = parent;
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
function twinError(running, other, via, alternative = "") {
|
|
896
|
+
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);
|
|
897
|
+
}
|
|
898
|
+
/**
|
|
899
|
+
* Fail fast when what the host actually loads for vitest-native's own `import 'vitest'`
|
|
900
|
+
* is not the running Vitest.
|
|
901
|
+
*
|
|
902
|
+
* A second physical copy is not a problem by itself: Vitest's own resolver maps every
|
|
903
|
+
* `vitest` import in a module it runs (setup files included) to the running copy, which
|
|
904
|
+
* is how peer-variant installs (two copies of the same version) work. So the question is
|
|
905
|
+
* put to the host, through the project's Vite resolver, for the file that imports it.
|
|
906
|
+
*/
|
|
907
|
+
async function assertHostResolvesRunningVitest(running, resolveId, importer) {
|
|
908
|
+
const resolved = await resolveId("vitest", importer);
|
|
909
|
+
const id = typeof resolved === "string" ? resolved : resolved?.id;
|
|
910
|
+
if (!id || !path.isAbsolute(id) || !fs.existsSync(id)) return;
|
|
911
|
+
const runningRoot = packageRootOf(running.distPath);
|
|
912
|
+
const loadedRoot = packageRootOf(id);
|
|
913
|
+
if (samePath(loadedRoot, runningRoot)) return;
|
|
914
|
+
throw twinError({
|
|
915
|
+
root: runningRoot,
|
|
916
|
+
version: running.version
|
|
917
|
+
}, loadedRoot, "the Vite resolver, for vitest-native's setup file,");
|
|
918
|
+
}
|
|
919
|
+
/**
|
|
920
|
+
* Fail fast when the hot runtime's worker, which Node loads directly and so outside
|
|
921
|
+
* Vitest's resolver, would import a different physical copy of Vitest from the running
|
|
922
|
+
* one.
|
|
923
|
+
*/
|
|
924
|
+
function assertHotWorkerLoadsRunningVitest(running, workerEntry) {
|
|
925
|
+
let manifest;
|
|
926
|
+
try {
|
|
927
|
+
manifest = createRequire(workerEntry).resolve("vitest/package.json");
|
|
928
|
+
} catch {
|
|
929
|
+
return;
|
|
930
|
+
}
|
|
931
|
+
const runningRoot = packageRootOf(running.distPath);
|
|
932
|
+
const loadedRoot = realPath(path.dirname(manifest));
|
|
933
|
+
if (samePath(loadedRoot, runningRoot)) return;
|
|
934
|
+
throw twinError({
|
|
935
|
+
root: runningRoot,
|
|
936
|
+
version: running.version
|
|
937
|
+
}, 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.");
|
|
938
|
+
}
|
|
939
|
+
export { validateOptions as _, runningVite as a, detectEcosystemPackages as c, fsModuleCacheOnByDefault as d, shouldDefaultFsModuleCache as f, unsupportedExpoSdkMessage as g, installedExpoVersion as h, ownVitestPackage as i, detectEngine as l, SUPPORTED_EXPO_SDKS as m, assertHotWorkerLoadsRunningVitest as n, usesVitePlus as o, PEER_REQUIREMENTS as p, installedViteVersion as r, aliasReachedPaths as s, assertHostResolvesRunningVitest as t, fsModuleCacheKey as u, validatePeerDependency as v, warnUnknownOptions as y };
|