vitest-native 0.11.1 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,199 @@
1
1
  # vitest-native
2
2
 
3
+ ## 0.12.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 0dce12c: Compile what Node cannot run, and nothing else
8
+
9
+ The native engine decided what to compile by NAME: a package was handed to the React
10
+ Native Babel preset because auto-detection or a dependency-closure walk selected it.
11
+ That guess was wrong far more often than it was right, and every way of being wrong
12
+ looked identical — a parse error deep inside a package the project never mentioned.
13
+ Babel's own emitted helpers, Metro's `lru-cache` chain and a pure-ESM validator all
14
+ arrived that way, and each was answered by adding another name to exclude.
15
+
16
+ The file answers precisely. If V8 can parse it, Node can run it, so compiling is
17
+ optional; if V8 cannot, Node cannot, so compiling is required — the same question Node
18
+ is about to ask, which is what makes it a fact rather than a heuristic. Files selected
19
+ for compiling are now parsed first, and only compiled if the parse fails.
20
+
21
+ What is given up is downleveling for Hermes: `const` to `var`, destructuring lowered.
22
+ Measured across React Native's own sources and the installed ecosystem, that is the
23
+ whole of what the preset does to a file V8 accepts, and it is behaviour-preserving on
24
+ Node — arguably closer to what the package published. `__DEV__` is left standing and
25
+ top-level requires are not inlined, so neither observable transform is affected.
26
+
27
+ **This is a robustness change, not a speed one.** On this repository's native suite
28
+ with a cold transform cache it measured 7.68s against 7.35s without the check: React
29
+ Native's own sources need compiling either way (440 of 450 fail to parse), so the check
30
+ mostly adds work here. The benefit is that a package Node can already run can no longer
31
+ reach Babel, whatever put it on the list.
32
+
33
+ Scoped to script-goal files. A `type: module` package is compiled exactly as before,
34
+ because the loader hands those to Node as CommonJS and changing that is an interop
35
+ question about named exports and live bindings that a parse cannot answer.
36
+
37
+ Also adds `transform: { include, exclude }`. `exclude` names packages the engine must
38
+ never compile, overriding auto-detection, the closure walk and the built-in lists —
39
+ so a project that hits a case the parse check does not cover can unblock itself the
40
+ same day instead of waiting for a release. The array form keeps its meaning.
41
+
42
+ ### Patch Changes
43
+
44
+ - c118f51: Reset externalized packages a test file imports, under the hot runtime
45
+
46
+ The hot runtime keeps a worker alive across test files and clears what each file
47
+ loaded, so the next one starts fresh. That reset could only reach Node's CommonJS
48
+ cache. A package reached through ESM `import` is held by Node's ESM registry, which
49
+ has no invalidation API, so its module-level state — a store, a client, a cache —
50
+ survived for the whole run. The second test file to touch such a package saw the
51
+ first one's writes.
52
+
53
+ The registry cannot be invalidated, but it is keyed by full URL, and the engine owns
54
+ the resolve hook. The per-file reset now advances a generation counter that the
55
+ loader stamps onto the resolved URL, so the next file imports a URL Node has not seen
56
+ and evaluates the module again. React Native itself and the identity-sensitive
57
+ modules already listed in the reset are exempt: for those a fresh instance is the
58
+ bug, not the fix. Cost is bounded by ownership — a CommonJS package re-enters through
59
+ `Module._cache`, which the reset already drops, so only a namespace wrapper is
60
+ retained per generation.
61
+
62
+ Correctness on a 135-file suite went from 126/135 to 135/135 against the same suite
63
+ under stock isolation.
64
+
65
+ The cost is re-execution, and it scales with how many externalized packages a test
66
+ file imports — which is nothing to do with React Native, since RN and the packages
67
+ that depend on it are inlined into Vite's graph and never reach this path. A suite
68
+ where every file imports eight ordinary npm packages measured 1.14s to 1.77s, 55%
69
+ more wall clock; stock isolation runs the same suite in 15.90s, so hot goes from
70
+ 13.9× to 9.0×. Suites that import few externalized packages pay close to nothing.
71
+
72
+ Peak RSS does not grow: 946 MB with the stamp against 955 MB without, on that same
73
+ suite. A CommonJS package re-enters through `Module._cache`, which the reset already
74
+ drops, so only a namespace wrapper is retained per generation.
75
+
76
+ `hotRuntime: { esmGeneration: false }` trades the correctness back for the speed.
77
+ Nothing changes when the hot runtime is off; the counter is only installed by the hot
78
+ worker.
79
+
80
+ The hot-isolation suite reached this fixture through `require` deliberately, because
81
+ the ESM path could not pass — it documented the hole rather than covering it. It now
82
+ has an ESM twin, and the scale validation gained templates for the shapes that were
83
+ missing from it entirely: real React Navigation, a navigation container wrapping a
84
+ Modal, and a node_modules package holding module-level state. Navigation had never
85
+ run under the hot runtime in any gate.
86
+
87
+ The stamp is scoped away from the test stack itself — vitest, `@vitest/*`, chai, and
88
+ this engine. The worker's runtime holds boot instances of these (the runner's
89
+ SnapshotClient, chai's extended Assertion, the engine's registry), and a test file
90
+ reaches the same packages through Node's ESM path; stamping those resolutions hands
91
+ the file a twin runtime whose failures are emergent and order-dependent —
92
+ `toMatchSnapshot` asking a SnapshotClient no one set up, fake timers flipping a copy
93
+ of the state the runner never reads. The workspace gates cannot see this class: in
94
+ the repository, the engine and the validation suites resolve outside node_modules,
95
+ where the node_modules-scoped stamp never applies. It surfaced only on a packed
96
+ install, running react-native-paper's suite under the hot runtime: 603/678 → 473/648
97
+ before the exemption, 609/678 — above the recorded baseline — with it.
98
+
99
+ The consumer tests gained the gate that class needs: the packed current-RN fixture
100
+ now runs a hot-runtime leg whose probe asserts the resolution invariant directly —
101
+ an ordinary node_modules package resolves generation-stamped while vitest,
102
+ `@vitest/snapshot`, chai, and the engine never do — alongside behavioral checks
103
+ (snapshots, fake timers, cross-file state reset from a packed install). Both
104
+ mutations were run before trusting it: removing the exemption and disabling the
105
+ generation mechanism each turn the leg red.
106
+
107
+ - c120d05: Match Metro's extension-major platform resolution order, verified against real metro-resolver
108
+
109
+ Platform-file resolution interleaved its candidate extensions platform-major —
110
+ every `.ios.*` variant before any `.native.*` before any bare extension. Metro
111
+ resolves extension-major: for each source extension in order, it tries the
112
+ platform variant, then `.native`, then bare (`.ios.js`, `.native.js`, `.js`,
113
+ `.ios.jsx`, …). The difference selects different files when a module mixes
114
+ platform variants across extensions: `Foo.native.js` beside `Foo.ios.tsx`
115
+ resolves to `.native.js` under Metro — the `js` round finishes before `tsx` is
116
+ tried — but resolved to `.ios.tsx` here, so a test could run a different file
117
+ than the application ships. One shared list feeds both the Vite graph and the
118
+ Node hooks, so the correction applies to both at once.
119
+
120
+ The order had also been asserted by a unit test whose literals were written from
121
+ the implementation — the gate encoded the mistake it existed to catch. The
122
+ authority is now external: a differential oracle resolves a 160-case sweep of
123
+ mixed platform/extension layouts (plus directory-index and per-extension cases)
124
+ through real metro-resolver and through this package's resolver and requires
125
+ byte-identical answers. The oracle runs against a pinned metro-resolver in the
126
+ PR gate, and the weekly compatibility job bumps metro-resolver@latest alongside
127
+ react-native@latest so upstream resolution changes surface as scheduled drift.
128
+ Reverting the interleaving fails the oracle on the exact mixed-variant shapes
129
+ described above.
130
+
131
+ - c27474e: Engine auto-detection requires react-native itself, not just its Babel toolchain
132
+
133
+ `engine: 'auto'` chose the native engine whenever `@react-native/babel-preset`
134
+ and `@babel/core` resolved — react-native itself was never checked, so an
135
+ incomplete install (or a babel-only workspace) selected native mode and then
136
+ failed later at React Native resolution with nothing pointing at the cause.
137
+
138
+ Detection now requires all three. The check resolves rather than reads
139
+ declarations — everything is located by walking node_modules upward from the
140
+ project root, so a hoisted workspace install or Expo's transitive react-native
141
+ counts without appearing in the project's own manifest. The fallback notice and
142
+ the explicit-`engine: 'native'` configuration error both name exactly which
143
+ dependencies did not resolve.
144
+
145
+ - 2fca83a: Compile a preset-shadowed package's pass-through entries when Node cannot run them
146
+
147
+ Preset packages are shadowed: their bare and subpath imports are redirected to the
148
+ preset mock before any file loads. The deliberate exceptions — package.json
149
+ subpaths, assets, and Node-safe utility entries such as `mock`, `plugin`, and
150
+ `jest-utils` — pass through to the real file. Some of those files only Metro can
151
+ run: react-native-worklets publishes its own mock entry (`lib/module/mock.js`) as
152
+ ESM `import` statements over a `module.exports = …` footer. And because the preset
153
+ shadow is exactly what keeps such packages out of ecosystem detection, nothing else
154
+ would ever compile them. A suite that maps the package onto its published mock —
155
+ react-native-paper does, via
156
+ `vi.mock('react-native-worklets', () => require('react-native-worklets/lib/module/mock'))` —
157
+ lost every test file whose component imports the package.
158
+
159
+ Preset-shadowed package names now join the Node-side transform set, built in the
160
+ worker from the same preset definitions that power the redirect, so user-supplied
161
+ presets are covered alongside the auto-detected ones. Membership only makes a file
162
+ eligible: `needsTransform` still gates every compile, so a pass-through Node can
163
+ already run is served untouched. The hot runtime needed one more piece — its worker
164
+ installs the require hooks at boot, before the setup file has built the preset
165
+ mocks, and the install-once guard silently pinned that boot-time list; the guard
166
+ now updates the transform matcher instead.
167
+
168
+ What the served-as-published failure looks like depends on the Node version, and
169
+ both shapes are cured: where Node lacks a `module` global the require(esm) retry
170
+ throws "module is not defined in ES module scope", and on Node 24 — which defines
171
+ `module` as a global — the file loads silently with EMPTY exports instead.
172
+
173
+ The thrown shape also joins the explained-error family: the ReferenceError from a
174
+ mixed ES-module/CommonJS file now gets the same actionable message as untranspiled
175
+ JSX/Flow/TS SyntaxErrors — naming the owning package and the `transform: [...]`
176
+ remedy — instead of a bare "module is not defined in ES module scope".
177
+
178
+ - 6bd6ec6: Scope the native transformer's toolchain to the project root instead of the process
179
+
180
+ The transformer resolved its toolchain — `@react-native/babel-preset`,
181
+ `@babel/core`, the flow-enums plugin, and the disk-cache directory — into module
182
+ globals initialized by the first caller. `transformRN` accepts a project root per
183
+ call, but a second root's calls silently reused the first root's resolved
184
+ toolchain and cache. Registries for every project in a Vitest workspace are built
185
+ in the one Vite main process, so two projects with different React Native or
186
+ Babel versions could serve the first project's output to the second project's
187
+ tests.
188
+
189
+ Proven before fixing: a regression test gives two roots their own Babel preset
190
+ whose plugin stamps a root-specific marker into every transformed file, and the
191
+ second root's file came back carrying the first root's stamp. Toolchain state now
192
+ lives in a per-root context — resolved requires, preset, lazily-loaded Babel,
193
+ in-memory cache, and disk-cache directory each belong to one canonical (realpath)
194
+ project root — and the same test asserts both call orders plus per-root cache
195
+ directories.
196
+
3
197
  ## 0.11.1
4
198
 
5
199
  ### Patch Changes
package/dist/cli.cjs CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  const require_rolldown_runtime = require("./rolldown-runtime-C0BPl7ul.cjs");
4
- const require_ecosystem = require("./ecosystem-DGlajfDG.cjs");
4
+ const require_ecosystem = require("./ecosystem-CEIF_-jq.cjs");
5
5
  const require_preset_map = require("./preset-map-BoG19dLa.cjs");
6
6
  let node_fs = require("node:fs");
7
7
  node_fs = require_rolldown_runtime.__toESM(node_fs, 1);
package/dist/cli.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { l as validatePeerDependency, n as detectEngine, s as PEER_REQUIREMENTS, t as detectEcosystemPackages } from "./ecosystem-DJMGR2YY.mjs";
2
+ import { l as validatePeerDependency, n as detectEngine, s as PEER_REQUIREMENTS, t as detectEcosystemPackages } from "./ecosystem-Duw40-mO.mjs";
3
3
  import { t as AUTO_DETECT_PRESETS } from "./preset-map-DuX0ocdn.mjs";
4
4
  import { createRequire } from "node:module";
5
5
  import fs from "node:fs";
@@ -20,7 +20,8 @@ const KNOWN_OPTIONS = [
20
20
  const KNOWN_HOT_RUNTIME_OPTIONS = [
21
21
  "recycleAfterFiles",
22
22
  "memoryLimit",
23
- "preserveGlobals"
23
+ "preserveGlobals",
24
+ "esmGeneration"
24
25
  ];
25
26
  function assertStringArray(value, option) {
26
27
  if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string" || entry.length === 0)) throw new require_errors.VitestNativeTypeError("INVALID_OPTION", `"${option}" must be an array of non-empty strings.`);
@@ -33,7 +34,14 @@ function validateOptions(options) {
33
34
  if (options.platform !== void 0 && options.platform !== "ios" && options.platform !== "android") throw new require_errors.VitestNativeTypeError("INVALID_OPTION", `"platform" must be "ios" or "android".`);
34
35
  if (options.diagnostics !== void 0 && typeof options.diagnostics !== "boolean") throw new require_errors.VitestNativeTypeError("INVALID_OPTION", `"diagnostics" must be a boolean.`);
35
36
  if (options.assetExts !== void 0) assertStringArray(options.assetExts, "assetExts");
36
- if (options.transform !== void 0) assertStringArray(options.transform, "transform");
37
+ if (options.transform !== void 0) if (Array.isArray(options.transform)) assertStringArray(options.transform, "transform");
38
+ else if (options.transform !== null && typeof options.transform === "object") {
39
+ const shape = options.transform;
40
+ const unknownKeys = Object.keys(shape).filter((k) => k !== "include" && k !== "exclude");
41
+ if (unknownKeys.length > 0) throw new require_errors.VitestNativeTypeError("INVALID_OPTION", `"transform" accepts only "include" and "exclude"; received ${unknownKeys.map((k) => `"${k}"`).join(", ")}.`);
42
+ if (shape.include !== void 0) assertStringArray(shape.include, "transform.include");
43
+ if (shape.exclude !== void 0) assertStringArray(shape.exclude, "transform.exclude");
44
+ } else throw new require_errors.VitestNativeTypeError("INVALID_OPTION", `"transform" must be an array of package names, or an object with "include" and/or "exclude".`);
37
45
  if (options.presets !== void 0 && !Array.isArray(options.presets)) {
38
46
  if (!(options.presets !== null && typeof options.presets === "object" && Object.values(options.presets).every((v) => typeof v === "boolean"))) throw new require_errors.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 }).");
39
47
  }
@@ -49,6 +57,7 @@ function validateOptions(options) {
49
57
  if (hotOptions.recycleAfterFiles !== void 0) assertNonNegativeInteger(hotOptions.recycleAfterFiles, "hotRuntime.recycleAfterFiles");
50
58
  if (hotOptions.memoryLimit !== void 0) assertNonNegativeInteger(hotOptions.memoryLimit, "hotRuntime.memoryLimit");
51
59
  if (hotOptions.preserveGlobals !== void 0) assertStringArray(hotOptions.preserveGlobals, "hotRuntime.preserveGlobals");
60
+ if (hotOptions.esmGeneration !== void 0 && typeof hotOptions.esmGeneration !== "boolean") throw new require_errors.VitestNativeTypeError("INVALID_OPTION", `"hotRuntime.esmGeneration" must be a boolean.`);
52
61
  }
53
62
  function satisfiesMinimum(version, minimum) {
54
63
  const parse = (v) => v.replace(/^[^0-9]*/, "").split(/[-+]/)[0].split(".").map(Number);
@@ -248,44 +257,71 @@ function packagePatterns(name, projectRoot) {
248
257
  if (dir && !containsPath(dir, projectRoot)) patterns.push(new RegExp(`^${escapeRe(toPosix(dir).replace(/\/$/, ""))}[\\\\/]`));
249
258
  return patterns;
250
259
  }
251
- /** Can this project run the native engine? (Both transform deps resolvable.) */
252
- function isNativeCapable(projectRoot) {
253
- try {
254
- const req = (0, node_module.createRequire)(node_path.default.join(projectRoot, "package.json"));
255
- req.resolve("@react-native/babel-preset");
256
- req.resolve("@babel/core");
257
- return true;
260
+ /**
261
+ * The native engine's dependencies that do NOT resolve from the project root.
262
+ *
263
+ * react-native itself is part of the check: the Babel toolchain alone chose
264
+ * native mode in a project with the preset installed but no react-native — an
265
+ * incomplete install, a babel-only workspace — which then failed later at RN
266
+ * resolution with nothing pointing at the cause. Resolution, not declaration:
267
+ * every check walks node_modules upward from the root — so a hoisted workspace
268
+ * install or Expo's transitive react-native counts, and a project does not need
269
+ * react-native in its own manifest.
270
+ */
271
+ function missingNativeDeps(projectRoot) {
272
+ const req = (0, node_module.createRequire)(node_path.default.join(projectRoot, "package.json"));
273
+ const missing = [];
274
+ if (!reactNativeInstalledNear(projectRoot)) missing.push("react-native");
275
+ for (const dep of ["@react-native/babel-preset", "@babel/core"]) try {
276
+ req.resolve(dep);
258
277
  } catch {
259
- return false;
278
+ missing.push(dep);
279
+ }
280
+ return missing;
281
+ }
282
+ /** Does node_modules/react-native exist in projectRoot or any ancestor? */
283
+ function reactNativeInstalledNear(projectRoot) {
284
+ let dir = node_path.default.resolve(projectRoot);
285
+ for (;;) {
286
+ if (node_fs.default.existsSync(node_path.default.join(dir, "node_modules", "react-native", "package.json"))) return true;
287
+ const parent = node_path.default.dirname(dir);
288
+ if (parent === dir) return false;
289
+ dir = parent;
260
290
  }
261
291
  }
262
292
  /** Resolve the concrete engine for a run. Pure; never throws. */
263
293
  function detectEngine(requested, projectRoot, opts) {
264
- const nativeAvailable = isNativeCapable(projectRoot);
294
+ const missing = missingNativeDeps(projectRoot);
295
+ const nativeAvailable = missing.length === 0;
265
296
  if (requested === "native") return {
266
297
  engine: "native",
267
298
  nativeAvailable,
299
+ missing,
268
300
  notice: null
269
301
  };
270
302
  if (requested === "mock") return {
271
303
  engine: "mock",
272
304
  nativeAvailable,
305
+ missing,
273
306
  notice: null
274
307
  };
275
308
  const prefersNative = opts?.autoPrefersNative ?? true;
276
309
  if (prefersNative && nativeAvailable) return {
277
310
  engine: "native",
278
311
  nativeAvailable,
312
+ missing,
279
313
  notice: null
280
314
  };
281
315
  if (prefersNative) return {
282
316
  engine: "mock",
283
317
  nativeAvailable: false,
284
- notice: "[vitest-native] @react-native/babel-preset not found — using the mock engine. Install it (and @babel/core) to run real React Native, or set engine:'mock' to silence this."
318
+ missing,
319
+ 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.`
285
320
  };
286
321
  return {
287
322
  engine: "mock",
288
323
  nativeAvailable,
324
+ missing,
289
325
  notice: null
290
326
  };
291
327
  }
@@ -449,12 +485,13 @@ function manifestsFrom(projectRoot) {
449
485
  * test infrastructure in NEVER_INLINE, and anything the consumer listed explicitly
450
486
  * in `transform` — that option keeps its existing meaning and takes precedence.
451
487
  */
452
- function detectEcosystemPackages(projectRoot, explicit = [], testRoots = []) {
488
+ function detectEcosystemPackages(projectRoot, explicit = [], testRoots = [], neverTransform = []) {
453
489
  const roots = (Array.isArray(projectRoot) ? projectRoot : [projectRoot]).filter(Boolean);
454
490
  const skip = /* @__PURE__ */ new Set([
455
491
  ...NEVER_INLINE,
456
492
  ...Object.keys(require_preset_map.AUTO_DETECT_PRESETS),
457
- ...explicit
493
+ ...explicit,
494
+ ...neverTransform
458
495
  ]);
459
496
  const candidates = /* @__PURE__ */ new Set();
460
497
  const found = roots.flatMap((root) => manifestsFrom(root));
@@ -17,7 +17,8 @@ const KNOWN_OPTIONS = [
17
17
  const KNOWN_HOT_RUNTIME_OPTIONS = [
18
18
  "recycleAfterFiles",
19
19
  "memoryLimit",
20
- "preserveGlobals"
20
+ "preserveGlobals",
21
+ "esmGeneration"
21
22
  ];
22
23
  function assertStringArray(value, option) {
23
24
  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.`);
@@ -30,7 +31,14 @@ function validateOptions(options) {
30
31
  if (options.platform !== void 0 && options.platform !== "ios" && options.platform !== "android") throw new VitestNativeTypeError("INVALID_OPTION", `"platform" must be "ios" or "android".`);
31
32
  if (options.diagnostics !== void 0 && typeof options.diagnostics !== "boolean") throw new VitestNativeTypeError("INVALID_OPTION", `"diagnostics" must be a boolean.`);
32
33
  if (options.assetExts !== void 0) assertStringArray(options.assetExts, "assetExts");
33
- if (options.transform !== void 0) assertStringArray(options.transform, "transform");
34
+ if (options.transform !== void 0) if (Array.isArray(options.transform)) assertStringArray(options.transform, "transform");
35
+ else if (options.transform !== null && typeof options.transform === "object") {
36
+ const shape = options.transform;
37
+ const unknownKeys = Object.keys(shape).filter((k) => k !== "include" && k !== "exclude");
38
+ if (unknownKeys.length > 0) throw new VitestNativeTypeError("INVALID_OPTION", `"transform" accepts only "include" and "exclude"; received ${unknownKeys.map((k) => `"${k}"`).join(", ")}.`);
39
+ if (shape.include !== void 0) assertStringArray(shape.include, "transform.include");
40
+ if (shape.exclude !== void 0) assertStringArray(shape.exclude, "transform.exclude");
41
+ } else throw new VitestNativeTypeError("INVALID_OPTION", `"transform" must be an array of package names, or an object with "include" and/or "exclude".`);
34
42
  if (options.presets !== void 0 && !Array.isArray(options.presets)) {
35
43
  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 }).");
36
44
  }
@@ -46,6 +54,7 @@ function validateOptions(options) {
46
54
  if (hotOptions.recycleAfterFiles !== void 0) assertNonNegativeInteger(hotOptions.recycleAfterFiles, "hotRuntime.recycleAfterFiles");
47
55
  if (hotOptions.memoryLimit !== void 0) assertNonNegativeInteger(hotOptions.memoryLimit, "hotRuntime.memoryLimit");
48
56
  if (hotOptions.preserveGlobals !== void 0) assertStringArray(hotOptions.preserveGlobals, "hotRuntime.preserveGlobals");
57
+ if (hotOptions.esmGeneration !== void 0 && typeof hotOptions.esmGeneration !== "boolean") throw new VitestNativeTypeError("INVALID_OPTION", `"hotRuntime.esmGeneration" must be a boolean.`);
49
58
  }
50
59
  function satisfiesMinimum(version, minimum) {
51
60
  const parse = (v) => v.replace(/^[^0-9]*/, "").split(/[-+]/)[0].split(".").map(Number);
@@ -245,44 +254,71 @@ function packagePatterns(name, projectRoot) {
245
254
  if (dir && !containsPath(dir, projectRoot)) patterns.push(new RegExp(`^${escapeRe(toPosix(dir).replace(/\/$/, ""))}[\\\\/]`));
246
255
  return patterns;
247
256
  }
248
- /** Can this project run the native engine? (Both transform deps resolvable.) */
249
- function isNativeCapable(projectRoot) {
250
- try {
251
- const req = createRequire(path.join(projectRoot, "package.json"));
252
- req.resolve("@react-native/babel-preset");
253
- req.resolve("@babel/core");
254
- return true;
257
+ /**
258
+ * The native engine's dependencies that do NOT resolve from the project root.
259
+ *
260
+ * react-native itself is part of the check: the Babel toolchain alone chose
261
+ * native mode in a project with the preset installed but no react-native — an
262
+ * incomplete install, a babel-only workspace — which then failed later at RN
263
+ * resolution with nothing pointing at the cause. Resolution, not declaration:
264
+ * every check walks node_modules upward from the root — so a hoisted workspace
265
+ * install or Expo's transitive react-native counts, and a project does not need
266
+ * react-native in its own manifest.
267
+ */
268
+ function missingNativeDeps(projectRoot) {
269
+ const req = createRequire(path.join(projectRoot, "package.json"));
270
+ const missing = [];
271
+ if (!reactNativeInstalledNear(projectRoot)) missing.push("react-native");
272
+ for (const dep of ["@react-native/babel-preset", "@babel/core"]) try {
273
+ req.resolve(dep);
255
274
  } catch {
256
- return false;
275
+ missing.push(dep);
276
+ }
277
+ return missing;
278
+ }
279
+ /** Does node_modules/react-native exist in projectRoot or any ancestor? */
280
+ function reactNativeInstalledNear(projectRoot) {
281
+ let dir = path.resolve(projectRoot);
282
+ for (;;) {
283
+ if (fs.existsSync(path.join(dir, "node_modules", "react-native", "package.json"))) return true;
284
+ const parent = path.dirname(dir);
285
+ if (parent === dir) return false;
286
+ dir = parent;
257
287
  }
258
288
  }
259
289
  /** Resolve the concrete engine for a run. Pure; never throws. */
260
290
  function detectEngine(requested, projectRoot, opts) {
261
- const nativeAvailable = isNativeCapable(projectRoot);
291
+ const missing = missingNativeDeps(projectRoot);
292
+ const nativeAvailable = missing.length === 0;
262
293
  if (requested === "native") return {
263
294
  engine: "native",
264
295
  nativeAvailable,
296
+ missing,
265
297
  notice: null
266
298
  };
267
299
  if (requested === "mock") return {
268
300
  engine: "mock",
269
301
  nativeAvailable,
302
+ missing,
270
303
  notice: null
271
304
  };
272
305
  const prefersNative = opts?.autoPrefersNative ?? true;
273
306
  if (prefersNative && nativeAvailable) return {
274
307
  engine: "native",
275
308
  nativeAvailable,
309
+ missing,
276
310
  notice: null
277
311
  };
278
312
  if (prefersNative) return {
279
313
  engine: "mock",
280
314
  nativeAvailable: false,
281
- notice: "[vitest-native] @react-native/babel-preset not found — using the mock engine. Install it (and @babel/core) to run real React Native, or set engine:'mock' to silence this."
315
+ missing,
316
+ 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.`
282
317
  };
283
318
  return {
284
319
  engine: "mock",
285
320
  nativeAvailable,
321
+ missing,
286
322
  notice: null
287
323
  };
288
324
  }
@@ -446,12 +482,13 @@ function manifestsFrom(projectRoot) {
446
482
  * test infrastructure in NEVER_INLINE, and anything the consumer listed explicitly
447
483
  * in `transform` — that option keeps its existing meaning and takes precedence.
448
484
  */
449
- function detectEcosystemPackages(projectRoot, explicit = [], testRoots = []) {
485
+ function detectEcosystemPackages(projectRoot, explicit = [], testRoots = [], neverTransform = []) {
450
486
  const roots = (Array.isArray(projectRoot) ? projectRoot : [projectRoot]).filter(Boolean);
451
487
  const skip = /* @__PURE__ */ new Set([
452
488
  ...NEVER_INLINE,
453
489
  ...Object.keys(AUTO_DETECT_PRESETS),
454
- ...explicit
490
+ ...explicit,
491
+ ...neverTransform
455
492
  ]);
456
493
  const candidates = /* @__PURE__ */ new Set();
457
494
  const found = roots.flatMap((root) => manifestsFrom(root));
@@ -287,12 +287,37 @@ interface VitestNativeOptions {
287
287
  * (e.g. `react-native-reanimated`, `react-native-safe-area-context`) need to
288
288
  * be listed here, analogous to Jest's `transformIgnorePatterns` allowlist.
289
289
  *
290
+ * The object form adds `exclude`, which names packages the engine must NEVER
291
+ * transform, whatever else would have selected them — auto-detection, a detected
292
+ * package's dependency closure, or the engine's own built-in lists.
293
+ *
294
+ * `exclude` exists because the engine's judgement about what is React Native source
295
+ * is a heuristic, and when it guesses wrong the failure is a parse error deep inside
296
+ * a package the project never named. Build toolchains are the recurring case:
297
+ * compiling one re-enters Babel while it is loading. The engine excludes the ones it
298
+ * knows about, but that list is only as current as the last release — `exclude` is
299
+ * how a project unblocks itself the same day, without waiting for one.
300
+ *
301
+ * Run with `diagnostics: true` to print the packages the engine chose to compile;
302
+ * that list is what `exclude` subtracts from.
303
+ *
290
304
  * @example
291
305
  * ```ts
292
306
  * reactNative({ engine: 'native', transform: ['react-native-reanimated'] })
307
+ *
308
+ * reactNative({
309
+ * engine: 'native',
310
+ * transform: {
311
+ * include: ['react-native-reanimated'],
312
+ * exclude: ['some-build-tool'], // never hand this to the Babel preset
313
+ * },
314
+ * })
293
315
  * ```
294
316
  */
295
- transform?: string[];
317
+ transform?: string[] | {
318
+ include?: string[];
319
+ exclude?: string[];
320
+ };
296
321
  /**
297
322
  * `engine: 'native'` only. **Experimental.** Run tests in persistent
298
323
  * RN-hot workers: React Native's module graph loads once per worker and
@@ -315,6 +340,15 @@ interface VitestNativeOptions {
315
340
  * - `preserveGlobals`: exact globalThis property names intentionally owned
316
341
  * by resident external libraries. App/test globals are otherwise removed
317
342
  * between files. Storybook's preview registry is preserved automatically.
343
+ * - `esmGeneration`: re-evaluate externalized packages a test file `import`s,
344
+ * so their module-level state does not carry into the next file. Node's ESM
345
+ * registry cannot be invalidated, so the loader stamps a per-file generation
346
+ * onto the resolved URL instead. On by default, because without it those
347
+ * packages behave differently under hot than under stock isolation. It costs
348
+ * re-execution: a suite whose files import many externalized (non-React
349
+ * Native) packages measured 55% more wall clock at the extreme — still 9x
350
+ * stock isolation, against 13.9x with it off. Set false to trade that back,
351
+ * accepting that a package holding state across files will keep it.
318
352
  *
319
353
  * Default: false (each file runs in a fresh worker; RN reloads per file).
320
354
  */
@@ -322,6 +356,7 @@ interface VitestNativeOptions {
322
356
  recycleAfterFiles?: number;
323
357
  memoryLimit?: number;
324
358
  preserveGlobals?: string[];
359
+ esmGeneration?: boolean;
325
360
  };
326
361
  }
327
362
  //#endregion
@@ -286,12 +286,37 @@ interface VitestNativeOptions {
286
286
  * (e.g. `react-native-reanimated`, `react-native-safe-area-context`) need to
287
287
  * be listed here, analogous to Jest's `transformIgnorePatterns` allowlist.
288
288
  *
289
+ * The object form adds `exclude`, which names packages the engine must NEVER
290
+ * transform, whatever else would have selected them — auto-detection, a detected
291
+ * package's dependency closure, or the engine's own built-in lists.
292
+ *
293
+ * `exclude` exists because the engine's judgement about what is React Native source
294
+ * is a heuristic, and when it guesses wrong the failure is a parse error deep inside
295
+ * a package the project never named. Build toolchains are the recurring case:
296
+ * compiling one re-enters Babel while it is loading. The engine excludes the ones it
297
+ * knows about, but that list is only as current as the last release — `exclude` is
298
+ * how a project unblocks itself the same day, without waiting for one.
299
+ *
300
+ * Run with `diagnostics: true` to print the packages the engine chose to compile;
301
+ * that list is what `exclude` subtracts from.
302
+ *
289
303
  * @example
290
304
  * ```ts
291
305
  * reactNative({ engine: 'native', transform: ['react-native-reanimated'] })
306
+ *
307
+ * reactNative({
308
+ * engine: 'native',
309
+ * transform: {
310
+ * include: ['react-native-reanimated'],
311
+ * exclude: ['some-build-tool'], // never hand this to the Babel preset
312
+ * },
313
+ * })
292
314
  * ```
293
315
  */
294
- transform?: string[];
316
+ transform?: string[] | {
317
+ include?: string[];
318
+ exclude?: string[];
319
+ };
295
320
  /**
296
321
  * `engine: 'native'` only. **Experimental.** Run tests in persistent
297
322
  * RN-hot workers: React Native's module graph loads once per worker and
@@ -314,6 +339,15 @@ interface VitestNativeOptions {
314
339
  * - `preserveGlobals`: exact globalThis property names intentionally owned
315
340
  * by resident external libraries. App/test globals are otherwise removed
316
341
  * between files. Storybook's preview registry is preserved automatically.
342
+ * - `esmGeneration`: re-evaluate externalized packages a test file `import`s,
343
+ * so their module-level state does not carry into the next file. Node's ESM
344
+ * registry cannot be invalidated, so the loader stamps a per-file generation
345
+ * onto the resolved URL instead. On by default, because without it those
346
+ * packages behave differently under hot than under stock isolation. It costs
347
+ * re-execution: a suite whose files import many externalized (non-React
348
+ * Native) packages measured 55% more wall clock at the extreme — still 9x
349
+ * stock isolation, against 13.9x with it off. Set false to trade that back,
350
+ * accepting that a package holding state across files will keep it.
317
351
  *
318
352
  * Default: false (each file runs in a fresh worker; RN reloads per file).
319
353
  */
@@ -321,6 +355,7 @@ interface VitestNativeOptions {
321
355
  recycleAfterFiles?: number;
322
356
  memoryLimit?: number;
323
357
  preserveGlobals?: string[];
358
+ esmGeneration?: boolean;
324
359
  };
325
360
  }
326
361
  //#endregion
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { b as ReactNativeMock, t as index_d_exports, x as VitestNativeOptions, y as Preset } from "./index-CrMeE8rd.mjs";
1
+ import { b as ReactNativeMock, t as index_d_exports, x as VitestNativeOptions, y as Preset } from "./index-CmETArCM.mjs";
2
2
  import { Plugin } from "vite";
3
3
  //#region src/plugin.d.ts
4
4
  /**