vitest-native 0.11.1 → 0.13.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,244 @@
1
1
  # vitest-native
2
2
 
3
+ ## 0.13.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 0c25e74: New helper `extendPresetMock(pkg, overrides)`: merge overrides into a preset's module mock (and its `default` export) — e.g. to give expo-constants a real `expoConfig` or add an export a library calls that the preset does not model. Undone by `resetAllMocks()`.
8
+ - 1283531: React Native 0.87 joins the supported matrix
9
+
10
+ The verified range is now 0.81–0.87: the CI matrix gains a 0.87 row (and the
11
+ Vitest 5 column moves its newest-RN cell up), the workspace pins 0.87, and the
12
+ published range statements follow. 0.87 removed InteractionManager, so its
13
+ cross-check probe is version-gated rather than deleted — the 0.81–0.86 legs
14
+ still compare it, and the published corpus count on the pinned version drops
15
+ from 85 to 84 with the retirement recorded deliberately via the report's
16
+ --allow-corpus-shrink flag.
17
+
18
+ ### Patch Changes
19
+
20
+ - 9f4fd3c: Complete the expo-linking preset mock: add `addEventListener`, `resolveScheme` and `getInitialURL`, which expo-router's linking layer calls at render time.
21
+ - 4216b1f: Fabricated native-module stubs follow Expo method conventions: unknown `*Async` properties resolve a Promise (fixes expo-notifications crashing at import), and unknown PascalCase properties are memoized classes extending `SharedObject` (fixes expo-file-system's `class File extends ExpoFileSystem.FileSystemFile`).
22
+ - 36a1625: Mock registries are null-prototype objects, so a module or package name of `__proto__` becomes an ordinary entry instead of re-prototyping the registry. Hardens the published `mockNativeModule()` surface against prototype-polluting names — the same class CodeQL flagged on `extendPresetMock()`.
23
+ - b127e6d: Resolve React Native 0.87's gated deep imports, and mock its new AssetRegistry export
24
+
25
+ React Native 0.87 ships an `exports` map whose deep-import surface sits behind
26
+ Metro's `react-native-legacy-deep-imports` condition — and its Babel preset now
27
+ compiles RN's own relative imports into bare deep specifiers
28
+ (`react-native/src/private/…`), so RN's compiled graph self-references through
29
+ paths plain Node refuses with `ERR_PACKAGE_PATH_NOT_EXPORTED`. Under the native
30
+ engine that failed almost every suite at collection. The engine now mirrors
31
+ Metro: when Node's resolver rejects a `react-native/*` or `@react-native/*` deep
32
+ specifier, the file is located by path from the package's real directory,
33
+ platform extensions included, in the require hook, the ESM loader, and the
34
+ precompiled registry's fall-through — where resolving by path keeps deep files
35
+ on the registry's instances instead of loading twins. Inert on 0.86 and earlier,
36
+ which have no exports map to reject anything.
37
+
38
+ The mock engine gains `AssetRegistry` (a top-level export since 0.87),
39
+ mirroring `@react-native/assets-registry/registry` down to its 1-based truthy
40
+ ids. The compatibility checker no longer misreads the bare `get() {` inside
41
+ 0.87's new `Object.defineProperty` export blocks as an export named `get`, and
42
+ the InteractionManager probe is version-gated: 0.87 removed the API outright,
43
+ so the matrix keeps running it on every version that ships it.
44
+
45
+ React Native 0.87 is not yet in the supported matrix — its release is inside
46
+ the dependency cooldown window; adoption follows separately.
47
+
48
+ ## 0.12.0
49
+
50
+ ### Minor Changes
51
+
52
+ - 0dce12c: Compile what Node cannot run, and nothing else
53
+
54
+ The native engine decided what to compile by NAME: a package was handed to the React
55
+ Native Babel preset because auto-detection or a dependency-closure walk selected it.
56
+ That guess was wrong far more often than it was right, and every way of being wrong
57
+ looked identical — a parse error deep inside a package the project never mentioned.
58
+ Babel's own emitted helpers, Metro's `lru-cache` chain and a pure-ESM validator all
59
+ arrived that way, and each was answered by adding another name to exclude.
60
+
61
+ The file answers precisely. If V8 can parse it, Node can run it, so compiling is
62
+ optional; if V8 cannot, Node cannot, so compiling is required — the same question Node
63
+ is about to ask, which is what makes it a fact rather than a heuristic. Files selected
64
+ for compiling are now parsed first, and only compiled if the parse fails.
65
+
66
+ What is given up is downleveling for Hermes: `const` to `var`, destructuring lowered.
67
+ Measured across React Native's own sources and the installed ecosystem, that is the
68
+ whole of what the preset does to a file V8 accepts, and it is behaviour-preserving on
69
+ Node — arguably closer to what the package published. `__DEV__` is left standing and
70
+ top-level requires are not inlined, so neither observable transform is affected.
71
+
72
+ **This is a robustness change, not a speed one.** On this repository's native suite
73
+ with a cold transform cache it measured 7.68s against 7.35s without the check: React
74
+ Native's own sources need compiling either way (440 of 450 fail to parse), so the check
75
+ mostly adds work here. The benefit is that a package Node can already run can no longer
76
+ reach Babel, whatever put it on the list.
77
+
78
+ Scoped to script-goal files. A `type: module` package is compiled exactly as before,
79
+ because the loader hands those to Node as CommonJS and changing that is an interop
80
+ question about named exports and live bindings that a parse cannot answer.
81
+
82
+ Also adds `transform: { include, exclude }`. `exclude` names packages the engine must
83
+ never compile, overriding auto-detection, the closure walk and the built-in lists —
84
+ so a project that hits a case the parse check does not cover can unblock itself the
85
+ same day instead of waiting for a release. The array form keeps its meaning.
86
+
87
+ ### Patch Changes
88
+
89
+ - c118f51: Reset externalized packages a test file imports, under the hot runtime
90
+
91
+ The hot runtime keeps a worker alive across test files and clears what each file
92
+ loaded, so the next one starts fresh. That reset could only reach Node's CommonJS
93
+ cache. A package reached through ESM `import` is held by Node's ESM registry, which
94
+ has no invalidation API, so its module-level state — a store, a client, a cache —
95
+ survived for the whole run. The second test file to touch such a package saw the
96
+ first one's writes.
97
+
98
+ The registry cannot be invalidated, but it is keyed by full URL, and the engine owns
99
+ the resolve hook. The per-file reset now advances a generation counter that the
100
+ loader stamps onto the resolved URL, so the next file imports a URL Node has not seen
101
+ and evaluates the module again. React Native itself and the identity-sensitive
102
+ modules already listed in the reset are exempt: for those a fresh instance is the
103
+ bug, not the fix. Cost is bounded by ownership — a CommonJS package re-enters through
104
+ `Module._cache`, which the reset already drops, so only a namespace wrapper is
105
+ retained per generation.
106
+
107
+ Correctness on a 135-file suite went from 126/135 to 135/135 against the same suite
108
+ under stock isolation.
109
+
110
+ The cost is re-execution, and it scales with how many externalized packages a test
111
+ file imports — which is nothing to do with React Native, since RN and the packages
112
+ that depend on it are inlined into Vite's graph and never reach this path. A suite
113
+ where every file imports eight ordinary npm packages measured 1.14s to 1.77s, 55%
114
+ more wall clock; stock isolation runs the same suite in 15.90s, so hot goes from
115
+ 13.9× to 9.0×. Suites that import few externalized packages pay close to nothing.
116
+
117
+ Peak RSS does not grow: 946 MB with the stamp against 955 MB without, on that same
118
+ suite. A CommonJS package re-enters through `Module._cache`, which the reset already
119
+ drops, so only a namespace wrapper is retained per generation.
120
+
121
+ `hotRuntime: { esmGeneration: false }` trades the correctness back for the speed.
122
+ Nothing changes when the hot runtime is off; the counter is only installed by the hot
123
+ worker.
124
+
125
+ The hot-isolation suite reached this fixture through `require` deliberately, because
126
+ the ESM path could not pass — it documented the hole rather than covering it. It now
127
+ has an ESM twin, and the scale validation gained templates for the shapes that were
128
+ missing from it entirely: real React Navigation, a navigation container wrapping a
129
+ Modal, and a node_modules package holding module-level state. Navigation had never
130
+ run under the hot runtime in any gate.
131
+
132
+ The stamp is scoped away from the test stack itself — vitest, `@vitest/*`, chai, and
133
+ this engine. The worker's runtime holds boot instances of these (the runner's
134
+ SnapshotClient, chai's extended Assertion, the engine's registry), and a test file
135
+ reaches the same packages through Node's ESM path; stamping those resolutions hands
136
+ the file a twin runtime whose failures are emergent and order-dependent —
137
+ `toMatchSnapshot` asking a SnapshotClient no one set up, fake timers flipping a copy
138
+ of the state the runner never reads. The workspace gates cannot see this class: in
139
+ the repository, the engine and the validation suites resolve outside node_modules,
140
+ where the node_modules-scoped stamp never applies. It surfaced only on a packed
141
+ install, running react-native-paper's suite under the hot runtime: 603/678 → 473/648
142
+ before the exemption, 609/678 — above the recorded baseline — with it.
143
+
144
+ The consumer tests gained the gate that class needs: the packed current-RN fixture
145
+ now runs a hot-runtime leg whose probe asserts the resolution invariant directly —
146
+ an ordinary node_modules package resolves generation-stamped while vitest,
147
+ `@vitest/snapshot`, chai, and the engine never do — alongside behavioral checks
148
+ (snapshots, fake timers, cross-file state reset from a packed install). Both
149
+ mutations were run before trusting it: removing the exemption and disabling the
150
+ generation mechanism each turn the leg red.
151
+
152
+ - c120d05: Match Metro's extension-major platform resolution order, verified against real metro-resolver
153
+
154
+ Platform-file resolution interleaved its candidate extensions platform-major —
155
+ every `.ios.*` variant before any `.native.*` before any bare extension. Metro
156
+ resolves extension-major: for each source extension in order, it tries the
157
+ platform variant, then `.native`, then bare (`.ios.js`, `.native.js`, `.js`,
158
+ `.ios.jsx`, …). The difference selects different files when a module mixes
159
+ platform variants across extensions: `Foo.native.js` beside `Foo.ios.tsx`
160
+ resolves to `.native.js` under Metro — the `js` round finishes before `tsx` is
161
+ tried — but resolved to `.ios.tsx` here, so a test could run a different file
162
+ than the application ships. One shared list feeds both the Vite graph and the
163
+ Node hooks, so the correction applies to both at once.
164
+
165
+ The order had also been asserted by a unit test whose literals were written from
166
+ the implementation — the gate encoded the mistake it existed to catch. The
167
+ authority is now external: a differential oracle resolves a 160-case sweep of
168
+ mixed platform/extension layouts (plus directory-index and per-extension cases)
169
+ through real metro-resolver and through this package's resolver and requires
170
+ byte-identical answers. The oracle runs against a pinned metro-resolver in the
171
+ PR gate, and the weekly compatibility job bumps metro-resolver@latest alongside
172
+ react-native@latest so upstream resolution changes surface as scheduled drift.
173
+ Reverting the interleaving fails the oracle on the exact mixed-variant shapes
174
+ described above.
175
+
176
+ - c27474e: Engine auto-detection requires react-native itself, not just its Babel toolchain
177
+
178
+ `engine: 'auto'` chose the native engine whenever `@react-native/babel-preset`
179
+ and `@babel/core` resolved — react-native itself was never checked, so an
180
+ incomplete install (or a babel-only workspace) selected native mode and then
181
+ failed later at React Native resolution with nothing pointing at the cause.
182
+
183
+ Detection now requires all three. The check resolves rather than reads
184
+ declarations — everything is located by walking node_modules upward from the
185
+ project root, so a hoisted workspace install or Expo's transitive react-native
186
+ counts without appearing in the project's own manifest. The fallback notice and
187
+ the explicit-`engine: 'native'` configuration error both name exactly which
188
+ dependencies did not resolve.
189
+
190
+ - 2fca83a: Compile a preset-shadowed package's pass-through entries when Node cannot run them
191
+
192
+ Preset packages are shadowed: their bare and subpath imports are redirected to the
193
+ preset mock before any file loads. The deliberate exceptions — package.json
194
+ subpaths, assets, and Node-safe utility entries such as `mock`, `plugin`, and
195
+ `jest-utils` — pass through to the real file. Some of those files only Metro can
196
+ run: react-native-worklets publishes its own mock entry (`lib/module/mock.js`) as
197
+ ESM `import` statements over a `module.exports = …` footer. And because the preset
198
+ shadow is exactly what keeps such packages out of ecosystem detection, nothing else
199
+ would ever compile them. A suite that maps the package onto its published mock —
200
+ react-native-paper does, via
201
+ `vi.mock('react-native-worklets', () => require('react-native-worklets/lib/module/mock'))` —
202
+ lost every test file whose component imports the package.
203
+
204
+ Preset-shadowed package names now join the Node-side transform set, built in the
205
+ worker from the same preset definitions that power the redirect, so user-supplied
206
+ presets are covered alongside the auto-detected ones. Membership only makes a file
207
+ eligible: `needsTransform` still gates every compile, so a pass-through Node can
208
+ already run is served untouched. The hot runtime needed one more piece — its worker
209
+ installs the require hooks at boot, before the setup file has built the preset
210
+ mocks, and the install-once guard silently pinned that boot-time list; the guard
211
+ now updates the transform matcher instead.
212
+
213
+ What the served-as-published failure looks like depends on the Node version, and
214
+ both shapes are cured: where Node lacks a `module` global the require(esm) retry
215
+ throws "module is not defined in ES module scope", and on Node 24 — which defines
216
+ `module` as a global — the file loads silently with EMPTY exports instead.
217
+
218
+ The thrown shape also joins the explained-error family: the ReferenceError from a
219
+ mixed ES-module/CommonJS file now gets the same actionable message as untranspiled
220
+ JSX/Flow/TS SyntaxErrors — naming the owning package and the `transform: [...]`
221
+ remedy — instead of a bare "module is not defined in ES module scope".
222
+
223
+ - 6bd6ec6: Scope the native transformer's toolchain to the project root instead of the process
224
+
225
+ The transformer resolved its toolchain — `@react-native/babel-preset`,
226
+ `@babel/core`, the flow-enums plugin, and the disk-cache directory — into module
227
+ globals initialized by the first caller. `transformRN` accepts a project root per
228
+ call, but a second root's calls silently reused the first root's resolved
229
+ toolchain and cache. Registries for every project in a Vitest workspace are built
230
+ in the one Vite main process, so two projects with different React Native or
231
+ Babel versions could serve the first project's output to the second project's
232
+ tests.
233
+
234
+ Proven before fixing: a regression test gives two roots their own Babel preset
235
+ whose plugin stamps a root-specific marker into every transformed file, and the
236
+ second root's file came back carrying the first root's stamp. Toolchain state now
237
+ lives in a per-root context — resolved requires, preset, lazily-loaded Babel,
238
+ in-memory cache, and disk-cache directory each belong to one canonical (realpath)
239
+ project root — and the same test asserts both call orders plus per-root cache
240
+ directories.
241
+
3
242
  ## 0.11.1
4
243
 
5
244
  ### 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));
package/dist/helpers.cjs CHANGED
@@ -49,6 +49,49 @@ function setInsets(insets) {
49
49
  const safeArea = globalThis.__vitest_native_preset_mocks?.["react-native-safe-area-context"];
50
50
  if (safeArea?._setInsets) safeArea._setInsets(insets);
51
51
  }
52
+ let presetMockOverrides = [];
53
+ /**
54
+ * Merge overrides into a preset's module mock (and its `default`, when that is
55
+ * an object) — e.g. to give expo-constants a real `expoConfig` or add an export
56
+ * a library calls that the preset does not model. Returns `false` when no
57
+ * preset mock exists for the package. Undone by `resetAllMocks()`.
58
+ */
59
+ function extendPresetMock(pkg, overrides) {
60
+ const mock = globalThis.__vitest_native_preset_mocks?.[pkg];
61
+ if (!mock) return false;
62
+ const targets = [mock];
63
+ if (mock.default && typeof mock.default === "object" && mock.default !== mock) targets.push(mock.default);
64
+ for (const target of targets) for (const [key, value] of Object.entries(overrides)) {
65
+ if (key === "__proto__" || key === "constructor" || key === "prototype") continue;
66
+ presetMockOverrides.push({
67
+ target,
68
+ key,
69
+ had: Object.prototype.hasOwnProperty.call(target, key),
70
+ previous: target[key]
71
+ });
72
+ Object.defineProperty(target, key, {
73
+ configurable: true,
74
+ enumerable: true,
75
+ writable: true,
76
+ value
77
+ });
78
+ }
79
+ return true;
80
+ }
81
+ function restorePresetMockOverrides() {
82
+ for (let i = presetMockOverrides.length - 1; i >= 0; i--) {
83
+ const { target, key, had, previous } = presetMockOverrides[i];
84
+ if (key === "__proto__" || key === "constructor" || key === "prototype") continue;
85
+ if (had) Object.defineProperty(target, key, {
86
+ configurable: true,
87
+ enumerable: true,
88
+ writable: true,
89
+ value: previous
90
+ });
91
+ else delete target[key];
92
+ }
93
+ presetMockOverrides = [];
94
+ }
52
95
  function mockNativeModule(name, impl) {
53
96
  const native = getNativeControl();
54
97
  if (native) return native.mockNativeModule(name, impl);
@@ -73,6 +116,7 @@ function clearMockFns(obj, visited = /* @__PURE__ */ new Set()) {
73
116
  }
74
117
  }
75
118
  function resetAllMocks() {
119
+ restorePresetMockOverrides();
76
120
  const native = getNativeControl();
77
121
  if (native) return native.resetAllMocks();
78
122
  const mock = getMock();
@@ -111,6 +155,7 @@ function resetAllMocks() {
111
155
  }
112
156
  }
113
157
  //#endregion
158
+ exports.extendPresetMock = extendPresetMock;
114
159
  exports.mockNativeModule = mockNativeModule;
115
160
  exports.resetAllMocks = resetAllMocks;
116
161
  exports.setColorScheme = setColorScheme;
@@ -13,7 +13,14 @@ declare function setInsets(insets: {
13
13
  bottom?: number;
14
14
  left?: number;
15
15
  }): void;
16
+ /**
17
+ * Merge overrides into a preset's module mock (and its `default`, when that is
18
+ * an object) — e.g. to give expo-constants a real `expoConfig` or add an export
19
+ * a library calls that the preset does not model. Returns `false` when no
20
+ * preset mock exists for the package. Undone by `resetAllMocks()`.
21
+ */
22
+ declare function extendPresetMock(pkg: string, overrides: Record<string, any>): boolean;
16
23
  declare function mockNativeModule(name: string, impl: Record<string, any>): void;
17
24
  declare function resetAllMocks(): void;
18
25
  //#endregion
19
- export { mockNativeModule, resetAllMocks, setColorScheme, setDimensions, setInsets, setPlatform };
26
+ export { extendPresetMock, mockNativeModule, resetAllMocks, setColorScheme, setDimensions, setInsets, setPlatform };
@@ -13,7 +13,14 @@ declare function setInsets(insets: {
13
13
  bottom?: number;
14
14
  left?: number;
15
15
  }): void;
16
+ /**
17
+ * Merge overrides into a preset's module mock (and its `default`, when that is
18
+ * an object) — e.g. to give expo-constants a real `expoConfig` or add an export
19
+ * a library calls that the preset does not model. Returns `false` when no
20
+ * preset mock exists for the package. Undone by `resetAllMocks()`.
21
+ */
22
+ declare function extendPresetMock(pkg: string, overrides: Record<string, any>): boolean;
16
23
  declare function mockNativeModule(name: string, impl: Record<string, any>): void;
17
24
  declare function resetAllMocks(): void;
18
25
  //#endregion
19
- export { mockNativeModule, resetAllMocks, setColorScheme, setDimensions, setInsets, setPlatform };
26
+ export { extendPresetMock, mockNativeModule, resetAllMocks, setColorScheme, setDimensions, setInsets, setPlatform };