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.
Files changed (89) hide show
  1. package/README.md +11 -10
  2. package/dist/cli.d.mts +9 -1
  3. package/dist/cli.mjs +2609 -361
  4. package/dist/context.d.mts +19 -0
  5. package/dist/context.mjs +47 -1
  6. package/dist/docs-url.d.mts +4 -0
  7. package/dist/docs-url.mjs +9 -0
  8. package/dist/errors.d.mts +21 -1
  9. package/dist/hang-watch-setup.mjs +55 -0
  10. package/dist/hang-watch.d.mts +56 -0
  11. package/dist/hang-watch.mjs +343 -0
  12. package/dist/helpers.cjs +24 -53
  13. package/dist/helpers.mjs +22 -1
  14. package/dist/host-D0r3P_T1.mjs +1985 -0
  15. package/dist/{index-aNBCTfA5.d.mts → index-JOR602XU.d.mts} +105 -2
  16. package/dist/index.d.mts +2 -1
  17. package/dist/index.mjs +723 -149
  18. package/dist/jest-compat/aliases.d.mts +1 -0
  19. package/dist/jest-compat/aliases.mjs +11 -0
  20. package/dist/jest-compat/interop.mjs +1 -1
  21. package/dist/jest-compat/jest-object.mjs +23 -5
  22. package/dist/jest-compat/node-registry.mjs +836 -68
  23. package/dist/jest-compat/setup.mjs +205 -12
  24. package/dist/jest-compat.cjs +383 -47
  25. package/dist/jest-compat.d.cts +19 -2
  26. package/dist/jest-compat.d.mts +19 -2
  27. package/dist/jest-compat.mjs +232 -47
  28. package/dist/matchers.d.cts +0 -1
  29. package/dist/matchers.d.mts +0 -1
  30. package/dist/native/assets.mjs +3 -1
  31. package/dist/native/babel-caller.d.mts +13 -0
  32. package/dist/native/babel-caller.mjs +24 -0
  33. package/dist/native/babel-toolchain.mjs +27 -3
  34. package/dist/native/boundary.mjs +45 -8
  35. package/dist/native/bounded-process.mjs +63 -5
  36. package/dist/native/bridge-client.mjs +133 -0
  37. package/dist/native/bridge-server.mjs +215 -0
  38. package/dist/native/bridge-thread.mjs +79 -0
  39. package/dist/native/bridge.mjs +512 -0
  40. package/dist/native/compile-error.mjs +120 -0
  41. package/dist/native/explain.mjs +3 -2
  42. package/dist/native/expo-module-mocks.mjs +2 -0
  43. package/dist/native/export-condition-recovery.mjs +20 -99
  44. package/dist/native/hooks.mjs +256 -133
  45. package/dist/native/jest-resolvers.mjs +94 -0
  46. package/dist/native/library-jest.mjs +352 -0
  47. package/dist/native/loader.mjs +167 -73
  48. package/dist/native/match.mjs +67 -7
  49. package/dist/native/module-reset.mjs +44 -49
  50. package/dist/native/ownership-ledger.d.mts +87 -0
  51. package/dist/native/ownership-ledger.mjs +524 -0
  52. package/dist/native/ownership.d.mts +20 -0
  53. package/dist/native/ownership.mjs +114 -0
  54. package/dist/native/registry-compiler.mjs +39 -5
  55. package/dist/native/registry-process.mjs +327 -28
  56. package/dist/native/registry.mjs +752 -200
  57. package/dist/native/resident-health.mjs +1 -0
  58. package/dist/native/resolve.d.mts +7 -0
  59. package/dist/native/resolve.mjs +119 -4
  60. package/dist/native/rntl-hooks.mjs +9 -5
  61. package/dist/native/rntl-text-host.mjs +5 -15
  62. package/dist/native/root-spelling.d.mts +6 -0
  63. package/dist/native/root-spelling.mjs +77 -0
  64. package/dist/native/runner.mjs +2 -19
  65. package/dist/native/setup.mjs +119 -38
  66. package/dist/native/shared-resolver.d.mts +141 -0
  67. package/dist/native/shared-resolver.mjs +719 -0
  68. package/dist/native/test-runner.mjs +26 -0
  69. package/dist/native/transform.mjs +18 -22
  70. package/dist/native/worker.mjs +9 -4
  71. package/dist/node-dispatch.mjs +293 -0
  72. package/dist/{preset-map-CogjYmSw.mjs → preset-map-DdAexIwz.mjs} +113 -2
  73. package/dist/{presets-CXDyg51l.mjs → presets-_EaSw29m.mjs} +710 -130
  74. package/dist/presets.d.mts +1 -1
  75. package/dist/presets.mjs +1 -1
  76. package/dist/rntl-matchers.d.ts +11 -15
  77. package/dist/rntl-support.mjs +28 -13
  78. package/dist/root-mocks-BNXeosbR.mjs +155 -0
  79. package/dist/serializer.cjs +7 -5
  80. package/dist/serializer.d.cts +7 -5
  81. package/dist/serializer.d.mts +7 -5
  82. package/dist/serializer.mjs +7 -5
  83. package/dist/setup.mjs +26 -27
  84. package/docs/migrating-from-jest.md +9 -232
  85. package/docs/migrating-from-vitest-react-native.md +4 -4
  86. package/docs/release-readiness.md +9 -11
  87. package/docs/versioning.md +38 -9
  88. package/package.json +59 -33
  89. package/dist/host-BAAAlSkO.mjs +0 -1028
@@ -1,1028 +0,0 @@
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
- const SPECIFIER = /(?:\brequire\s*\(\s*|\bimport\s*\(\s*|\bfrom\s*|\bimport\s*)["']([^"'\n]+)["']/g;
444
- const COMMENT = /\/\*[\s\S]*?\*\/|(^|[^:"'`\\])\/\/[^\n]*/g;
445
- const TYPE_ONLY = /\b(?:import|export)\s+type\b[^;]*?\bfrom\s*["'][^"']+["']/g;
446
- const RUNTIME_EXTENSIONS = [
447
- ".native.js",
448
- ".ios.js",
449
- ".js",
450
- ".mjs",
451
- ".cjs",
452
- ".jsx",
453
- ".native.ts",
454
- ".ios.ts",
455
- ".ts",
456
- ".native.tsx",
457
- ".ios.tsx",
458
- ".tsx"
459
- ];
460
- const MAX_RUNTIME_FILES = 5e3;
461
- const PACKAGE_SPECIFIER = /^(?:@[\w.-]+\/)?[\w][\w.-]*(?:\/|$)/;
462
- const runtimeMemo = /* @__PURE__ */ new Map();
463
- /** The file a relative specifier names from `fromDir`, as Metro and Node find it, or null. */
464
- function runtimeFile(base) {
465
- const isFile = (file) => fs.statSync(file, { throwIfNoEntry: false })?.isFile() === true;
466
- if (isFile(base)) return base;
467
- for (const ext of RUNTIME_EXTENSIONS) if (isFile(base + ext)) return base + ext;
468
- for (const ext of RUNTIME_EXTENSIONS) {
469
- const index = path.join(base, `index${ext}`);
470
- if (isFile(index)) return index;
471
- }
472
- return null;
473
- }
474
- /** Every string target of a manifest's `exports` root (all conditions), or none. */
475
- function exportTargets(exportsField) {
476
- if (typeof exportsField === "string") return [exportsField];
477
- if (!exportsField || typeof exportsField !== "object") return [];
478
- const node = exportsField;
479
- const root = "." in node ? node["."] : Object.keys(node).every((k) => !k.startsWith(".")) ? node : null;
480
- const out = [];
481
- const collect = (value) => {
482
- if (typeof value === "string") out.push(value);
483
- else if (value && typeof value === "object") Object.values(value).forEach(collect);
484
- };
485
- collect(root);
486
- return out;
487
- }
488
- /**
489
- * The packages a package loads when it runs, by name: the bare specifiers in the files
490
- * reachable from its runtime entries (its `react-native` field, `main` and `exports`
491
- * root) through relative requires and imports, with comments and type-only imports left
492
- * out. Its config plugin, scripts and type declarations are not reached, so a package
493
- * that names another only there (expo-constants' `expo`, from `expo/config`) does not
494
- * load it. Read once per directory and process. For the peer edge only (see the closure
495
- * walk).
496
- */
497
- function runtimeImports(dir, manifest) {
498
- let names = runtimeMemo.get(dir);
499
- if (names) return names;
500
- names = /* @__PURE__ */ new Set();
501
- const entries = [
502
- typeof manifest["react-native"] === "string" ? manifest["react-native"] : null,
503
- typeof manifest.main === "string" ? manifest.main : null,
504
- ...exportTargets(manifest.exports)
505
- ].filter((entry) => entry !== null);
506
- if (entries.length === 0) entries.push("index");
507
- const pending = entries.map((entry) => runtimeFile(path.resolve(dir, entry))).filter((file) => file !== null && containsPath(dir, file));
508
- const seen = /* @__PURE__ */ new Set();
509
- while (pending.length > 0 && seen.size < MAX_RUNTIME_FILES) {
510
- const file = pending.pop();
511
- if (seen.has(file) || file.endsWith(".json")) continue;
512
- seen.add(file);
513
- const code = fs.readFileSync(file, "utf8").replace(COMMENT, "$1").replace(TYPE_ONLY, "");
514
- for (const match of code.matchAll(SPECIFIER)) {
515
- const specifier = match[1];
516
- if (specifier.startsWith(".")) {
517
- const target = runtimeFile(path.resolve(path.dirname(file), specifier));
518
- if (target !== null && containsPath(dir, target) && !NODE_MODULES_DIR.test(path.relative(dir, target))) pending.push(target);
519
- } else if (PACKAGE_SPECIFIER.test(specifier)) {
520
- const parts = specifier.split("/");
521
- names.add(specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0]);
522
- }
523
- }
524
- }
525
- runtimeMemo.set(dir, names);
526
- return names;
527
- }
528
- /** Manifest fields that make a package part of the React Native ecosystem. */
529
- function dependsOnReactNative(manifest) {
530
- for (const field of ["dependencies", "peerDependencies"]) {
531
- const deps = manifest[field];
532
- if (deps && typeof deps === "object" && "react-native" in deps) return true;
533
- }
534
- return false;
535
- }
536
- /**
537
- * Every package manifest from the project up to the filesystem root.
538
- *
539
- * A workspace does not always declare its dependencies where the tests run: an app
540
- * package may inherit React Native libraries from the repository root, and a Vitest
541
- * `root` can point at a directory above or below the package that owns them. Reading
542
- * only the project's own manifest silently found nothing in those layouts and sent
543
- * the user back to maintaining `transform: [...]` by hand.
544
- *
545
- * Over-collecting is safe and under-collecting is not: a package that is listed but
546
- * never imported costs nothing, because inlining only applies to files that are
547
- * actually loaded.
548
- */
549
- /**
550
- * Directories of the workspace members a manifest declares, plus any listed in a
551
- * sibling pnpm-workspace.yaml.
552
- *
553
- * Needed because `manifestsFrom` only walks UP. In a workspace the run root is
554
- * frequently ABOVE the package under test — Nx invokes tasks from the workspace
555
- * root, and Vitest's root defaults to the working directory — so the app's own
556
- * dependencies are declared in a manifest that walking up never reaches. The
557
- * package then misses auto-detection and stays in Vite's graph while Node loads it
558
- * too, which is the dual-ownership failure reproducing from nothing but a different
559
- * working directory.
560
- *
561
- * Only the two glob shapes workspace fields actually use are expanded (`dir/*` and a
562
- * literal path). Over-collecting is safe here — an unimported package costs nothing —
563
- * so a shape that is not understood is skipped rather than approximated.
564
- */
565
- function workspaceMemberDirs(dir, manifest) {
566
- const patterns = [];
567
- const declared = manifest.workspaces;
568
- if (Array.isArray(declared)) patterns.push(...declared.filter((p) => typeof p === "string"));
569
- else if (declared && typeof declared === "object" && Array.isArray(declared.packages)) patterns.push(...declared.packages.filter((p) => typeof p === "string"));
570
- try {
571
- const yaml = fs.readFileSync(path.join(dir, "pnpm-workspace.yaml"), "utf8");
572
- for (const line of yaml.split(/\r?\n/)) {
573
- const entry = /^\s*-\s*["']?([^"'#]+?)["']?\s*$/.exec(line);
574
- if (entry) patterns.push(entry[1]);
575
- }
576
- } catch {}
577
- const dirs = [];
578
- for (const pattern of patterns) if (pattern.endsWith("/*")) {
579
- const parent = path.join(dir, pattern.slice(0, -2));
580
- try {
581
- for (const entry of fs.readdirSync(parent, { withFileTypes: true })) if (entry.isDirectory()) dirs.push(path.join(parent, entry.name));
582
- } catch {}
583
- } else if (!pattern.includes("*")) dirs.push(path.join(dir, pattern));
584
- return dirs;
585
- }
586
- function manifestsFrom(projectRoot) {
587
- const manifests = [];
588
- let dir = path.resolve(projectRoot);
589
- for (;;) {
590
- try {
591
- const raw = fs.readFileSync(path.join(dir, "package.json"), "utf8");
592
- const manifest = JSON.parse(raw);
593
- manifests.push({
594
- dir,
595
- manifest
596
- });
597
- for (const member of workspaceMemberDirs(dir, manifest)) try {
598
- manifests.push({
599
- dir: member,
600
- manifest: JSON.parse(fs.readFileSync(path.join(member, "package.json"), "utf8"))
601
- });
602
- } catch {}
603
- } catch {}
604
- const parent = path.dirname(dir);
605
- if (parent === dir) return manifests;
606
- dir = parent;
607
- }
608
- }
609
- /**
610
- * The paths a `resolve.alias` config points into, whatever each entry's `find` is: a
611
- * string, or a RegExp (an alias Vite applies to imports, which `jest.requireActual`
612
- * cannot, so serializableAliases leaves it out of the compat layer's list). These seed
613
- * the closure walk through the workspace members that contain them (ReachedPackages).
614
- *
615
- * A replacement may substitute part of the match (`/abs/packages/ui/src$1`): only the
616
- * text before its first substitution is fixed (fixedReplacement), and that part is the
617
- * path the alias reaches. A substitution that chooses the member (`/abs/packages/$1`)
618
- * leaves a fixed part above every member, so it reaches none: walking every member such
619
- * an alias could produce is the "seed from every member" #433 rejected. A `$` that is
620
- * not a substitution (`/home/ci/$work`, a `c$` share) is part of the path. A replacement
621
- * starting with `.` is taken from `root`, as the compat layer takes it; anything else
622
- * that is not absolute (a package name) reaches no member.
623
- *
624
- * Plugins that resolve through `resolveId` (vite-tsconfig-paths, nxViteTsPaths) add no
625
- * alias entry, so they are out of reach here by construction.
626
- */
627
- function aliasReachedPaths(alias, root) {
628
- const list = Array.isArray(alias) ? alias : alias && typeof alias === "object" ? Object.entries(alias).map(([find, replacement]) => ({
629
- find,
630
- replacement
631
- })) : [];
632
- const reached = [];
633
- for (const item of list) {
634
- const entry = item;
635
- const replacement = entry?.replacement;
636
- if (typeof replacement !== "string") continue;
637
- const fixed = fixedReplacement(replacement, entry?.find instanceof RegExp);
638
- const target = fixed.startsWith(".") ? path.resolve(root, fixed) : fixed;
639
- if (target && path.isAbsolute(target)) reached.push(target);
640
- }
641
- return reached;
642
- }
643
- /**
644
- * The text of an alias replacement up to its first substitution, with `$$` read as `$`.
645
- * Vite applies an alias with `String.prototype.replace`, which substitutes `$&`, `` $` ``
646
- * and `$'` for any pattern, and `$n` and `$<name>` for a RegExp; every other `$` is
647
- * literal (with a string pattern, `$1` is too).
648
- */
649
- function fixedReplacement(replacement, regExp) {
650
- let fixed = "";
651
- for (let i = 0; i < replacement.length; i++) {
652
- const char = replacement[i];
653
- if (char !== "$") {
654
- fixed += char;
655
- continue;
656
- }
657
- const next = replacement[i + 1] ?? "";
658
- if (next === "$") {
659
- fixed += "$";
660
- i++;
661
- } else if (next === "&" || next === "`" || next === "'") break;
662
- else if (regExp && (/[0-9]/.test(next) || next === "<")) break;
663
- else fixed += "$";
664
- }
665
- return fixed;
666
- }
667
- /**
668
- * Packages in the project that declare React Native in their own manifest.
669
- *
670
- * These are the ones published the way the React Native ecosystem publishes:
671
- * untranspiled JSX, Flow, or TypeScript, on the assumption that Metro will compile
672
- * them. Node cannot run that source, which is why they previously had to be listed
673
- * by hand in `transform: [...]` — a list every project had to discover the hard way,
674
- * one `SyntaxError: Unexpected token '<'` at a time.
675
- *
676
- * A package's own manifest is the authority here rather than a heuristic on its
677
- * name: `react-native-*` misses `@gorhom/bottom-sheet` and would wrongly claim
678
- * `react-native` itself, while the manifest states the relationship exactly.
679
- *
680
- * Declared dependencies are read from the project and every manifest above it, so a
681
- * workspace that declares its React Native libraries at the repository root is covered
682
- * too. Resolving each name is cheap and package-manager-agnostic, where walking the
683
- * installed tree depends on the store layout. Transitive dependencies that nothing
684
- * declares stay available through `transform: [...]`.
685
- *
686
- * Excluded: packages a preset already shadows (their real source never loads), the
687
- * test infrastructure in NEVER_INLINE, and anything the consumer listed explicitly
688
- * in `transform` — that option keeps its existing meaning and takes precedence.
689
- *
690
- * `dirOf` finds a dependency's directory from a directory: `dependencyDirOf`, or a
691
- * memoized copy of it (memoizePackageDirOf). Not `packageDirOf`, whose answer for a
692
- * workspace member differs (see dependencyDirOf).
693
- *
694
- * `reachedPaths` adds the workspace members an alias reaches; see ReachedPackages.
695
- */
696
- function detectEcosystemPackages(projectRoot, explicit = [], testRoots = [], neverTransform = [], activePresets, dirOf = dependencyDirOf, { reachedPaths = [], onReachedUndeclared } = {}) {
697
- runtimeMemo.clear();
698
- const roots = (Array.isArray(projectRoot) ? projectRoot : [projectRoot]).filter(Boolean);
699
- const shadowed = Object.entries(AUTO_DETECT_PRESETS).filter(([, presetName]) => activePresets === void 0 || activePresets.includes(presetName)).map(([pkg]) => pkg);
700
- const skip = /* @__PURE__ */ new Set([
701
- ...NEVER_INLINE,
702
- ...shadowed,
703
- ...explicit,
704
- ...neverTransform
705
- ]);
706
- const candidates = /* @__PURE__ */ new Set();
707
- const found = roots.flatMap((root) => manifestsFrom(root));
708
- const declaringDirs = [...new Set(found.map((entry) => entry.dir))];
709
- for (const { manifest } of found) for (const field of [
710
- "dependencies",
711
- "devDependencies",
712
- "optionalDependencies"
713
- ]) {
714
- const deps = manifest[field];
715
- if (deps && typeof deps === "object") for (const name of Object.keys(deps)) candidates.add(name);
716
- }
717
- if (candidates.size === 0) return [];
718
- const installedFrom = (fromDir, name) => {
719
- const dir = dirOf(name, fromDir);
720
- if (!dir) return null;
721
- try {
722
- return {
723
- manifest: JSON.parse(fs.readFileSync(path.join(dir, "package.json"), "utf8")),
724
- dir
725
- };
726
- } catch {
727
- return null;
728
- }
729
- };
730
- /** Resolve a package's manifest from whichever root can see it. */
731
- const installedOf = (name) => {
732
- for (const dir of declaringDirs) {
733
- const installed = installedFrom(dir, name);
734
- if (installed) return installed;
735
- }
736
- return null;
737
- };
738
- const manifestOf = (name) => installedOf(name)?.manifest ?? null;
739
- const dependencyOf = (parent, name) => installedFrom(parent.dir, name);
740
- /**
741
- * The packages the run itself lives in — the project, in other words.
742
- *
743
- * In a workspace, the package under test is usually declared as a dependency by a
744
- * sibling or by the repository root, so it appears in the candidate set like any
745
- * third-party library — and it declares React Native, because it is React Native
746
- * code. Detecting it would claim the project's own source: its directory becomes a
747
- * `server.deps.external` pattern, so Vitest hands every file under it to Node,
748
- * where the loader compiles it to CommonJS. A test file's own
749
- * `import { it } from 'vitest'` becomes `require('vitest')`, which throws
750
- * "Vitest cannot be imported in a CommonJS module using require()" — a failure that
751
- * appears in one workspace package and not another for no visible reason.
752
- *
753
- * A package cannot be its own dependency, so a manifest whose directory contains a
754
- * run root belongs to the project. Read straight off the manifests already walked,
755
- * which is both cheaper than resolving each candidate and independent of how a
756
- * package manager happens to lay out its store — under pnpm every workspace member
757
- * is additionally linked into a hidden directory on NODE_PATH, so a package can
758
- * resolve its own name from its own directory, but nothing here depends on that.
759
- *
760
- * Workspace libraries the project merely depends on sit beside a run root rather
761
- * than above it and are unaffected — detecting those is the point of the
762
- * workspace-member walk above.
763
- */
764
- const ownerRoots = [...roots, ...testRoots];
765
- const runOwners = new Set(found.filter(({ dir }) => ownerRoots.some((root) => containsPath(dir, root))).map(({ manifest }) => manifest.name).filter((name) => typeof name === "string"));
766
- const ownsTheRun = (name) => runOwners.has(name);
767
- const detected = [];
768
- for (const name of candidates) {
769
- if (skip.has(name) || name.startsWith("@react-native/")) continue;
770
- const pkg = manifestOf(name);
771
- if (pkg && dependsOnReactNative(pkg) && !ownsTheRun(name)) detected.push(name);
772
- }
773
- const rnOwned = new Set(Object.keys(manifestOf("react-native")?.dependencies ?? {}));
774
- /** Every package reachable from `starts` through runtime dependencies. */
775
- const closureOf = (starts) => {
776
- const seen = /* @__PURE__ */ new Set();
777
- const pending = [...starts];
778
- while (pending.length > 0) {
779
- const [name, installed] = pending.pop();
780
- if (seen.has(name)) continue;
781
- seen.add(name);
782
- const deps = installed?.manifest.dependencies;
783
- if (!installed || !deps || typeof deps !== "object") continue;
784
- for (const dep of Object.keys(deps)) if (!seen.has(dep)) pending.push([dep, dependencyOf(installed, dep)]);
785
- }
786
- return seen;
787
- };
788
- const reactNativeInstalled = installedOf("react-native");
789
- const expoInstalled = installedOf("expo");
790
- const seed = (name) => [name, installedOf(name) ?? (reactNativeInstalled && dependencyOf(reactNativeInstalled, name)) ?? (expoInstalled && dependencyOf(expoInstalled, name))];
791
- const toolchain = closureOf([
792
- seed("@babel/core"),
793
- seed("@react-native/babel-preset"),
794
- seed("babel-preset-expo"),
795
- seed("@babel/runtime"),
796
- seed("metro"),
797
- seed("@expo/metro")
798
- ]);
799
- const projectDeclared = /* @__PURE__ */ new Set();
800
- for (const { dir, manifest } of found) {
801
- if (!ownerRoots.some((root) => containsPath(dir, root))) continue;
802
- for (const field of [
803
- "dependencies",
804
- "devDependencies",
805
- "optionalDependencies"
806
- ]) {
807
- const deps = manifest[field];
808
- if (deps && typeof deps === "object") for (const name of Object.keys(deps)) projectDeclared.add(name);
809
- }
810
- }
811
- const detectedSet = new Set(detected);
812
- const inClosure = new Set(detected);
813
- const walked = /* @__PURE__ */ new Set();
814
- const queue = [];
815
- const reach = (name, installed) => {
816
- inClosure.add(name);
817
- if (walked.has(name)) return;
818
- walked.add(name);
819
- queue.push(installed);
820
- };
821
- for (const name of detected) {
822
- if (!projectDeclared.has(name)) continue;
823
- const installed = installedOf(name);
824
- if (installed) reach(name, installed);
825
- }
826
- const neverSeeded = /* @__PURE__ */ new Set([...shadowed, ...neverTransform]);
827
- for (const name of explicit) {
828
- if (neverSeeded.has(name)) continue;
829
- const installed = installedOf(name);
830
- if (!installed || walked.has(name)) continue;
831
- walked.add(name);
832
- queue.push(installed);
833
- }
834
- /** A dependency or peer the walk may not take, whatever its manifest says. */
835
- const excluded = (dep) => skip.has(dep) || dep.startsWith("@react-native/") || rnOwned.has(dep) || toolchain.has(dep) || ownsTheRun(dep);
836
- /**
837
- * Walk the queue. With `installedOnly`, only installed packages (a real path inside a
838
- * node_modules directory) are added: see "Workspace members the run reaches" below.
839
- */
840
- const walk = (installedOnly) => {
841
- const admits = (installed) => !installedOnly || NODE_MODULES_DIR.test(installed.dir);
842
- while (queue.length > 0) {
843
- const pkg = queue.pop();
844
- const deps = pkg.manifest.dependencies;
845
- for (const dep of deps && typeof deps === "object" ? Object.keys(deps) : []) {
846
- if (walked.has(dep) || excluded(dep)) continue;
847
- const installed = dependencyOf(pkg, dep);
848
- if (!installed) continue;
849
- if (!inClosure.has(dep) && publishesOnlyEsm(installed.manifest)) continue;
850
- if (admits(installed)) reach(dep, installed);
851
- }
852
- const peers = pkg.manifest.peerDependencies;
853
- const peersMeta = pkg.manifest.peerDependenciesMeta;
854
- for (const peer of peers && typeof peers === "object" ? Object.keys(peers) : []) {
855
- if (walked.has(peer) || excluded(peer)) continue;
856
- const installed = dependencyOf(pkg, peer);
857
- if (!installed || !admits(installed)) continue;
858
- const loadedReactNativePeer = !detectedSet.has(peer) && peersMeta?.[peer]?.optional !== true && dependsOnReactNative(installed.manifest) && runtimeImports(pkg.dir, pkg.manifest).has(peer);
859
- if (detectedSet.has(peer) || loadedReactNativePeer) reach(peer, installed);
860
- }
861
- }
862
- };
863
- walk(false);
864
- const members = found.filter(({ dir, manifest }) => typeof manifest.name === "string" && !ownerRoots.some((root) => containsPath(dir, root)));
865
- const memberByName = new Map(members.map((m) => [m.manifest.name, m]));
866
- const reachedMembers = /* @__PURE__ */ new Map();
867
- const reachMember = (member) => {
868
- if (reachedMembers.has(member.dir)) return;
869
- reachedMembers.set(member.dir, member);
870
- const deps = member.manifest.dependencies;
871
- for (const dep of deps && typeof deps === "object" ? Object.keys(deps) : []) {
872
- const other = memberByName.get(dep);
873
- if (other) reachMember(other);
874
- }
875
- };
876
- for (const name of projectDeclared) {
877
- const member = memberByName.get(name);
878
- if (member) reachMember(member);
879
- }
880
- for (const target of reachedPaths) {
881
- const member = members.filter(({ dir }) => containsPath(dir, target)).sort((a, b) => b.dir.length - a.dir.length)[0];
882
- if (!member) continue;
883
- if (!reachedMembers.has(member.dir)) onReachedUndeclared?.(member.manifest.name, member.dir);
884
- reachMember(member);
885
- }
886
- for (const member of reachedMembers.values()) {
887
- const deps = member.manifest.dependencies;
888
- for (const dep of deps && typeof deps === "object" ? Object.keys(deps) : []) {
889
- if (walked.has(dep) || excluded(dep) || !detectedSet.has(dep)) continue;
890
- const installed = installedFrom(member.dir, dep);
891
- if (installed) reach(dep, installed);
892
- }
893
- }
894
- walk(true);
895
- return [...inClosure].sort();
896
- }
897
- // src/host.ts
898
- /** The running Vite's version, and where it was read, for messages that name it. */
899
- async function runningVite(context) {
900
- const fromHost = context?.meta?.viteVersion;
901
- if (typeof fromHost === "string") return {
902
- version: fromHost,
903
- source: "the running Vite"
904
- };
905
- try {
906
- const vite = await import("vite");
907
- if (typeof vite.version !== "string") return null;
908
- let at = "";
909
- try {
910
- at = ` at ${path.dirname(createRequire(import.meta.url).resolve("vite/package.json"))}`;
911
- } catch {}
912
- return {
913
- version: vite.version,
914
- source: `the vite module${at}`
915
- };
916
- } catch {
917
- return null;
918
- }
919
- }
920
- /**
921
- * The version of Vite installed where `root` resolves it, read from the module, for
922
- * diagnostics that run without a Vite process (`doctor`, `migrate`). Falls back to the
923
- * manifest, preferring the Vite version a wrapper records it bundles.
924
- */
925
- function installedViteVersion(root) {
926
- const req = createRequire(path.join(root, "package.json"));
927
- try {
928
- const version = req("vite").version;
929
- if (typeof version === "string") return version;
930
- } catch {}
931
- try {
932
- const manifest = req("vite/package.json");
933
- return manifest.bundledVersions?.vite ?? manifest.version ?? null;
934
- } catch {
935
- return null;
936
- }
937
- }
938
- /** Whether the project at `root` runs its tests through Vite+. */
939
- function usesVitePlus(root) {
940
- try {
941
- createRequire(path.join(root, "package.json")).resolve("vite-plus/package.json");
942
- return true;
943
- } catch {
944
- return false;
945
- }
946
- }
947
- /** The `vitest` package this package's own files resolve by name, or null. */
948
- function ownVitestPackage() {
949
- try {
950
- const req = createRequire(import.meta.url);
951
- const manifest = req.resolve("vitest/package.json");
952
- const { version } = req(manifest);
953
- return {
954
- root: realPath(path.dirname(manifest)),
955
- version
956
- };
957
- } catch {
958
- return null;
959
- }
960
- }
961
- /**
962
- * A path's canonical spelling. `realpathSync.native` asks the OS, which returns the long
963
- * on-disk spelling (no 8.3 short names) and the on-disk case on Windows and macOS. It is
964
- * what the error messages show.
965
- */
966
- function realPath(file) {
967
- return fs.realpathSync.native(file);
968
- }
969
- /** Whether two canonical paths are one directory: without case on Windows, as NTFS looks up. */
970
- function samePath(a, b) {
971
- return process.platform === "win32" ? a.toLowerCase() === b.toLowerCase() : a === b;
972
- }
973
- /** The directory of the package that contains `file`, by its nearest package.json. */
974
- function packageRootOf(file) {
975
- let dir = realPath(file);
976
- const start = dir;
977
- for (;;) {
978
- if (fs.existsSync(path.join(dir, "package.json"))) return dir;
979
- const parent = path.dirname(dir);
980
- if (parent === dir) return start;
981
- dir = parent;
982
- }
983
- }
984
- function twinError(running, other, via, alternative = "") {
985
- 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);
986
- }
987
- /**
988
- * Fail fast when what the host actually loads for vitest-native's own `import 'vitest'`
989
- * is not the running Vitest.
990
- *
991
- * A second physical copy is not a problem by itself: Vitest's own resolver maps every
992
- * `vitest` import in a module it runs (setup files included) to the running copy, which
993
- * is how peer-variant installs (two copies of the same version) work. So the question is
994
- * put to the host, through the project's Vite resolver, for the file that imports it.
995
- */
996
- async function assertHostResolvesRunningVitest(running, resolveId, importer) {
997
- const resolved = await resolveId("vitest", importer);
998
- const id = typeof resolved === "string" ? resolved : resolved?.id;
999
- if (!id || !path.isAbsolute(id) || !fs.existsSync(id)) return;
1000
- const runningRoot = packageRootOf(running.distPath);
1001
- const loadedRoot = packageRootOf(id);
1002
- if (samePath(loadedRoot, runningRoot)) return;
1003
- throw twinError({
1004
- root: runningRoot,
1005
- version: running.version
1006
- }, loadedRoot, "the Vite resolver, for vitest-native's setup file,");
1007
- }
1008
- /**
1009
- * Fail fast when the hot runtime's worker, which Node loads directly and so outside
1010
- * Vitest's resolver, would import a different physical copy of Vitest from the running
1011
- * one.
1012
- */
1013
- function assertHotWorkerLoadsRunningVitest(running, workerEntry) {
1014
- let manifest;
1015
- try {
1016
- manifest = createRequire(workerEntry).resolve("vitest/package.json");
1017
- } catch {
1018
- return;
1019
- }
1020
- const runningRoot = packageRootOf(running.distPath);
1021
- const loadedRoot = realPath(path.dirname(manifest));
1022
- if (samePath(loadedRoot, runningRoot)) return;
1023
- throw twinError({
1024
- root: runningRoot,
1025
- version: running.version
1026
- }, 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.");
1027
- }
1028
- 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 };