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.
Files changed (97) hide show
  1. package/README.md +76 -60
  2. package/dist/cli.d.mts +1 -3
  3. package/dist/cli.mjs +175 -63
  4. package/dist/context.d.mts +45 -0
  5. package/dist/context.mjs +243 -0
  6. package/dist/errors.d.mts +3 -0
  7. package/dist/helpers.cjs +53 -4
  8. package/dist/helpers.d.cts +1 -3
  9. package/dist/helpers.d.mts +1 -3
  10. package/dist/helpers.mjs +2 -3
  11. package/dist/host-5o48Ujzs.mjs +939 -0
  12. package/dist/{index-CzQazgp9.d.cts → index-DqU4YO3D.d.mts} +27 -49
  13. package/dist/index.d.mts +1 -3
  14. package/dist/index.mjs +463 -595
  15. package/dist/jest-compat/error-equality.mjs +127 -0
  16. package/dist/jest-compat/jest-object.mjs +149 -4
  17. package/dist/jest-compat/node-registry.mjs +233 -58
  18. package/dist/jest-compat/setup.mjs +28 -4
  19. package/dist/jest-compat.cjs +227 -52
  20. package/dist/jest-compat.d.cts +5 -6
  21. package/dist/jest-compat.d.mts +5 -6
  22. package/dist/jest-compat.mjs +204 -52
  23. package/dist/matchers.cjs +1 -2
  24. package/dist/matchers.d.cts +0 -2
  25. package/dist/matchers.d.mts +0 -2
  26. package/dist/matchers.mjs +1 -2
  27. package/dist/{memory-FYbP0_gg.mjs → memory-Couw0Esx.mjs} +31 -6
  28. package/dist/native/assets.d.mts +2 -0
  29. package/dist/native/assets.mjs +34 -0
  30. package/dist/native/babel-toolchain.mjs +190 -0
  31. package/dist/native/babel-worker.mjs +47 -0
  32. package/dist/native/boundary.mjs +23 -8
  33. package/dist/native/compile-cache.mjs +21 -9
  34. package/dist/native/coverage-v8.mjs +287 -0
  35. package/dist/native/esm-interop.mjs +216 -0
  36. package/dist/native/expo-native-modules.mjs +7 -1
  37. package/dist/native/globals.mjs +104 -6
  38. package/dist/native/hooks.mjs +271 -60
  39. package/dist/native/loader.mjs +378 -20
  40. package/dist/native/match.d.mts +24 -2
  41. package/dist/native/match.mjs +117 -12
  42. package/dist/native/metro-profile-compiler.mjs +2 -31
  43. package/dist/native/module-reset.mjs +37 -5
  44. package/dist/native/native-modules.d.mts +2 -3
  45. package/dist/native/native-modules.mjs +22 -21
  46. package/dist/native/ownership.d.mts +10 -0
  47. package/dist/native/ownership.mjs +96 -9
  48. package/dist/native/registry-compiler.mjs +6 -0
  49. package/dist/native/registry.mjs +138 -119
  50. package/dist/native/resident-health.mjs +133 -0
  51. package/dist/native/resolve.d.mts +6 -0
  52. package/dist/native/resolve.mjs +100 -9
  53. package/dist/native/rntl-hooks.mjs +157 -6
  54. package/dist/native/rntl-text-host.mjs +64 -0
  55. package/dist/native/runner.mjs +73 -0
  56. package/dist/native/setup.mjs +96 -70
  57. package/dist/native/state-manifest.mjs +14 -8
  58. package/dist/native/transform.d.mts +2 -0
  59. package/dist/native/transform.mjs +476 -59
  60. package/dist/native/worker.mjs +65 -36
  61. package/dist/{pool-DjpOjOf3.mjs → pool-CFSpNfyw.mjs} +37 -11
  62. package/dist/{preset-map-BlBriTA0.mjs → preset-map-CogjYmSw.mjs} +4 -19
  63. package/dist/preset-modules.mjs +2 -11
  64. package/dist/{presets--zrEWQC2.mjs → presets-CXDyg51l.mjs} +65 -82
  65. package/dist/presets.d.mts +1 -1
  66. package/dist/presets.mjs +1 -1
  67. package/dist/report-error.d.mts +20 -0
  68. package/dist/report-error.mjs +145 -0
  69. package/dist/rntl-support.d.mts +12 -0
  70. package/dist/rntl-support.mjs +189 -0
  71. package/dist/{rolldown-runtime-BhDjJH2R.mjs → rolldown-runtime-D70C1uOS.mjs} +1 -2
  72. package/dist/serializer.cjs +1 -2
  73. package/dist/serializer.d.cts +1 -3
  74. package/dist/serializer.d.mts +1 -3
  75. package/dist/serializer.mjs +1 -2
  76. package/dist/setup.mjs +95 -156
  77. package/dist/{worker-vitest-BGPo0ek6.mjs → worker-vitest-CILPFeRX.mjs} +2 -3
  78. package/docs/migrating-from-jest.md +76 -12
  79. package/docs/release-readiness.md +1 -1
  80. package/package.json +119 -102
  81. package/CHANGELOG.md +0 -2491
  82. package/dist/cli.cjs +0 -1951
  83. package/dist/cli.d.cts +0 -3
  84. package/dist/ecosystem-D6e1OVOg.mjs +0 -1019
  85. package/dist/ecosystem-MFwkbnaC.cjs +0 -1099
  86. package/dist/errors-B3lJK46O.cjs +0 -75
  87. package/dist/errors-CxoBUfVJ.mjs +0 -64
  88. package/dist/index-xw43lBlv.d.mts +0 -481
  89. package/dist/memory-6EPHrJA1.cjs +0 -144
  90. package/dist/pool-B4yesGhI.cjs +0 -121
  91. package/dist/preset-map-jSFsNy1Q.cjs +0 -241
  92. package/dist/preset-modules-BoLkaeEN.cjs +0 -53
  93. package/dist/preset-modules-CG8-G82P.mjs +0 -36
  94. package/dist/presets-9f83H0WW.cjs +0 -3939
  95. package/dist/rolldown-runtime-C0BPl7ul.cjs +0 -43
  96. package/dist/worker-vitest-BfiQB8ND.cjs +0 -62
  97. package/docs/hot-default-design.md +0 -216
package/dist/index.mjs CHANGED
@@ -1,76 +1,24 @@
1
- import { n as VitestNativeTypeError, t as VitestNativeError } from "./errors-CxoBUfVJ.mjs";
2
- import { a as findNativeInlineConflicts, c as containsPath, d as validateOptions, f as validatePeerDependency, i as createNativeOwnershipPolicy, l as packageDirOf, n as detectEngine, o as findNativeOwnershipConflict, p as warnUnknownOptions, s as formatNativeOwnershipManifest, t as detectEcosystemPackages, u as PEER_REQUIREMENTS } from "./ecosystem-D6e1OVOg.mjs";
3
- import { n as presetFromModule } from "./preset-modules-CG8-G82P.mjs";
4
- import { M as BUILT_IN_PRESET, t as presets_exports } from "./presets--zrEWQC2.mjs";
5
- import { a as presetForInstalled, i as autoDetectedPresetApplies, n as DEFAULT_ASSET_EXTS, r as PRESET_MODULES, t as AUTO_DETECT_PRESETS } from "./preset-map-BlBriTA0.mjs";
6
- import { t as workerVitestMismatch } from "./worker-vitest-BGPo0ek6.mjs";
1
+ import { _ as validateOptions, a as runningVite, c as detectEcosystemPackages, f as shouldDefaultFsModuleCache, g as unsupportedExpoSdkMessage, h as installedExpoVersion, i as ownVitestPackage, l as detectEngine, m as SUPPORTED_EXPO_SDKS, n as assertHotWorkerLoadsRunningVitest, p as PEER_REQUIREMENTS, s as aliasReachedPaths, t as assertHostResolvesRunningVitest, u as fsModuleCacheKey, v as validatePeerDependency, y as warnUnknownOptions } from "./host-5o48Ujzs.mjs";
2
+ import { M as BUILT_IN_PRESET, t as presets_exports } from "./presets-CXDyg51l.mjs";
3
+ import { a as presetForInstalled, i as autoDetectedPresetApplies, n as DEFAULT_ASSET_EXTS, r as PRESET_MODULES, t as AUTO_DETECT_PRESETS } from "./preset-map-CogjYmSw.mjs";
4
+ import { t as workerVitestMismatch } from "./worker-vitest-CILPFeRX.mjs";
7
5
  import { createRequire } from "node:module";
8
- import fs from "node:fs";
9
- import path from "node:path";
6
+ import { extensionsFor, firstExact } from "./native/resolve.mjs";
10
7
  import { fileURLToPath, pathToFileURL } from "node:url";
8
+ import path from "node:path";
9
+ import fs from "node:fs";
11
10
  import os from "node:os";
12
11
  import flowRemoveTypes from "flow-remove-types";
13
- import { createHash } from "node:crypto";
14
- //#region src/native/resolve.mjs
15
- /**
16
- * Metro's default `sourceExts`, in its order. Kept as data rather than spelled out
17
- * per platform so the Vite graph and the Node graph cannot drift apart — both build
18
- * their list from this one array (see `getPlatformExtensions` in ../resolve.ts).
19
- *
20
- * The order is load-bearing where a module has more than one variant on disk:
21
- * Metro picks `Foo.js` over `Foo.tsx`, so this list must too, or a project with a
22
- * compiled file beside its source tests a different file than it ships. `json` is
23
- * a source extension to Metro, which is why `import config from './config'`
24
- * resolves `config.json` in an app.
25
- */
26
- const METRO_SOURCE_EXTS = [
27
- "js",
28
- "jsx",
29
- "json",
30
- "ts",
31
- "tsx"
32
- ];
33
- /**
34
- * Extension-MAJOR, exactly as Metro resolves: for each source extension in order,
35
- * try the platform variant, then `.native`, then bare — `.ios.js`, `.native.js`,
36
- * `.js`, `.ios.jsx`, … (metro-resolver's `resolveSourceFile` loops `sourceExts`
37
- * in the outer loop and the platform variants inside it).
38
- *
39
- * This order previously interleaved the other way — every `.ios.*` before any
40
- * `.native.*` before any bare extension — and the difference is not stylistic:
41
- * a module shipping `Foo.native.js` beside `Foo.ios.tsx` resolves to
42
- * `.native.js` under Metro (the `js` round wins before `tsx` is ever tried) but
43
- * resolved to `.ios.tsx` here, so the test ran a different file than the app
44
- * ships. The order is asserted against real metro-resolver by
45
- * tests/metro-resolver-oracle.test.ts, not just against these literals.
46
- */
47
- function extensionsFor(platform, sourceExts = METRO_SOURCE_EXTS) {
48
- const suffix = platform === "android" ? "android" : "ios";
49
- const exts = [];
50
- for (const e of sourceExts) exts.push(`.${suffix}.${e}`, `.native.${e}`, `.${e}`);
51
- return exts;
52
- }
53
- /**
54
- * Whether `file` exists under exactly this name.
55
- *
56
- * macOS and Windows disks are case-insensitive by default, so `fs.existsSync("App.json")`
57
- * is true when only `app.json` exists. Resolving `./App` in extension order (Metro's: js,
58
- * jsx, json, ts, tsx) then picks the React Native template's `app.json` over its `App.tsx`,
59
- * and the template's own test renders `{ name, displayName }`. Metro resolves from a
60
- * case-sensitive file map, as does Linux, which is why neither Metro nor CI saw it. The
61
- * directory listing has the real names. Checked for the file's own name: the case the
62
- * template hits, and one `readdir` per hit, which the resolution caches absorb.
63
- */
64
- function existsExact(file) {
65
- if (!fs.existsSync(file)) return false;
66
- try {
67
- return fs.readdirSync(path.dirname(file)).includes(path.basename(file));
68
- } catch {
69
- return true;
70
- }
71
- }
72
- //#endregion
73
- //#region src/resolve.ts
12
+ import { VitestNativeError, VitestNativeTypeError } from "./errors.mjs";
13
+ import { presetFromModule } from "./preset-modules.mjs";
14
+ import { serializableAliases } from "./jest-compat/aliases.mjs";
15
+ import { tsconfigPathAliases } from "./native/tsconfig-paths.mjs";
16
+ import { knownNativeModulesFor, nativeModuleSpecsFor } from "./native/native-modules.mjs";
17
+ import { createNativeOwnershipPolicy, findNativeInlineConflicts, findNativeOwnershipConflict, formatNativeOwnershipManifest } from "./native/ownership.mjs";
18
+ import { containsPath, dependencyDirOf, isPackageEntryFile, memoizePackageDirOf, packageDirOf } from "./native/match.mjs";
19
+ import { CONTEXT_ENV, ensureProjectContext, projectContext, writeProjectContext } from "./context.mjs";
20
+ import { cacheRootFor } from "./native/transform.mjs";
21
+ // src/resolve.ts
74
22
  /**
75
23
  * Extension search order for the Vite graph, taken from the same definition the
76
24
  * Node graph uses. Vite's default list is replaced wholesale by whatever is set
@@ -87,397 +35,8 @@ function getPlatformExtensions(platform) {
87
35
  function getConfiguredPlatformExtensions(platform, sourceExts) {
88
36
  return extensionsFor(platform, sourceExts);
89
37
  }
90
- //#endregion
91
- //#region src/jest-compat/aliases.mjs
92
- /**
93
- * The string-to-string entries of a Vite `resolve.alias`, in either of its shapes, with
94
- * relative replacements made absolute against `root`. Regex `find`s and custom
95
- * resolvers cannot cross into the test worker, so they are listed as `skipped` for the
96
- * error that explains a miss.
97
- *
98
- * @param {unknown} alias `resolve.alias`: an object, or an array of `{ find, replacement }`
99
- * @param {string} root project root, for relative replacements
100
- * @returns {{ entries: [string, string][], skipped: string[] }}
101
- */
102
- function serializableAliases(alias, root) {
103
- const entries = [];
104
- const skipped = [];
105
- const list = Array.isArray(alias) ? alias : alias && typeof alias === "object" ? Object.entries(alias).map(([find, replacement]) => ({
106
- find,
107
- replacement
108
- })) : [];
109
- for (const item of list) {
110
- const find = item?.find;
111
- const replacement = item?.replacement;
112
- if (typeof find !== "string" || typeof replacement !== "string" || item.customResolver) {
113
- skipped.push(String(find));
114
- continue;
115
- }
116
- entries.push([find, replacement.startsWith(".") ? path.resolve(root, replacement) : replacement]);
117
- }
118
- return {
119
- entries,
120
- skipped
121
- };
122
- }
123
- //#endregion
124
- //#region src/native/tsconfig-paths.mjs
125
- /** JSON with comments and trailing commas (tsconfig's format) → JSON. */
126
- function stripJsonc(text) {
127
- let out = "";
128
- let inString = false;
129
- for (let i = 0; i < text.length; i++) {
130
- const c = text[i];
131
- if (inString) {
132
- out += c;
133
- if (c === "\\") out += text[++i] ?? "";
134
- else if (c === "\"") inString = false;
135
- } else if (c === "\"") {
136
- inString = true;
137
- out += c;
138
- } else if (c === "/" && text[i + 1] === "/") {
139
- while (i < text.length && text[i] !== "\n") i++;
140
- out += "\n";
141
- } else if (c === "/" && text[i + 1] === "*") {
142
- i += 2;
143
- while (i < text.length && !(text[i] === "*" && text[i + 1] === "/")) i++;
144
- i++;
145
- } else out += c;
146
- }
147
- return dropTrailingCommas(out);
148
- }
149
- function dropTrailingCommas(text) {
150
- let out = "";
151
- let inString = false;
152
- for (let i = 0; i < text.length; i++) {
153
- const c = text[i];
154
- if (inString) {
155
- out += c;
156
- if (c === "\\") out += text[++i] ?? "";
157
- else if (c === "\"") inString = false;
158
- continue;
159
- }
160
- if (c === "\"") inString = true;
161
- if (c === ",") {
162
- let j = i + 1;
163
- while (j < text.length && /\s/.test(text[j])) j++;
164
- if (text[j] === "}" || text[j] === "]") continue;
165
- }
166
- out += c;
167
- }
168
- return out;
169
- }
170
- function readConfig(file) {
171
- try {
172
- return JSON.parse(stripJsonc(fs.readFileSync(file, "utf8")));
173
- } catch {
174
- return null;
175
- }
176
- }
177
- function resolveExtends(spec, fromDir) {
178
- if (spec.startsWith(".") || path.isAbsolute(spec)) {
179
- const file = path.resolve(fromDir, spec);
180
- return fs.existsSync(file) ? file : fs.existsSync(`${file}.json`) ? `${file}.json` : null;
181
- }
182
- const req = createRequire(path.join(fromDir, "package.json"));
183
- for (const candidate of [
184
- spec,
185
- `${spec}.json`,
186
- `${spec}/tsconfig.json`
187
- ]) try {
188
- return req.resolve(candidate);
189
- } catch {}
190
- return null;
191
- }
192
- function withConfigDir(value, leafDir) {
193
- return value.replaceAll("${configDir}", leafDir);
194
- }
195
- /**
196
- * The compiler options that decide `paths` resolution, merged along `extends` as
197
- * TypeScript does: bases in order, later ones winning, the extending file over all of
198
- * them. `paths` and `baseUrl` are tracked separately, each with the directory that
199
- * declared it, because a base may set `baseUrl` while the leaf sets `paths`. Cycles are
200
- * cut per chain (a stack, not a global set), so two bases sharing a third both see it.
201
- */
202
- function effectiveOptions(file, leafDir, stack = []) {
203
- if (stack.includes(file) || stack.length > 16) return {};
204
- const config = readConfig(file);
205
- if (!config) return {};
206
- const dir = path.dirname(file);
207
- let merged = {};
208
- for (const spec of [config.extends ?? []].flat().filter((s) => typeof s === "string")) {
209
- const base = resolveExtends(withConfigDir(spec, leafDir), dir);
210
- if (base) merged = {
211
- ...merged,
212
- ...effectiveOptions(base, leafDir, [...stack, file])
213
- };
214
- }
215
- const options = config.compilerOptions ?? {};
216
- if (typeof options.baseUrl === "string") merged.baseUrl = path.resolve(dir, withConfigDir(options.baseUrl, leafDir));
217
- if (options.paths && typeof options.paths === "object") {
218
- merged.paths = options.paths;
219
- merged.pathsDir = dir;
220
- }
221
- return merged;
222
- }
223
- /**
224
- * @param {string} projectRoot directory holding tsconfig.json
225
- * @returns {{ entries: [string, string][], skipped: string[] }}
226
- */
227
- function tsconfigPathAliases(projectRoot) {
228
- const entries = [];
229
- const skipped = [];
230
- const leafDir = path.resolve(projectRoot);
231
- const found = effectiveOptions(path.join(leafDir, "tsconfig.json"), leafDir);
232
- if (!found.paths) return {
233
- entries,
234
- skipped
235
- };
236
- const base = found.baseUrl ?? found.pathsDir;
237
- for (const [pattern, targets] of Object.entries(found.paths)) {
238
- const raw = Array.isArray(targets) ? targets[0] : null;
239
- if (typeof raw !== "string") continue;
240
- const target = withConfigDir(raw, leafDir);
241
- const patternStars = pattern.split("*").length - 1;
242
- const targetStars = target.split("*").length - 1;
243
- if (patternStars === 0 && targetStars === 0) entries.push([pattern, path.resolve(base, target)]);
244
- else if (patternStars === 1 && targetStars === 1 && pattern.endsWith("/*") && target.endsWith("/*")) entries.push([pattern.slice(0, -1), `${path.resolve(base, target.slice(0, -2))}/`]);
245
- else skipped.push(pattern);
246
- }
247
- return {
248
- entries,
249
- skipped
250
- };
251
- }
252
- //#endregion
253
- //#region src/fs-module-cache.ts
254
- /**
255
- * Vitest's persistent transform cache (`fsModuleCache`), keyed for what this plugin
256
- * contributes.
257
- *
258
- * Vitest 5 can keep transformed modules on disk between runs, as Jest keeps its
259
- * transform cache. Measured on a 104-file production Expo suite, it cut warm runs by
260
- * about 11%. Vitest keys each entry on the module's id and source, the config file's
261
- * contents, the plugin NAMES, `resolve`, NODE_ENV and its own version — not on plugin
262
- * versions, nor on anything a plugin reads from disk. This plugin's output depends on
263
- * both: its own version, and the installed packages (which presets are detected, which
264
- * packages compile). Vitest's official extension point, a cache key generator, carries
265
- * that part of the key:
266
- * - the vitest-native version,
267
- * - the plugin's resolved options and the environment it hands to workers,
268
- * - the project's lockfile(s), so any dependency change invalidates the cache.
269
- * Without a lockfile the root package.json stands in for it.
270
- */
271
- const LOCKFILES = [
272
- "bun.lock",
273
- "bun.lockb",
274
- "package-lock.json",
275
- "npm-shrinkwrap.json",
276
- "pnpm-lock.yaml",
277
- "yarn.lock"
278
- ];
279
- const sha1 = (value) => createHash("sha1").update(value).digest("hex");
280
- /** A digest of the nearest lockfiles at or above `root`, else of its package.json. */
281
- function dependencyFingerprint(root) {
282
- for (let dir = path.resolve(root);; dir = path.dirname(dir)) {
283
- const found = LOCKFILES.map((name) => path.join(dir, name)).filter((file) => fs.existsSync(file));
284
- if (found.length > 0) {
285
- const hash = createHash("sha1");
286
- for (const file of found) hash.update(file).update(fs.readFileSync(file));
287
- return hash.digest("hex");
288
- }
289
- if (path.dirname(dir) === dir) break;
290
- }
291
- try {
292
- return sha1(fs.readFileSync(path.join(root, "package.json")));
293
- } catch {
294
- return "no-manifest";
295
- }
296
- }
297
- /** The version of the package rooted at `packageDir`. */
298
- function packageVersionAt(packageDir) {
299
- try {
300
- const manifest = JSON.parse(fs.readFileSync(path.join(packageDir, "package.json"), "utf8"));
301
- return typeof manifest.version === "string" ? manifest.version : "unknown";
302
- } catch {
303
- return "unknown";
304
- }
305
- }
306
- /** This plugin's contribution to a module's cache key in one project. */
307
- function fsModuleCacheKey(ownPackageDir, projectRoot, pluginState) {
308
- const state = JSON.stringify(pluginState, (_key, value) => typeof value === "function" || value instanceof RegExp ? String(value) : value);
309
- return sha1(`vitest-native@${packageVersionAt(ownPackageDir)}\0${dependencyFingerprint(projectRoot)}\0${state}`);
310
- }
311
- /**
312
- * Whether to turn the cache on: Vitest 5 (where `fsModuleCache` is a top-level option)
313
- * and the user has not chosen either way, in either spelling.
314
- */
315
- function shouldDefaultFsModuleCache(vitestMajor, userTest) {
316
- if (!(vitestMajor >= 5)) return false;
317
- return userTest?.fsModuleCache === void 0 && userTest?.experimental?.fsModuleCache === void 0;
318
- }
319
- //#endregion
320
- //#region src/native/native-modules.mjs
321
- /** Where React Native's JavaScript lives, relative to the package root. */
322
- const REACT_NATIVE_SOURCE_DIRS = ["Libraries", "src"];
323
- /**
324
- * Directories inside those that are React Native's own tests and test doubles,
325
- * not code an app runs.
326
- */
327
- const SKIPPED_DIRS = /* @__PURE__ */ new Set([
328
- "__tests__",
329
- "__mocks__",
330
- "__flowtests__",
331
- "__fixtures__"
332
- ]);
333
- /** Modules vitest-native implements at the boundary, beyond React Native's own. */
334
- const BOUNDARY_NATIVE_MODULES = Object.freeze(["NitroModules"]);
335
- /**
336
- * The environment variable carrying the known set from the plugin (computed once,
337
- * in the main process) to the workers.
338
- */
339
- const KNOWN_NATIVE_MODULES_ENV = "VITEST_NATIVE_RN_NATIVE_MODULES";
340
- /** Set to "permissive" by the plugin's `nativeModules: 'permissive'` option. */
341
- const PERMISSIVE_NATIVE_MODULES_ENV = "VITEST_NATIVE_NATIVE_MODULES";
342
- /** The same, for each module's spec members. */
343
- const NATIVE_MODULE_SPECS_ENV = "VITEST_NATIVE_RN_NATIVE_MODULE_SPECS";
344
- const CALL_RE = /TurboModuleRegistry\s*\.\s*(get|getEnforcing)\b/g;
345
- const NAMED_CALL_RE = /TurboModuleRegistry\s*\.\s*(get|getEnforcing)\s*(?:<[^()]*?>)?\s*\(\s*(['"])([^'"]+)\2/g;
346
- const NATIVE_MODULES_RE = /\bNativeModules\s*(?:\?\.|\.)\s*([A-Za-z_$][\w$]*)|\bNativeModules\s*(?:\?\.)?\s*\[\s*(['"])([^'"]+)\2\s*\]/g;
347
- /**
348
- * Comments describe lookups without performing them (NativeModules.js documents
349
- * `NativeModules.ModuleName`), so they are removed before matching. The line form
350
- * keeps `://` in URLs intact.
351
- */
352
- function stripComments(source) {
353
- return source.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:\\])\/\/.*$/gm, "$1");
354
- }
355
- function walk(dir, files) {
356
- let entries;
357
- try {
358
- entries = fs.readdirSync(dir, { withFileTypes: true });
359
- } catch {
360
- return;
361
- }
362
- for (const entry of entries) {
363
- if (SKIPPED_DIRS.has(entry.name)) continue;
364
- const full = path.join(dir, entry.name);
365
- if (entry.isDirectory()) walk(full, files);
366
- else if (entry.name.endsWith(".js")) files.push(full);
367
- }
368
- }
369
- const SPEC_RE = /\binterface\s+Spec\s+extends\s+TurboModule\s*\{/g;
370
- /**
371
- * The members of each `interface Spec extends TurboModule { ... }` in a source file:
372
- * the methods (and getConstants) the module's codegen spec declares, which are the
373
- * only properties its native object has on a device. Members are the names directly
374
- * inside the interface body; names nested in parameter or object types sit deeper
375
- * and are skipped.
376
- */
377
- function specMembers(source) {
378
- const members = /* @__PURE__ */ new Set();
379
- for (const match of source.matchAll(SPEC_RE)) {
380
- let depth = 1;
381
- let atMemberStart = true;
382
- for (let i = match.index + match[0].length; i < source.length && depth > 0; i++) {
383
- const c = source[i];
384
- if (c === "{" || c === "(" || c === "[") depth++;
385
- else if (c === "}" || c === ")" || c === "]") depth--;
386
- else if (depth === 1 && (c === ";" || c === "," || c === "\n")) atMemberStart = true;
387
- else if (depth === 1 && atMemberStart && !/\s/.test(c)) {
388
- atMemberStart = false;
389
- const member = /^(?:\+|-|readonly\s+)?([A-Za-z_$][\w$]*)\??\s*:/.exec(source.slice(i));
390
- if (member) members.add(member[1]);
391
- }
392
- }
393
- }
394
- return members;
395
- }
396
- /**
397
- * Every native module name React Native's own JavaScript requests, by lookup kind.
398
- * `unnamed` counts TurboModuleRegistry calls whose argument is not a string
399
- * literal; React Native's specs always pass a literal, and a test holds the
400
- * installed copy to that, so a change upstream cannot silently shrink the set.
401
- */
402
- function scanReactNativeModuleRequests(reactNativeRoot) {
403
- const files = [];
404
- for (const dir of REACT_NATIVE_SOURCE_DIRS) walk(path.join(reactNativeRoot, dir), files);
405
- const get = /* @__PURE__ */ new Set();
406
- const getEnforcing = /* @__PURE__ */ new Set();
407
- const nativeModules = /* @__PURE__ */ new Set();
408
- const specs = /* @__PURE__ */ new Map();
409
- let unnamed = 0;
410
- for (const file of files) {
411
- const raw = fs.readFileSync(file, "utf8");
412
- if (!raw.includes("TurboModuleRegistry") && !raw.includes("NativeModules")) continue;
413
- const source = stripComments(raw);
414
- let named = 0;
415
- const members = specMembers(source);
416
- for (const match of source.matchAll(NAMED_CALL_RE)) {
417
- (match[1] === "get" ? get : getEnforcing).add(match[3]);
418
- named++;
419
- if (members.size > 0) {
420
- const known = specs.get(match[3]) ?? /* @__PURE__ */ new Set();
421
- for (const member of members) known.add(member);
422
- specs.set(match[3], known);
423
- }
424
- }
425
- if (!file.replace(/\\/g, "/").endsWith("/Libraries/TurboModule/TurboModuleRegistry.js")) unnamed += (source.match(CALL_RE) || []).length - named;
426
- for (const match of source.matchAll(NATIVE_MODULES_RE)) nativeModules.add(match[1] ?? match[3]);
427
- }
428
- const sorted = (set) => [...set].sort();
429
- return {
430
- files: files.length,
431
- get: sorted(get),
432
- getEnforcing: sorted(getEnforcing),
433
- nativeModules: sorted(nativeModules),
434
- specs: Object.fromEntries([...specs.keys()].sort().map((name) => [name, sorted(specs.get(name))])),
435
- unnamed
436
- };
437
- }
438
- /** The installed React Native's package root, as `react-native` resolves from the project. */
439
- function reactNativeRootFor(projectRoot) {
440
- try {
441
- const req = createRequire(path.join(projectRoot, "package.json"));
442
- return path.dirname(fs.realpathSync(req.resolve("react-native/package.json")));
443
- } catch {
444
- return null;
445
- }
446
- }
447
- const memo = /* @__PURE__ */ new Map();
448
- /** The installed React Native's scan, memoized per React Native root. */
449
- function scanFor(projectRoot) {
450
- const root = reactNativeRootFor(projectRoot);
451
- if (root === null) return null;
452
- let scan = memo.get(root);
453
- if (!scan) {
454
- scan = scanReactNativeModuleRequests(root);
455
- memo.set(root, scan);
456
- }
457
- return scan;
458
- }
459
- /**
460
- * The module names React Native's JavaScript requests, plus the boundary's own,
461
- * sorted. Memoized per React Native root: the scan reads ~600 files (~60-80ms
462
- * measured on 0.78-0.87), and several Vitest projects in one run share a copy.
463
- */
464
- function knownNativeModulesFor(projectRoot) {
465
- const scan = scanFor(projectRoot);
466
- if (scan === null) return [...BOUNDARY_NATIVE_MODULES];
467
- return [.../* @__PURE__ */ new Set([
468
- ...scan.get,
469
- ...scan.getEnforcing,
470
- ...scan.nativeModules,
471
- ...BOUNDARY_NATIVE_MODULES
472
- ])].sort();
473
- }
474
- /** Each React Native module's spec members, by module name (see specMembers). */
475
- function nativeModuleSpecsFor(projectRoot) {
476
- return scanFor(projectRoot)?.specs ?? {};
477
- }
478
- //#endregion
479
- //#region src/native/apply.ts
480
- function nativeEngineConfig(setupFilePath, env, extensions, transformPkgs = [], hot, jsxTransform = { esbuild: { jsx: "automatic" } }, userPool, inlinePkgs = [], projectRoot = process.cwd(), userInlinesEverything = false, projectDirs = [], ownershipPolicy) {
38
+ // src/native/apply.ts
39
+ function nativeEngineConfig(setupFilePath, fields, extensions, transformPkgs = [], hot, jsxTransform = { esbuild: { jsx: "automatic" } }, userPool, inlinePkgs = [], projectRoot = process.cwd(), userInlinesEverything = false, projectDirs = [], ownershipPolicy) {
481
40
  const ownership = ownershipPolicy ?? createNativeOwnershipPolicy({
482
41
  projectRoot,
483
42
  explicitTransforms: transformPkgs,
@@ -486,15 +45,14 @@ function nativeEngineConfig(setupFilePath, env, extensions, transformPkgs = [],
486
45
  serverDepsInlineAll: userInlinesEverything
487
46
  });
488
47
  const nodeTransformed = ownership.nodeTransformPackages;
489
- const fullEnv = { ...env };
490
48
  const ownershipManifest = ownership.manifest();
491
- fullEnv.VITEST_NATIVE_OWNERSHIP = JSON.stringify(ownershipManifest);
492
- if (fullEnv.VITEST_NATIVE_DIAGNOSTICS === "true") for (const line of formatNativeOwnershipManifest(ownershipManifest)) {
49
+ fields.ownership = ownershipManifest;
50
+ if (fields.diagnostics) for (const line of formatNativeOwnershipManifest(ownershipManifest)) {
493
51
  const report = `[vitest-native] ownership: ${line}`;
494
52
  if (line.startsWith("WARNING:")) console.warn(report);
495
53
  else console.log(report);
496
54
  }
497
- if (nodeTransformed.length > 0) fullEnv.VITEST_NATIVE_TRANSFORM = JSON.stringify(nodeTransformed);
55
+ if (nodeTransformed.length > 0) fields.transform = [...nodeTransformed];
498
56
  return {
499
57
  ...jsxTransform,
500
58
  ssr: { resolve: {
@@ -524,7 +82,7 @@ function nativeEngineConfig(setupFilePath, env, extensions, transformPkgs = [],
524
82
  },
525
83
  test: {
526
84
  setupFiles: [setupFilePath],
527
- env: fullEnv,
85
+ env: {},
528
86
  ...hot ? {
529
87
  pool: hot.pool,
530
88
  isolate: false,
@@ -538,8 +96,7 @@ function nativeEngineConfig(setupFilePath, env, extensions, transformPkgs = [],
538
96
  }
539
97
  };
540
98
  }
541
- //#endregion
542
- //#region src/plugin.ts
99
+ // src/plugin.ts
543
100
  function uniqueExtensions(values) {
544
101
  const seen = /* @__PURE__ */ new Set();
545
102
  const result = [];
@@ -598,6 +155,36 @@ function testIncludeRoots(include, projectRoot) {
598
155
  return [...dirs];
599
156
  }
600
157
  /**
158
+ * The files `test.setupFiles` names, resolved as Vitest resolves them (from the run
159
+ * root: a package request first, then a path), in the spelling given and in the real
160
+ * path's spellings, since Vite reports a module by its real path.
161
+ *
162
+ * Vitest evaluates every setup file in Vite whatever `server.deps.external` says, so
163
+ * the ownership policy treats them as entries (see decideFile in native/ownership.mjs).
164
+ */
165
+ function setupEntryFiles(setupFiles, projectRoot) {
166
+ const list = Array.isArray(setupFiles) ? setupFiles : [setupFiles];
167
+ const req = createRequire(path.join(projectRoot, "package.json"));
168
+ const files = /* @__PURE__ */ new Set();
169
+ for (const entry of list) {
170
+ if (typeof entry !== "string" || entry === "") continue;
171
+ let file;
172
+ if (entry.startsWith("file:")) file = fileURLToPath(entry);
173
+ else if (path.isAbsolute(entry)) file = entry;
174
+ else try {
175
+ file = req.resolve(entry);
176
+ } catch {
177
+ file = path.resolve(projectRoot, entry);
178
+ }
179
+ files.add(path.resolve(file));
180
+ if (fs.existsSync(file)) {
181
+ files.add(fs.realpathSync(file));
182
+ files.add(fs.realpathSync.native(file));
183
+ }
184
+ }
185
+ return [...files];
186
+ }
187
+ /**
601
188
  * Where a glob stops being a literal path.
602
189
  *
603
190
  * `!`, `+` and `@` only introduce a pattern as part of an extglob — `@(a|b)` — and
@@ -706,19 +293,39 @@ function expoTsconfigPaths(projectRoot, userTsconfigPaths, viteMajor) {
706
293
  * Written to stderr: this is the plugin's only unconditional output, and stdout
707
294
  * must stay parseable for pipelines like `vitest --reporter=json > results.json`.
708
295
  */
709
- function printEngineBanner(engine, platform, projectRoot, hotRuntime = false) {
296
+ function printEngineBanner(engine, platform, projectRoot, presetNames, hotRuntime = false) {
710
297
  const g = globalThis;
711
298
  if (g.__vitest_native_banner_printed) return;
712
299
  g.__vitest_native_banner_printed = true;
300
+ const mocked = presetNames.length > 0 ? ` · mocked: ${presetNames.join(", ")}` : "";
713
301
  if (engine === "native") {
714
302
  const rn = resolvePackageVersion("react-native", projectRoot);
715
303
  const runtime = hotRuntime ? ", hot runtime" : "";
716
- console.error(`[vitest-native] engine: native — real react-native${rn ? `@${rn}` : ""} (platform ${platform}${runtime})`);
717
- } else console.error(`[vitest-native] engine: mock — React Native reimplementation, cross-checked against real RN (platform ${platform})`);
304
+ console.error(`[vitest-native] engine: native — real react-native${rn ? `@${rn}` : ""}${mocked} (platform ${platform}${runtime})`);
305
+ } else console.error(`[vitest-native] engine: mock — React Native reimplementation, cross-checked against real RN${mocked} (platform ${platform})`);
718
306
  }
719
- function getJsxTransformConfig(projectRoot) {
720
- const viteVersion = resolvePackageVersion("vite", projectRoot);
721
- return Number(viteVersion?.split(".")[0]) >= 8 ? { oxc: { jsx: { runtime: "automatic" } } } : { esbuild: { jsx: "automatic" } };
307
+ /**
308
+ * The presets a mock-engine worker applies, for the banner. An array is the list the
309
+ * workers are handed (the project context's `presetNames`). Otherwise each worker
310
+ * detects its own (setup.ts: every auto-detected preset not switched off), so this is
311
+ * a second computation of that list, not a read of it: both read AUTO_DETECT_PRESETS
312
+ * through presetForInstalled, from the same project root, and agree as long as the
313
+ * package resolves the same way from the main process and the worker. The native
314
+ * engine's banner prints the list its workers are handed.
315
+ */
316
+ function mockEnginePresetNames(listed, presetsOption, projectRoot) {
317
+ if (listed) return listed.map((p) => p.name);
318
+ const disabled = disabledPresetNames(presetsOption);
319
+ return autoDetectPresetNames(projectRoot, false).filter((n) => !disabled.has(n));
320
+ }
321
+ /** The major of a version string, or NaN. */
322
+ /** The unsupported-Expo-SDK warnings already printed in this process. */
323
+ const warnedExpoProblems = /* @__PURE__ */ new Set();
324
+ function majorOf(version) {
325
+ return Number(version?.replace(/^[^0-9]*/, "").split(".")[0]);
326
+ }
327
+ function getJsxTransformConfig(viteMajor) {
328
+ return viteMajor >= 8 ? { oxc: { jsx: { runtime: "automatic" } } } : { esbuild: { jsx: "automatic" } };
722
329
  }
723
330
  /**
724
331
  * The names React Native's index exports.
@@ -770,6 +377,35 @@ function parseReactNativeMembers(indexSource) {
770
377
  }));
771
378
  }
772
379
  /**
380
+ * Coverage of the files Node compiles (native/coverage-v8.mjs): `@vitest/coverage-v8`,
381
+ * told how to read them.
382
+ *
383
+ * Under the native engine, Node runs part of a project's own source: workspace packages
384
+ * written for React Native, and app source a test reaches through `require()`. V8 counts
385
+ * what ran, which for those files is Babel's output, while @vitest/coverage-v8 maps
386
+ * counts back through Vite's transform of the file. Vite does not own those files (the
387
+ * plugin refuses them, see transform below), so the provider fell back to parsing the
388
+ * original TypeScript, failed, and left the file out: "Failed to parse … Excluding it
389
+ * from coverage". The provider installed here is @vitest/coverage-v8 with that one step
390
+ * answered from Node's compiled output and its inline source map.
391
+ *
392
+ * Set on Vitest's resolved options, before Vitest loads the provider: coverage options
393
+ * belong to the root config, and a monorepo often configures this plugin only in its
394
+ * projects. Only `provider: 'v8'` (Vitest's default) is replaced; Istanbul and custom
395
+ * providers are left as configured. The test workers load the same @vitest/coverage-v8
396
+ * runtime either way.
397
+ */
398
+ function useNativeCoverageProvider(coverage) {
399
+ if (!coverage) return false;
400
+ const dir = path.dirname(fileURLToPath(import.meta.url));
401
+ const module = path.resolve(dir, "native/coverage-v8.mjs");
402
+ if (coverage.provider === "v8" && coverage.enabled === true) {
403
+ coverage.provider = "custom";
404
+ coverage.customProviderModule = module;
405
+ }
406
+ return coverage.enabled === true && coverage.customProviderModule === module;
407
+ }
408
+ /**
773
409
  * The Metro asset-module generator (native/assets.mjs). It ships as runtime `.mjs`
774
410
  * for the Node hooks, so — like the registry builder below — it is reached through a
775
411
  * computed dynamic import: a static specifier would bundle a second copy into the
@@ -818,6 +454,47 @@ async function loadProjectMetroProfile(options) {
818
454
  function asCompatibleViteConfig(config) {
819
455
  return config;
820
456
  }
457
+ /** Fields of every context this process wrote, by reference. */
458
+ const writtenContexts = /* @__PURE__ */ new Map();
459
+ /**
460
+ * The worker environment for one project: its fields become one context file, and
461
+ * workers get only the reference. `env` (the memory plan, read back from the config)
462
+ * passes through.
463
+ */
464
+ function withProjectContext(fields, env, projectRoot) {
465
+ const ref = writeProjectContext(fields, cacheRootFor(projectRoot));
466
+ writtenContexts.set(ref, fields);
467
+ return {
468
+ ...env,
469
+ [CONTEXT_ENV]: ref
470
+ };
471
+ }
472
+ /** The same context with `changes` applied, written as its own file. */
473
+ function amendProjectContext(ref, changes, projectRoot) {
474
+ const current = writtenContexts.get(ref) ?? projectContext(ref);
475
+ if (!current) throw new VitestNativeError("CONTEXT_INVALID", `no project context at ${ref}`);
476
+ const fields = {
477
+ ...current,
478
+ ...changes
479
+ };
480
+ const next = writeProjectContext(fields, cacheRootFor(projectRoot));
481
+ writtenContexts.set(next, fields);
482
+ return next;
483
+ }
484
+ /**
485
+ * Settings that were `VITEST_NATIVE_*` environment variables before the project
486
+ * context. Set by hand in the shell or `test.env`, they no longer reach the workers,
487
+ * so the plugin says so once.
488
+ */
489
+ const RETIRED_VARIABLES = new Set("PLATFORM DIAGNOSTICS PROJECT_ROOT RN_VERSION TRANSFORM SOURCE_EXTS ASSET_EXTS HOT_PRESERVE_GLOBALS RN_REGISTRY OWNERSHIP PROJECT_DIRS REQUIRE_ALIASES REQUIRE_ALIASES_SKIPPED PRESET_NAMES PRESET_CONFIG PRESET_EXPORTS PRESET_MODULES PRESET_DISABLED MOCKS RN_NATIVE_MODULES RN_NATIVE_MODULE_SPECS NATIVE_MODULES".split(" ").map((name) => `VITEST_NATIVE_${name}`));
490
+ let warnedRetired = false;
491
+ function warnRetiredVariables(...sources) {
492
+ if (warnedRetired) return;
493
+ const found = [...new Set(sources.flatMap((env) => Object.keys(env ?? {}).filter((k) => RETIRED_VARIABLES.has(k))))];
494
+ if (found.length === 0) return;
495
+ warnedRetired = true;
496
+ console.warn(`[vitest-native] ${found.join(", ")} ${found.length === 1 ? "is" : "are"} set but no longer read: workers take their configuration from reactNative()'s options, through the project context. Set the matching option instead.`);
497
+ }
821
498
  /**
822
499
  * Synchronously resolve the export-names of presets whose package is installed.
823
500
  * Used by the native-engine config path (which can't await the factory imports)
@@ -1115,20 +792,29 @@ function selectPresets(option, root) {
1115
792
  if (Array.isArray(option)) {
1116
793
  const listed = [];
1117
794
  const modulePaths = [];
1118
- for (const entry of option) if (typeof entry === "string") modulePaths.push(resolvePresetModule(entry, root));
1119
- else listed.push(listedBuiltInPreset(entry));
795
+ const moduleSpecs = [];
796
+ for (const entry of option) if (typeof entry === "string") {
797
+ modulePaths.push(resolvePresetModule(entry, root));
798
+ moduleSpecs.push(entry);
799
+ } else listed.push(listedBuiltInPreset(entry));
1120
800
  return {
1121
801
  listed,
1122
- modulePaths
802
+ modulePaths,
803
+ moduleSpecs
1123
804
  };
1124
805
  }
1125
806
  const modulePaths = [];
807
+ const moduleSpecs = [];
1126
808
  if (option !== null && typeof option === "object") {
1127
- for (const [key, enabled] of Object.entries(option)) if (enabled === true && !Object.hasOwn(PRESET_MODULES, key)) modulePaths.push(resolvePresetModule(key, root));
809
+ for (const [key, enabled] of Object.entries(option)) if (enabled === true && !Object.hasOwn(PRESET_MODULES, key)) {
810
+ modulePaths.push(resolvePresetModule(key, root));
811
+ moduleSpecs.push(key);
812
+ }
1128
813
  }
1129
814
  return {
1130
815
  listed: null,
1131
- modulePaths
816
+ modulePaths,
817
+ moduleSpecs
1132
818
  };
1133
819
  }
1134
820
  /**
@@ -1305,6 +991,17 @@ function prependSetupFile(userConfig, contributed) {
1305
991
  userTest.setupFiles = [...ours, ...userFiles.filter((f) => !ours.includes(f))];
1306
992
  contributed.setupFiles = [];
1307
993
  }
994
+ function sameDirectory(a, b) {
995
+ if (a === b) return true;
996
+ const real = (p) => {
997
+ try {
998
+ return fs.realpathSync.native(p);
999
+ } catch {
1000
+ return path.resolve(p);
1001
+ }
1002
+ };
1003
+ return real(a) === real(b);
1004
+ }
1308
1005
  function hasSetupFile(setupFiles, file) {
1309
1006
  const real = (f) => {
1310
1007
  try {
@@ -1321,11 +1018,11 @@ function hasSetupFile(setupFiles, file) {
1321
1018
  * Vitest schedules projects that share a `sequence.groupOrder` (0 unless set) as one
1322
1019
  * group, and throws when they resolve to different `maxWorkers` ("Projects … have
1323
1020
  * different 'maxWorkers' but same 'sequence.groupOrder'", groupSpecs in Vitest 4 and
1324
- * 5). The hot runtime's memory plan caps workers (at most four), while a project
1325
- * beside it gets Vitest's default of one fewer than the CPUs, so a native project next
1326
- * to a mock or non-React-Native project failed on any machine with more than five
1327
- * cores. Mirrors Vitest's resolveMaxWorkers and its grouping, including the exemption
1328
- * for a single-worker isolated project in the default group.
1021
+ * 5). The hot runtime's memory plan caps workers (at most four unless the user set the
1022
+ * count), while a project beside it gets Vitest's default of one fewer than the CPUs,
1023
+ * so a native project next to a mock or non-React-Native project failed on any machine
1024
+ * with more than five cores. Mirrors Vitest's resolveMaxWorkers and its grouping,
1025
+ * including the exemption for a single-worker isolated project in the default group.
1329
1026
  */
1330
1027
  function sharedGroupConflict(self, others, root, cpus) {
1331
1028
  const order = (p) => Number(p.config.sequence?.groupOrder ?? 0);
@@ -1344,7 +1041,7 @@ function vmPoolUnsupported(pool) {
1344
1041
  return new VitestNativeError("UNSUPPORTED_POOL", `engine:'native' cannot run on the '${pool}' pool. React Native is loaded through Node's module hooks, which a VM pool's context does not use — React Native fails to resolve its platform files there. Use 'threads' (the default) or 'forks', or switch to engine:'mock', which needs no hooks.`);
1345
1042
  }
1346
1043
  function hotRuntimeOverridden(reason) {
1347
- return new VitestNativeError("HOT_RUNTIME_OVERRIDDEN", `hotRuntime was requested, but ${reason}, which the hot runtime cannot honour. Remove that setting, or use hotRuntime:'auto' to fall back to it automatically or hotRuntime:false.`);
1044
+ return new VitestNativeError("HOT_RUNTIME_OVERRIDDEN", `hotRuntime was requested, but ${reason}, which the hot runtime cannot honour. Remove that setting, or use hotRuntime:'auto' (or add mode:'auto' to the options object, keeping its recycling options) to fall back to it automatically, or hotRuntime:false.`);
1348
1045
  }
1349
1046
  /**
1350
1047
  * The worker count Vitest would have used had the hot runtime not capped it: the
@@ -1366,6 +1063,63 @@ function workerVitestMismatchReason(workerEntry, projectRoot) {
1366
1063
  const mismatch = workerVitestMismatch(workerEntry, projectRoot);
1367
1064
  return mismatch ? `its worker would load vitest@${mismatch.worker.version} while this run uses vitest@${mismatch.project.version}` : null;
1368
1065
  }
1066
+ function warnWorkersCapped(requestedWorkers, plan) {
1067
+ console.warn(`[vitest-native] hotRuntime capped maxWorkers from ${requestedWorkers} to ${plan.maxWorkers} for the ${plan.source} memory budget. Set diagnostics:true to see the full envelope.`);
1068
+ }
1069
+ let workerDecisionPrinted = false;
1070
+ /**
1071
+ * The hot runtime's worker count, printed with the engine banner on every run, not only
1072
+ * with diagnostics: the number a user tunes `maxWorkers` against or quotes in a report.
1073
+ * Printed where the count is final (configureVitest, after a --maxWorkers re-plan).
1074
+ */
1075
+ function printWorkerDecision(line) {
1076
+ if (workerDecisionPrinted) return;
1077
+ workerDecisionPrinted = true;
1078
+ console.error(`[vitest-native] ${line}`);
1079
+ }
1080
+ function printHotMemoryPlan(lines) {
1081
+ for (const line of lines) console.log(`[vitest-native] memory: ${line}`);
1082
+ }
1083
+ /**
1084
+ * Rebuild the hot memory plan for the worker count Vitest resolved, when it is not the
1085
+ * count config() planned for. Vitest applies `--maxWorkers` and `VITEST_MAX_WORKERS`
1086
+ * over the `maxWorkers` every config hook returned (resolveConfig in Vitest 4.1 and 5;
1087
+ * Vitest 5 also copies `--maxWorkers` into each project), and config() never sees the
1088
+ * environment variable: `VITEST_MAX_WORKERS=10` ran ten workers on a heap threshold
1089
+ * and plan sized for four. The count is the user's explicit choice, so memory
1090
+ * admission alone bounds it, as it does for one in the config file. Sets the
1091
+ * project's `maxWorkers` to the admitted count and returns the new plan, which takes
1092
+ * effect through applyHotMemoryPlan; returns undefined when the plan already fits.
1093
+ * Vitest 5 hands config() `--maxWorkers` too, so a memory-capped request comes back
1094
+ * here as the same plan config() built and warned about; that is not a new plan.
1095
+ */
1096
+ function replanForVitestWorkers(memory, projectConfig) {
1097
+ const workers = projectConfig.maxWorkers;
1098
+ if (typeof workers !== "number" || workers === memory.plan.maxWorkers) return void 0;
1099
+ const plan = memory.replan(workers);
1100
+ projectConfig.maxWorkers = plan.maxWorkers;
1101
+ return plan.maxWorkers === memory.plan.maxWorkers && plan.requestedWorkers === memory.plan.requestedWorkers ? void 0 : plan;
1102
+ }
1103
+ /**
1104
+ * Hand a rebuilt plan to everything that consumes it. The hot pool reads its options as
1105
+ * Vitest creates each worker, and Vitest passes `env` to workers as it starts them;
1106
+ * both happen when the run starts, after every configureVitest hook has returned.
1107
+ */
1108
+ function applyHotMemoryPlan(memory, plan, projectConfig, diagnostics) {
1109
+ memory.plan = plan;
1110
+ memory.poolOptions.memoryPlan = plan;
1111
+ if (!memory.userMemoryLimit) memory.poolOptions.memoryLimit = plan.workerHeapLimit;
1112
+ projectConfig.env ??= {};
1113
+ projectConfig.env.VITEST_NATIVE_MEMORY_PLAN = JSON.stringify({
1114
+ ...plan,
1115
+ enforced: true
1116
+ });
1117
+ if (plan.maxWorkers < plan.requestedWorkers) warnWorkersCapped(plan.requestedWorkers, plan);
1118
+ if (diagnostics) {
1119
+ console.log(`[vitest-native] memory: plan rebuilt for the ${plan.requestedWorkers} workers Vitest resolved after config (--maxWorkers or VITEST_MAX_WORKERS)`);
1120
+ printHotMemoryPlan(memory.formatPlan(plan));
1121
+ }
1122
+ }
1369
1123
  function reactNative(options) {
1370
1124
  let jestMockTransformPresent = true;
1371
1125
  const hotSelections = /* @__PURE__ */ new Map();
@@ -1375,6 +1129,8 @@ function reactNative(options) {
1375
1129
  const cacheKeys = /* @__PURE__ */ new Map();
1376
1130
  let warnedMissingJestMockTransform = false;
1377
1131
  let warnedTsconfigPaths = false;
1132
+ let hostViteVersion = null;
1133
+ let hostViteSource = "";
1378
1134
  const warnIfJestMockUnhoisted = (code, id) => {
1379
1135
  if (jestMockTransformPresent || warnedMissingJestMockTransform) return;
1380
1136
  if (/[\\/]node_modules[\\/]/.test(id) || containsPath(ownPackageDir, id)) return;
@@ -1412,19 +1168,10 @@ function reactNative(options) {
1412
1168
  if (cached !== void 0) return cached;
1413
1169
  const importerDir = path.dirname(importer);
1414
1170
  const absolute = path.resolve(importerDir, source);
1415
- for (const ext of extensions) {
1416
- const candidate = absolute + ext;
1417
- if (existsExact(candidate)) {
1418
- resolveCache.set(cacheKey, candidate);
1419
- return candidate;
1420
- }
1421
- }
1422
- for (const ext of extensions) {
1423
- const candidate = path.join(absolute, `index${ext}`);
1424
- if (existsExact(candidate)) {
1425
- resolveCache.set(cacheKey, candidate);
1426
- return candidate;
1427
- }
1171
+ const candidate = firstExact(absolute, extensions) ?? firstExact(path.join(absolute, "index"), extensions);
1172
+ if (candidate !== null) {
1173
+ resolveCache.set(cacheKey, candidate);
1174
+ return candidate;
1428
1175
  }
1429
1176
  resolveCache.set(cacheKey, void 0);
1430
1177
  }
@@ -1438,13 +1185,7 @@ function reactNative(options) {
1438
1185
  let result = null;
1439
1186
  try {
1440
1187
  const req = createRequire(from);
1441
- result = alignLegacyFieldsWithNode(source, (name) => {
1442
- try {
1443
- return path.dirname(req.resolve(`${name}/package.json`));
1444
- } catch {
1445
- return null;
1446
- }
1447
- }, (dir) => {
1188
+ result = alignLegacyFieldsWithNode(source, (name) => packageDirOf(name, path.dirname(from)), (dir) => {
1448
1189
  try {
1449
1190
  return JSON.parse(fs.readFileSync(path.join(dir, "package.json"), "utf8"));
1450
1191
  } catch {
@@ -1484,8 +1225,8 @@ function reactNative(options) {
1484
1225
  const hotRuntimeExplicit = options?.hotRuntime !== void 0;
1485
1226
  const hotRuntimeOpt = options?.hotRuntime ?? false;
1486
1227
  const hotRuntimeRequested = hotRuntimeOpt !== false;
1487
- const hotRuntimeAuto = hotRuntimeOpt === "auto";
1488
1228
  const hotRecycle = typeof hotRuntimeOpt === "object" ? hotRuntimeOpt : {};
1229
+ const hotRuntimeAuto = hotRuntimeOpt === "auto" || hotRecycle.mode === "auto";
1489
1230
  let engine = requestedEngine === "native" ? "native" : "mock";
1490
1231
  let sourceExts = [
1491
1232
  "js",
@@ -1501,12 +1242,35 @@ function reactNative(options) {
1501
1242
  if (!assetPattern) return void 0;
1502
1243
  if (source.endsWith(".json") || assetPattern.test(source) || isUtilitySubpath(source)) return;
1503
1244
  const pkg = packageNameOf(source);
1504
- if (pkg !== source && presetModules.has(pkg)) return `\0virtual:preset:${source}`;
1245
+ if (pkg === source || !presetModules.has(pkg)) return void 0;
1246
+ if (engine === "native" && unexportedPresetSubpath(source) !== null) return void 0;
1247
+ return `\0virtual:preset:${source}`;
1248
+ };
1249
+ const unexportedPresetSubpath = (source) => {
1250
+ const pkg = packageNameOf(source);
1251
+ if (pkg === source || !presetModules.has(pkg) || presetModules.has(source)) return null;
1252
+ if (source.endsWith(".json") || assetPattern?.test(source) || isUtilitySubpath(source)) return null;
1253
+ const leaf = subpathLeafOf(source);
1254
+ return leaf !== null && (presetExportNames.get(pkg) ?? []).includes(leaf) ? null : pkg;
1505
1255
  };
1506
1256
  const pluginDefinition = {
1507
1257
  name: "vitest-native",
1508
1258
  enforce: "pre",
1259
+ api: {
1260
+ nativeOwnership: () => nativeOwnership,
1261
+ nodeCoverageTarget: (file) => {
1262
+ if (engine !== "native" || nativeOwnership === null) return null;
1263
+ if (nativeOwnership.decideFile(file).owner !== "node") return null;
1264
+ return {
1265
+ root: alignRoot,
1266
+ platform
1267
+ };
1268
+ }
1269
+ },
1509
1270
  async config(userConfig, _env) {
1271
+ const hostVite = await runningVite(this);
1272
+ hostViteVersion = hostVite?.version ?? null;
1273
+ hostViteSource = hostVite?.source ?? "";
1510
1274
  const resolvedRoot = vitestRootOf(userConfig);
1511
1275
  alignRoot = resolvedRoot;
1512
1276
  const metroOption = options?.metroConfig;
@@ -1534,60 +1298,78 @@ function reactNative(options) {
1534
1298
  console.log(`[vitest-native] Metro resolverMainFields=${metro.profile.resolverMainFields.join(",")} and conditions=${metro.profile.conditionNames.join(",")} are observational; module ownership keeps the package-format policy authoritative.`);
1535
1299
  }
1536
1300
  }
1537
- const jsxTransform = getJsxTransformConfig(resolvedRoot);
1301
+ const jsxTransform = getJsxTransformConfig(majorOf(hostViteVersion));
1538
1302
  const decision = detectEngine(requestedEngine, resolvedRoot);
1539
1303
  engine = decision.engine;
1540
1304
  if (engine === "native" && !decision.nativeAvailable) throw new VitestNativeError("ENGINE_REQUIRES_BABEL", `engine:'native' requires react-native, a React Native Babel preset ('@react-native/babel-preset', or Expo's from SDK 56), and '@babel/core' to resolve from ${resolvedRoot} — missing: ${decision.missing.join(", ")}. React Native and Expo projects ship all three by default. Install what's missing (react-native as a dependency, the toolchain as devDependencies), or set engine:'mock' to run without a React Native install.`);
1541
1305
  if (decision.notice) console.warn(decision.notice);
1542
- if (engine !== "native") printEngineBanner(engine, platform, resolvedRoot);
1543
- const env = {
1544
- VITEST_NATIVE_PLATFORM: platform,
1545
- VITEST_NATIVE_DIAGNOSTICS: String(diagnostics),
1546
- VITEST_NATIVE_PROJECT_ROOT: resolvedRoot
1306
+ warnRetiredVariables(process.env, userConfig.test?.env);
1307
+ const fields = {
1308
+ platform,
1309
+ diagnostics,
1310
+ projectRoot: resolvedRoot
1547
1311
  };
1548
- const requireAliases = serializableAliases(userConfig.resolve?.alias, resolvedRoot);
1312
+ const env = {};
1313
+ const userAlias = userConfig.resolve?.alias;
1314
+ const requireAliases = serializableAliases(userAlias, resolvedRoot);
1315
+ const aliasTargets = aliasReachedPaths(userAlias, resolvedRoot);
1549
1316
  const userTsconfigPaths = userConfig.resolve?.tsconfigPaths;
1550
- const viteMajorForPaths = Number(resolvePackageVersion("vite", resolvedRoot)?.split(".")[0]);
1551
- if (userTsconfigPaths === true || expoTsconfigPaths(resolvedRoot, userTsconfigPaths, viteMajorForPaths) === "enable") requireAliases.entries.push(...tsconfigPathAliases(resolvedRoot).entries);
1552
- if (requireAliases.entries.length > 0) env.VITEST_NATIVE_REQUIRE_ALIASES = JSON.stringify(requireAliases.entries);
1553
- if (requireAliases.skipped.length > 0) env.VITEST_NATIVE_REQUIRE_ALIASES_SKIPPED = JSON.stringify(requireAliases.skipped);
1317
+ const viteMajorForPaths = majorOf(hostViteVersion);
1318
+ if (userTsconfigPaths === true || expoTsconfigPaths(resolvedRoot, userTsconfigPaths, viteMajorForPaths) === "enable") {
1319
+ const pathAliases = tsconfigPathAliases(resolvedRoot).entries;
1320
+ requireAliases.entries.push(...pathAliases);
1321
+ aliasTargets.push(...pathAliases.map(([, target]) => target).filter((target) => path.isAbsolute(target)));
1322
+ }
1323
+ if (requireAliases.entries.length > 0) fields.requireAliases = requireAliases.entries;
1324
+ if (requireAliases.skipped.length > 0) fields.requireAliasesSkipped = requireAliases.skipped;
1554
1325
  const reactNativeVersion = resolvePackageVersion("react-native", resolvedRoot);
1555
- if (reactNativeVersion) env.VITEST_NATIVE_RN_VERSION = reactNativeVersion;
1326
+ if (reactNativeVersion) fields.reactNativeVersion = reactNativeVersion;
1556
1327
  if (engine === "native") {
1557
- env[KNOWN_NATIVE_MODULES_ENV] = JSON.stringify(knownNativeModulesFor(resolvedRoot));
1558
- env[NATIVE_MODULE_SPECS_ENV] = JSON.stringify(nativeModuleSpecsFor(resolvedRoot));
1559
- if (options?.nativeModules === "permissive") env[PERMISSIVE_NATIVE_MODULES_ENV] = "permissive";
1328
+ fields.knownNativeModules = knownNativeModulesFor(resolvedRoot);
1329
+ fields.nativeModuleSpecs = nativeModuleSpecsFor(resolvedRoot);
1330
+ if (options?.nativeModules === "permissive") fields.nativeModules = "permissive";
1331
+ fields.expoSdks = [SUPPORTED_EXPO_SDKS.minimum, SUPPORTED_EXPO_SDKS.maximum];
1560
1332
  }
1561
- env.VITEST_NATIVE_ASSET_EXTS = JSON.stringify(assetExtList);
1562
- if (metroOption === true || typeof metroOption === "object") env.VITEST_NATIVE_SOURCE_EXTS = JSON.stringify(sourceExts);
1563
- if (hotRuntimeRequested && hotRecycle.preserveGlobals?.length) env.VITEST_NATIVE_HOT_PRESERVE_GLOBALS = JSON.stringify(hotRecycle.preserveGlobals);
1564
- if (hotRuntimeRequested && hotRecycle.esmGeneration === false) env.VITEST_NATIVE_HOT_ESM_GEN = "0";
1333
+ fields.assetExts = assetExtList;
1334
+ if (metroOption === true || typeof metroOption === "object") fields.sourceExts = sourceExts;
1335
+ if (hotRuntimeRequested && hotRecycle.preserveGlobals?.length) fields.hotPreserveGlobals = hotRecycle.preserveGlobals;
1336
+ if (hotRuntimeRequested && hotRecycle.esmGeneration === false) fields.hotEsmGeneration = false;
1337
+ const userDeps = userConfig.test?.deps;
1338
+ if (hotRuntimeRequested && userDeps?.interopDefault === false) fields.hotReleaseGenerations = false;
1565
1339
  if (engine === "native") {
1566
1340
  if (options?.mocks && Object.keys(options.mocks).length > 0) throw new VitestNativeError("MOCKS_REQUIRE_MOCK_ENGINE", "The \"mocks\" option is only supported by engine:'mock'. The native engine runs the real react-native module and cannot safely merge arbitrary exports into it. Use vi.mock() in a setup file, mockNativeModule() for native modules, or set engine:'mock'.");
1567
1341
  const disabledNative = disabledPresetNames(options?.presets);
1568
1342
  const selection = selectPresets(options?.presets, resolvedRoot);
1569
1343
  const nativePresetNames = selection.listed ? selection.listed.map((p) => p.name) : autoDetectPresetNames(resolvedRoot, diagnostics).filter((n) => !disabledNative.has(n) && autoDetectedPresetApplies(n, "native", options?.presets));
1570
- if (nativePresetNames.length > 0) env.VITEST_NATIVE_PRESET_NAMES = JSON.stringify(nativePresetNames);
1571
- if (selection.modulePaths.length > 0) env.VITEST_NATIVE_PRESET_MODULES = JSON.stringify(selection.modulePaths);
1344
+ if (nativePresetNames.length > 0) fields.presetNames = nativePresetNames;
1345
+ if (selection.modulePaths.length > 0) fields.presetModules = selection.modulePaths;
1572
1346
  if (selection.listed) {
1573
1347
  const presetConfig = {};
1574
1348
  for (const p of selection.listed) if (p.config && Object.keys(p.config).length > 0) presetConfig[p.name] = p.config;
1575
- if (Object.keys(presetConfig).length > 0) env.VITEST_NATIVE_PRESET_CONFIG = JSON.stringify(presetConfig);
1349
+ if (Object.keys(presetConfig).length > 0) fields.presetConfig = presetConfig;
1576
1350
  }
1577
1351
  const includeRoots = testIncludeRoots(userConfig.test?.include, resolvedRoot);
1578
1352
  const userInline = userConfig.test?.server?.deps?.inline;
1579
1353
  const userInlinesEverything = userInline === true;
1580
- const ecosystem = detectEcosystemPackages([resolvedRoot, ...includeRoots], transformPkgs, includeRoots, neverTransform, nativePresetNames);
1581
- const linkedDetectedDirs = ecosystem.map((name) => packageDirOf(name, resolvedRoot)).filter((dir) => dir !== null && !/[\\/]node_modules[\\/]/.test(dir));
1354
+ const dirOf = memoizePackageDirOf();
1355
+ const ecosystem = detectEcosystemPackages([resolvedRoot, ...includeRoots], transformPkgs, includeRoots, neverTransform, nativePresetNames, memoizePackageDirOf(dependencyDirOf), {
1356
+ reachedPaths: aliasTargets,
1357
+ onReachedUndeclared: (name, dir) => {
1358
+ if (diagnostics) console.log(`[vitest-native] ${name} (${dir}) is reached through an alias (resolve.alias or tsconfig paths) but is not a dependency of this package. Its installed React Native dependencies are compiled as if it were declared; declaring it makes the dependency explicit.`);
1359
+ }
1360
+ });
1361
+ const linkedDetectedDirs = ecosystem.map((name) => dirOf(name, resolvedRoot)).filter((dir) => dir !== null && !/[\\/]node_modules[\\/]/.test(dir));
1582
1362
  const projectDirs = [...new Set([resolvedRoot, ...includeRoots].map((dir) => nearestPackageDir(dir)).filter((dir) => dir !== null))].filter((dir) => !linkedDetectedDirs.some((detected) => containsPath(dir, detected)));
1583
- if (projectDirs.length > 0) env.VITEST_NATIVE_PROJECT_DIRS = JSON.stringify(projectDirs);
1363
+ if (projectDirs.length > 0) fields.projectDirs = projectDirs;
1584
1364
  nativeOwnership = createNativeOwnershipPolicy({
1585
1365
  projectRoot: resolvedRoot,
1586
1366
  explicitTransforms: transformPkgs,
1587
1367
  ecosystemPackages: ecosystem,
1588
1368
  runtimeTransformAugmentations: nativePresetNames.length > 0 ? ["preset-pass-through-modules"] : [],
1589
1369
  projectDirs,
1590
- serverDepsInlineAll: userInlinesEverything
1370
+ entryFiles: setupEntryFiles(userConfig.test?.setupFiles, resolvedRoot),
1371
+ serverDepsInlineAll: userInlinesEverything,
1372
+ packageDirOf: dirOf
1591
1373
  });
1592
1374
  assertInlineOwnership(userInline);
1593
1375
  const userTest = userConfig.test;
@@ -1596,19 +1378,22 @@ function reactNative(options) {
1596
1378
  nativeRoots.add(vitestRootOf(userConfig));
1597
1379
  let hotMemory;
1598
1380
  if (hotRuntimeRequested) {
1599
- const { createHotMemoryPlan, formatHotMemoryPlan, resolveRequestedWorkers } = await import("./memory-FYbP0_gg.mjs").then((n) => n.r);
1381
+ const { createHotMemoryPlan, formatHotMemoryPlan, formatHotWorkerDecision, resolveRequestedWorkers } = await import("./memory-Couw0Esx.mjs").then((n) => n.r);
1600
1382
  const requestedWorkers = resolveRequestedWorkers(userTest?.maxWorkers, { fileParallelism: userTest?.fileParallelism });
1601
- const plan = createHotMemoryPlan({ requestedWorkers });
1383
+ const plan = createHotMemoryPlan({
1384
+ requestedWorkers,
1385
+ explicitWorkers: userTest?.maxWorkers != null
1386
+ });
1602
1387
  const allowUnboundedMemory = hotRecycle.allowUnboundedMemory === true;
1603
1388
  const configConflict = hotAutoConfigDeclineReason(userPool, userTest?.isolate);
1604
1389
  if (!hotRuntimeAuto && configConflict !== null) throw hotRuntimeOverridden(configConflict);
1605
1390
  const autoDeclineReason = hotRuntimeAuto ? configConflict ?? workerVitestMismatchReason(nativeWorkerPath, resolvedRoot) ?? (plan.maxWorkers < 2 ? `the ${plan.source} memory/scheduler plan selects only one unrecyclable worker` : null) : null;
1606
1391
  if (autoDeclineReason !== null) {
1607
- if (hotRuntimeExplicit || diagnostics) console.warn(`[vitest-native] hotRuntime:'auto' kept default isolation: ${autoDeclineReason}.`);
1608
- } else if (!allowUnboundedMemory && plan.maxWorkers < 2) throw new VitestNativeError("HOT_MEMORY_UNBOUNDED", `hotRuntime cannot enforce its memory budget with one worker because Vitest batches every file into one unrecyclable task. The effective ${plan.source} memory ceiling admits ${plan.admittedWorkers} worker, or this config explicitly selects one. Use hotRuntime:false, provide enough memory for at least two workers, or explicitly accept unbounded growth with hotRuntime:{ allowUnboundedMemory:true }.`);
1609
- if (autoDeclineReason === null && (hotRuntimeExplicit || diagnostics) && !allowUnboundedMemory && userTest?.maxWorkers != null && plan.maxWorkers < requestedWorkers) console.warn(`[vitest-native] hotRuntime capped maxWorkers from ${requestedWorkers} to ${plan.maxWorkers} for the ${plan.source} memory budget. Set diagnostics:true to see the full envelope.`);
1392
+ if (hotRuntimeExplicit || diagnostics) console.warn(`[vitest-native] hotRuntime${hotRuntimeOpt === "auto" ? ":'auto'" : " mode:'auto'"} kept default isolation: ${autoDeclineReason}.`);
1393
+ } else if (!allowUnboundedMemory && plan.maxWorkers < 2) throw new VitestNativeError("HOT_MEMORY_UNBOUNDED", "hotRuntime cannot enforce its memory budget with one worker because Vitest batches every file into one unrecyclable task. " + (plan.admittedWorkers < 2 ? `The effective ${plan.source} memory ceiling admits only one worker. ` : `This config selects one worker (maxWorkers or fileParallelism). `) + "Use hotRuntime:'auto' (or mode:'auto' in the options object) to fall back to per-file isolation here, hotRuntime:false, provide enough memory for at least two workers, or explicitly accept unbounded growth with hotRuntime:{ allowUnboundedMemory:true }.");
1394
+ const capWarning = autoDeclineReason === null && !allowUnboundedMemory && userTest?.maxWorkers != null && plan.maxWorkers < requestedWorkers;
1610
1395
  if (autoDeclineReason === null && diagnostics) {
1611
- for (const line of formatHotMemoryPlan(plan)) console.log(`[vitest-native] memory: ${line}`);
1396
+ printHotMemoryPlan(formatHotMemoryPlan(plan));
1612
1397
  if (allowUnboundedMemory) console.warn("[vitest-native] memory: allowUnboundedMemory:true disables the automatic worker cap and process-RSS enforcement.");
1613
1398
  }
1614
1399
  if (autoDeclineReason === null) {
@@ -1619,7 +1404,14 @@ function reactNative(options) {
1619
1404
  hotMemory = {
1620
1405
  plan,
1621
1406
  memoryLimit: hotRecycle.memoryLimit ?? plan.workerHeapLimit,
1622
- allowUnboundedMemory
1407
+ allowUnboundedMemory,
1408
+ replan: (count) => createHotMemoryPlan({
1409
+ requestedWorkers: count,
1410
+ explicitWorkers: true
1411
+ }),
1412
+ formatPlan: formatHotMemoryPlan,
1413
+ formatDecision: formatHotWorkerDecision,
1414
+ capWarning
1623
1415
  };
1624
1416
  }
1625
1417
  }
@@ -1631,42 +1423,56 @@ function reactNative(options) {
1631
1423
  sourceExts,
1632
1424
  diagnostics
1633
1425
  });
1634
- if (registryFile) env.VITEST_NATIVE_RN_REGISTRY = registryFile;
1426
+ if (registryFile) fields.registry = registryFile;
1635
1427
  let hot;
1428
+ let hotPoolOptions;
1636
1429
  if (hotMemory) {
1637
- const { nativePool } = await import("./pool-DjpOjOf3.mjs");
1430
+ const { nativePool } = await import("./pool-CFSpNfyw.mjs");
1431
+ hotPoolOptions = {
1432
+ workerEntry: nativeWorkerPath,
1433
+ projectRoot: resolvedRoot,
1434
+ recycleAfterFiles: hotRecycle.recycleAfterFiles,
1435
+ memoryLimit: hotMemory.memoryLimit,
1436
+ memoryPlan: hotMemory.plan,
1437
+ allowUnboundedMemory: hotMemory.allowUnboundedMemory,
1438
+ diagnostics
1439
+ };
1638
1440
  hot = {
1639
- pool: nativePool({
1640
- workerEntry: nativeWorkerPath,
1641
- projectRoot: resolvedRoot,
1642
- recycleAfterFiles: hotRecycle.recycleAfterFiles,
1643
- memoryLimit: hotMemory.memoryLimit,
1644
- memoryPlan: hotMemory.plan,
1645
- allowUnboundedMemory: hotMemory.allowUnboundedMemory,
1646
- diagnostics
1647
- }),
1441
+ pool: nativePool(hotPoolOptions),
1648
1442
  runnerPath: nativeRunnerPath,
1649
1443
  maxWorkers: hotMemory.allowUnboundedMemory ? void 0 : hotMemory.plan.maxWorkers
1650
1444
  };
1651
1445
  }
1652
- printEngineBanner(engine, platform, resolvedRoot, hot !== void 0);
1446
+ printEngineBanner(engine, platform, resolvedRoot, [...nativePresetNames, ...selection.moduleSpecs], hot !== void 0);
1653
1447
  if (hot) hotSelections.set(vitestRootOf(userConfig), {
1654
1448
  pool: hot.pool,
1655
1449
  userPool,
1656
1450
  userMaxWorkers: userTest?.maxWorkers,
1657
- singleWorkerAccepted: hotMemory?.allowUnboundedMemory === true
1451
+ singleWorkerAccepted: hotMemory?.allowUnboundedMemory === true,
1452
+ memory: hotMemory && hotPoolOptions && !hotMemory.allowUnboundedMemory ? {
1453
+ plan: hotMemory.plan,
1454
+ poolOptions: hotPoolOptions,
1455
+ userMemoryLimit: hotRecycle.memoryLimit !== void 0,
1456
+ replan: hotMemory.replan,
1457
+ formatPlan: hotMemory.formatPlan,
1458
+ formatDecision: hotMemory.formatDecision,
1459
+ capWarning: hotMemory.capWarning
1460
+ } : void 0
1658
1461
  });
1659
1462
  else hotSelections.delete(vitestRootOf(userConfig));
1660
- return asCompatibleViteConfig(nativeEngineConfig(nativeSetupPath, env, extensions, transformPkgs, hot, jsxTransform, userPool, ecosystem, resolvedRoot, userInlinesEverything, projectDirs, nativeOwnership));
1463
+ const nativeConfig = nativeEngineConfig(nativeSetupPath, fields, extensions, transformPkgs, hot, jsxTransform, userPool, ecosystem, resolvedRoot, userInlinesEverything, projectDirs, nativeOwnership);
1464
+ nativeConfig.test.env = withProjectContext(fields, env, resolvedRoot);
1465
+ return asCompatibleViteConfig(nativeConfig);
1661
1466
  }
1662
1467
  if (hotRuntimeRequested && hotRuntimeExplicit) console.warn(`[vitest-native] 'hotRuntime' only applies to engine:'native' (resolved engine: '${engine}'); ignoring.`);
1663
- if (options?.mocks && Object.keys(options.mocks).length > 0) env.VITEST_NATIVE_MOCKS = JSON.stringify(options.mocks);
1468
+ if (options?.mocks && Object.keys(options.mocks).length > 0) fields.mocks = options.mocks;
1664
1469
  const selection = selectPresets(options?.presets, resolvedRoot);
1665
- if (selection.modulePaths.length > 0) env.VITEST_NATIVE_PRESET_MODULES = JSON.stringify(selection.modulePaths);
1666
- if (selection.listed) env.VITEST_NATIVE_PRESET_NAMES = JSON.stringify(selection.listed.map((p) => p.name));
1470
+ printEngineBanner(engine, platform, resolvedRoot, [...mockEnginePresetNames(selection.listed, options?.presets, resolvedRoot), ...selection.moduleSpecs]);
1471
+ if (selection.modulePaths.length > 0) fields.presetModules = selection.modulePaths;
1472
+ if (selection.listed) fields.presetNames = selection.listed.map((p) => p.name);
1667
1473
  else {
1668
1474
  const disabled = disabledPresetNames(options?.presets);
1669
- if (disabled.size > 0) env.VITEST_NATIVE_PRESET_DISABLED = JSON.stringify([...disabled]);
1475
+ if (disabled.size > 0) fields.presetDisabled = [...disabled];
1670
1476
  }
1671
1477
  return asCompatibleViteConfig({
1672
1478
  ...jsxTransform,
@@ -1697,7 +1503,7 @@ function reactNative(options) {
1697
1503
  },
1698
1504
  test: {
1699
1505
  setupFiles: [setupFilePath, presetReadyPath],
1700
- env
1506
+ env: withProjectContext(fields, env, resolvedRoot)
1701
1507
  }
1702
1508
  });
1703
1509
  },
@@ -1721,7 +1527,11 @@ function reactNative(options) {
1721
1527
  const peerErrors = [];
1722
1528
  for (const { name, minimum, maximumMajor, minimumByMajor, optional } of PEER_REQUIREMENTS) {
1723
1529
  if (optional) continue;
1724
- const error = validatePeerDependency(name, minimum, config.root, maximumMajor, minimumByMajor);
1530
+ if (name === "vitest") {
1531
+ const found = resolvePackageVersion("vitest", config.root);
1532
+ if (found === null || !(majorOf(found) < 4)) continue;
1533
+ }
1534
+ const error = validatePeerDependency(name, minimum, config.root, maximumMajor, minimumByMajor, name === "vite" ? hostViteVersion : void 0, name === "vite" ? hostViteSource : void 0);
1725
1535
  if (error) peerErrors.push(error);
1726
1536
  }
1727
1537
  if (peerErrors.length > 0) throw new VitestNativeError("UNSUPPORTED_PEER", `Unsupported peer dependencies:\n- ${peerErrors.join("\n- ")}`);
@@ -1730,6 +1540,12 @@ function reactNative(options) {
1730
1540
  const error = validatePeerDependency(name, minimum, config.root, maximumMajor, minimumByMajor);
1731
1541
  if (error && !error.includes("not found")) console.warn(`[vitest-native] ${error}`);
1732
1542
  }
1543
+ const expoVersion = installedExpoVersion(config.root);
1544
+ const expoProblem = expoVersion && unsupportedExpoSdkMessage(expoVersion);
1545
+ if (expoProblem && !warnedExpoProblems.has(expoProblem)) {
1546
+ warnedExpoProblems.add(expoProblem);
1547
+ console.warn(`[vitest-native] ${expoProblem}`);
1548
+ }
1733
1549
  resolved = await resolveOptions({
1734
1550
  ...options,
1735
1551
  engine
@@ -1779,7 +1595,10 @@ function reactNative(options) {
1779
1595
  if (source === "react-native" && rnFacadeExports !== null) return "\0virtual:rn-facade";
1780
1596
  const presetHit = resolvePresetId(source);
1781
1597
  if (presetHit) return presetHit;
1782
- return resolveExtensionless(source, importer) ?? alignedResolution(source, importer);
1598
+ const resolveReal = () => resolveExtensionless(source, importer) ?? alignedResolution(source, importer);
1599
+ const entryOf = assetPattern ? unexportedPresetSubpath(source) : null;
1600
+ if (entryOf === null) return resolveReal();
1601
+ return this.resolve(source, importer, { skipSelf: true }).then((hit) => hit && isPackageEntryFile(entryOf, stripFsPrefix(hit.id.split("?")[0]), importer?.split("?")[0]) ? `\0virtual:preset:${entryOf}` : resolveReal());
1783
1602
  }
1784
1603
  if (source === "react-native") return "\0virtual:react-native";
1785
1604
  if (source.startsWith("react-native/")) {
@@ -1826,7 +1645,7 @@ function reactNative(options) {
1826
1645
  ...exportNames.map((n) => `export const ${n} = _m['${n}'];`),
1827
1646
  ...leaf ? [
1828
1647
  `const _hit = ${JSON.stringify(leaf)} in _m;`,
1829
- `if (!_hit && process.env.VITEST_NATIVE_DIAGNOSTICS === "true") console.warn(${JSON.stringify(`[vitest-native] '${specifier}' has no matching export on the '${pkg}' preset mock; serving the root mock namespace.`)});`,
1648
+ `if (!_hit && ${diagnostics}) console.warn(${JSON.stringify(`[vitest-native] '${specifier}' has no matching export on the '${pkg}' preset mock; serving the root mock namespace.`)});`,
1830
1649
  `export default (_hit ? _m[${JSON.stringify(leaf)}] : ${fallback});`
1831
1650
  ] : [`export default ${fallback};`]
1832
1651
  ].join("\n");
@@ -1897,6 +1716,84 @@ function reactNative(options) {
1897
1716
  }
1898
1717
  }
1899
1718
  };
1719
+ function configureProject({ vitest, project, defineCacheKeyGenerator, experimental_defineCacheKeyGenerator }) {
1720
+ const projectConfig = project.config;
1721
+ const root = projectConfig.root ? path.resolve(projectConfig.root) : process.cwd();
1722
+ const coverage = engine === "native" && useNativeCoverageProvider(vitest.config?.coverage);
1723
+ if (typeof vitest.version === "string") {
1724
+ const vitestPeer = PEER_REQUIREMENTS.find((peer) => peer.name === "vitest");
1725
+ const error = vitestPeer && validatePeerDependency("vitest", vitestPeer.minimum, root, vitestPeer.maximumMajor, vitestPeer.minimumByMajor, vitest.version);
1726
+ if (error) throw new VitestNativeError("UNSUPPORTED_PEER", `Unsupported peer dependencies:\n- ${error}`);
1727
+ }
1728
+ const cacheKey = cacheKeys.get(root);
1729
+ if (cacheKey) (defineCacheKeyGenerator ?? experimental_defineCacheKeyGenerator)?.(() => cacheKey);
1730
+ const setupFile = contributedSetup.get(root);
1731
+ if (setupFile && !hasSetupFile(projectConfig.setupFiles, setupFile)) throw new VitestNativeError("SHARED_VITE_SERVER", `A Vitest project under ${root} shares a Vite server without vitest-native's test config, so React Native's setup would not run. Give the project a \`root\`, or set \`test.sharedViteServer: false\` in the top-level Vitest config.`);
1732
+ const presetExports = presetExportsByRoot.get(root);
1733
+ const contextRef = projectConfig.env?.[CONTEXT_ENV];
1734
+ if (typeof contextRef === "string") {
1735
+ const own = writtenContexts.get(contextRef) ?? projectContext(contextRef);
1736
+ if (own && !sameDirectory(own.projectRoot, root)) throw new VitestNativeError("CONTEXT_INVALID", `the project context is invalid (project): the Vitest project at ${root} was handed the context for ${own.projectRoot}. Give each project its own \`root\`, or report this, with the Vitest config, as a vitest-native bug.`);
1737
+ const changes = {
1738
+ ...presetExports ? { presetExports } : {},
1739
+ ...coverage ? { sourceMaps: true } : {}
1740
+ };
1741
+ const ref = Object.keys(changes).length > 0 ? amendProjectContext(contextRef, changes, root) : contextRef;
1742
+ projectConfig.env[CONTEXT_ENV] = ref;
1743
+ const fields = writtenContexts.get(ref);
1744
+ if (fields) vitest.onTestsRerun?.(() => {
1745
+ projectConfig.env[CONTEXT_ENV] = ensureProjectContext(projectConfig.env[CONTEXT_ENV] ?? ref, fields);
1746
+ });
1747
+ }
1748
+ const cli = vitest._cliOptions ?? vitest.config?.cliOptions ?? {};
1749
+ if (nativeRoots.has(root) && isVmPool(cli.pool)) throw vmPoolUnsupported(cli.pool);
1750
+ const pool = cli.pool ?? projectConfig.pool;
1751
+ if (isVmPool(pool) && PRESET_MODULES.skia.some((name) => presetExports?.[name])) throw new VitestNativeError("UNSUPPORTED_POOL", `The skia preset cannot run on the '${pool}' pool: Skia's test mock loads react-native through Node's require, which a VM pool's context does not route to the React Native mock. Use 'threads' (the default) or 'forks', or turn the preset off: reactNative({ presets: { skia: false } }).`);
1752
+ const selection = hotSelections.get(root);
1753
+ if (!selection) return;
1754
+ const override = hotOverrideReason(projectConfig, cli, selection.pool, selection.singleWorkerAccepted);
1755
+ const vitestWorkers = projectConfig.maxWorkers;
1756
+ const replanned = override === null && selection.memory ? replanForVitestWorkers(selection.memory, projectConfig) : void 0;
1757
+ const reason = override ?? sharedGroupConflict(project, vitest.projects ?? [], {
1758
+ maxWorkers: vitest.config?.maxWorkers,
1759
+ watch: vitest.config?.watch
1760
+ });
1761
+ if (reason === null) {
1762
+ if (replanned && selection.memory) applyHotMemoryPlan(selection.memory, replanned, projectConfig, diagnostics);
1763
+ else if (selection.memory?.capWarning) warnWorkersCapped(selection.memory.plan.requestedWorkers, selection.memory.plan);
1764
+ if (selection.memory) selection.memory.capWarning = false;
1765
+ printWorkerDecision(selection.memory ? selection.memory.formatDecision(selection.memory.plan) : `workers: ${String(projectConfig.maxWorkers ?? "Vitest's default")} (allowUnboundedMemory: no memory plan)`);
1766
+ return;
1767
+ }
1768
+ projectConfig.maxWorkers = vitestWorkers;
1769
+ if (!hotRuntimeAuto) throw hotRuntimeOverridden(reason);
1770
+ projectConfig.pool = cli.pool ?? selection.userPool ?? "threads";
1771
+ projectConfig.isolate = cli.isolate ?? true;
1772
+ projectConfig.runner = void 0;
1773
+ if (cli.maxWorkers === void 0 && !process.env.VITEST_MAX_WORKERS) projectConfig.maxWorkers = projectConfig.fileParallelism === false ? 1 : selection.userMaxWorkers === void 0 && vitest.config !== projectConfig && typeof vitest.config?.maxWorkers === "number" && vitestRootOf(vitest.config) !== root ? vitest.config.maxWorkers : vitestMaxWorkers(selection.userMaxWorkers, vitest.config?.watch === true);
1774
+ if (projectConfig.env) delete projectConfig.env.VITEST_NATIVE_MEMORY_PLAN;
1775
+ hotSelections.delete(root);
1776
+ console.error(`[vitest-native] hot runtime off: ${reason}; Vitest's settings apply.`);
1777
+ }
1778
+ /**
1779
+ * Refuse a run in which vitest-native's own `import 'vitest'` would reach a different
1780
+ * physical Vitest from the one running (host.ts): through the project's Vite resolver
1781
+ * for the setup file, and through Node for the hot runtime's worker.
1782
+ */
1783
+ async function verifyRunningVitest({ vitest, project }) {
1784
+ if (typeof vitest.version !== "string" || typeof vitest.distPath !== "string") return;
1785
+ const running = {
1786
+ version: vitest.version,
1787
+ distPath: vitest.distPath
1788
+ };
1789
+ const root = project.config.root ? path.resolve(project.config.root) : process.cwd();
1790
+ if (hotSelections.has(root)) assertHotWorkerLoadsRunningVitest(running, nativeWorkerPath);
1791
+ const setupFile = contributedSetup.get(root);
1792
+ const container = project.vite?.environments?.__vitest__?.pluginContainer ?? project.vite?.pluginContainer;
1793
+ const resolveId = container?.resolveId?.bind(container);
1794
+ if (!setupFile || resolveId === void 0) return;
1795
+ await assertHostResolvesRunningVitest(running, resolveId, setupFile);
1796
+ }
1900
1797
  const configHandler = pluginDefinition.config;
1901
1798
  return {
1902
1799
  ...pluginDefinition,
@@ -1913,7 +1810,7 @@ function reactNative(options) {
1913
1810
  if (test) test.execArgv = [...test.execArgv ?? [], ...EXPORT_RECOVERY_ARGV];
1914
1811
  if (test) {
1915
1812
  const viteRoot = userConfig.root ? path.resolve(userConfig.root) : process.cwd();
1916
- const vitestMajor = Number(resolvePackageVersion("vitest", viteRoot)?.split(".")[0]);
1813
+ const vitestMajor = majorOf(resolvePackageVersion("vitest", viteRoot) ?? ownVitestPackage()?.version);
1917
1814
  const userTest = userConfig.test;
1918
1815
  if (shouldDefaultFsModuleCache(vitestMajor, userTest)) test.fsModuleCache = true;
1919
1816
  cacheKeys.set(vitestRootOf(userConfig), fsModuleCacheKey(path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."), viteRoot, {
@@ -1923,7 +1820,7 @@ function reactNative(options) {
1923
1820
  }
1924
1821
  if (test) {
1925
1822
  const viteRoot = userConfig.root ? path.resolve(userConfig.root) : process.cwd();
1926
- const viteMajor = Number(resolvePackageVersion("vite", viteRoot)?.split(".")[0]);
1823
+ const viteMajor = majorOf(hostViteVersion);
1927
1824
  const tsconfigPaths = expoTsconfigPaths(viteRoot, userConfig.resolve?.tsconfigPaths, viteMajor);
1928
1825
  const config = result;
1929
1826
  if (tsconfigPaths === "enable") config.resolve = {
@@ -1938,39 +1835,10 @@ function reactNative(options) {
1938
1835
  return result;
1939
1836
  }
1940
1837
  },
1941
- configureVitest({ vitest, project, defineCacheKeyGenerator, experimental_defineCacheKeyGenerator }) {
1942
- const projectConfig = project.config;
1943
- const root = projectConfig.root ? path.resolve(projectConfig.root) : process.cwd();
1944
- const cacheKey = cacheKeys.get(root);
1945
- if (cacheKey) (defineCacheKeyGenerator ?? experimental_defineCacheKeyGenerator)?.(() => cacheKey);
1946
- const setupFile = contributedSetup.get(root);
1947
- if (setupFile && !hasSetupFile(projectConfig.setupFiles, setupFile)) throw new VitestNativeError("SHARED_VITE_SERVER", `A Vitest project under ${root} shares a Vite server without vitest-native's test config, so React Native's setup would not run. Give the project a \`root\`, or set \`test.sharedViteServer: false\` in the top-level Vitest config.`);
1948
- const presetExports = presetExportsByRoot.get(root);
1949
- if (presetExports) {
1950
- projectConfig.env ??= {};
1951
- projectConfig.env.VITEST_NATIVE_PRESET_EXPORTS = JSON.stringify(presetExports);
1952
- }
1953
- const cli = vitest._cliOptions ?? vitest.config?.cliOptions ?? {};
1954
- if (nativeRoots.has(root) && isVmPool(cli.pool)) throw vmPoolUnsupported(cli.pool);
1955
- const pool = cli.pool ?? projectConfig.pool;
1956
- if (isVmPool(pool) && PRESET_MODULES.skia.some((name) => presetExports?.[name])) throw new VitestNativeError("UNSUPPORTED_POOL", `The skia preset cannot run on the '${pool}' pool: Skia's test mock loads react-native through Node's require, which a VM pool's context does not route to the React Native mock. Use 'threads' (the default) or 'forks', or turn the preset off: reactNative({ presets: { skia: false } }).`);
1957
- const selection = hotSelections.get(root);
1958
- if (!selection) return;
1959
- const reason = hotOverrideReason(projectConfig, cli, selection.pool, selection.singleWorkerAccepted) ?? sharedGroupConflict(project, vitest.projects ?? [], {
1960
- maxWorkers: vitest.config?.maxWorkers,
1961
- watch: vitest.config?.watch
1962
- });
1963
- if (reason === null) return;
1964
- if (!hotRuntimeAuto) throw hotRuntimeOverridden(reason);
1965
- projectConfig.pool = cli.pool ?? selection.userPool ?? "threads";
1966
- projectConfig.isolate = cli.isolate ?? true;
1967
- projectConfig.runner = void 0;
1968
- if (cli.maxWorkers === void 0 && !process.env.VITEST_MAX_WORKERS) projectConfig.maxWorkers = projectConfig.fileParallelism === false ? 1 : selection.userMaxWorkers === void 0 && vitest.config !== projectConfig ? void 0 : vitestMaxWorkers(selection.userMaxWorkers, vitest.config?.watch === true);
1969
- if (projectConfig.env) delete projectConfig.env.VITEST_NATIVE_MEMORY_PLAN;
1970
- hotSelections.delete(root);
1971
- console.error(`[vitest-native] hot runtime off: ${reason}; Vitest's settings apply.`);
1838
+ configureVitest(context) {
1839
+ configureProject(context);
1840
+ return verifyRunningVitest(context);
1972
1841
  }
1973
1842
  };
1974
1843
  }
1975
- //#endregion
1976
1844
  export { disabledPresetNames, presets_exports as presets, reactNative };