vitest-native 0.8.0 → 0.9.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 (46) hide show
  1. package/CHANGELOG.md +332 -0
  2. package/README.md +15 -1
  3. package/dist/cli.cjs +506 -0
  4. package/dist/cli.d.cts +4 -0
  5. package/dist/cli.d.mts +4 -0
  6. package/dist/cli.mjs +502 -0
  7. package/dist/ecosystem-BIWaVwYL.cjs +294 -0
  8. package/dist/ecosystem-EFtHnKS9.mjs +256 -0
  9. package/dist/{index-vlK4zxuK.d.mts → index-CEgRDdhd.d.cts} +13 -3
  10. package/dist/{index-YjjYELG7.d.cts → index-j-0tueBr.d.mts} +11 -5
  11. package/dist/index.cjs +345 -200
  12. package/dist/index.d.cts +1 -1
  13. package/dist/index.d.mts +1 -1
  14. package/dist/index.mjs +341 -196
  15. package/dist/jest-compat/setup.mjs +65 -1
  16. package/dist/native/boundary.mjs +108 -30
  17. package/dist/native/compile-cache.mjs +10 -5
  18. package/dist/native/explain.mjs +69 -0
  19. package/dist/native/hooks.mjs +76 -3
  20. package/dist/native/loader.mjs +35 -6
  21. package/dist/native/match.mjs +107 -8
  22. package/dist/native/registry.mjs +471 -0
  23. package/dist/native/reset.mjs +18 -12
  24. package/dist/native/runner.mjs +13 -7
  25. package/dist/native/setup.mjs +15 -1
  26. package/dist/native/transform.mjs +88 -19
  27. package/dist/native/worker.mjs +10 -1
  28. package/dist/pool-CJmjRgsB.mjs +117 -0
  29. package/dist/pool-DzsEo9vv.cjs +121 -0
  30. package/dist/{preset-map-BY9zk9Pj.cjs → preset-map-CG4FMtsl.cjs} +1 -0
  31. package/dist/{preset-map-DCWaM08s.mjs → preset-map-CNsZKfvu.mjs} +1 -0
  32. package/dist/{presets-7eMfp7o2.cjs → presets-C4faM3ds.cjs} +133 -2
  33. package/dist/{presets-23FJ76O4.mjs → presets-CuDrNA_W.mjs} +128 -3
  34. package/dist/presets.cjs +2 -1
  35. package/dist/presets.d.cts +2 -2
  36. package/dist/presets.d.mts +2 -2
  37. package/dist/presets.mjs +2 -2
  38. package/dist/setup.cjs +318 -130
  39. package/dist/setup.mjs +318 -130
  40. package/docs/hot-default-design.md +129 -0
  41. package/docs/migrating-from-jest.md +43 -7
  42. package/docs/migrating-from-vitest-react-native.md +1 -1
  43. package/docs/release-readiness.md +2 -1
  44. package/package.json +17 -5
  45. package/dist/pool-B7LBfcMQ.mjs +0 -67
  46. package/dist/pool-p54QV1dQ.cjs +0 -69
package/dist/index.mjs CHANGED
@@ -1,7 +1,8 @@
1
- import { t as AUTO_DETECT_PRESETS } from "./preset-map-DCWaM08s.mjs";
2
- import { t as presets_exports } from "./presets-23FJ76O4.mjs";
1
+ import { a as validatePeerDependency, i as validateOptions, n as detectEngine, o as warnUnknownOptions, r as PEER_REQUIREMENTS, t as detectEcosystemPackages } from "./ecosystem-EFtHnKS9.mjs";
2
+ import { t as AUTO_DETECT_PRESETS } from "./preset-map-CNsZKfvu.mjs";
3
+ import { t as presets_exports } from "./presets-CuDrNA_W.mjs";
3
4
  import { createRequire } from "node:module";
4
- import { fileURLToPath } from "node:url";
5
+ import { fileURLToPath, pathToFileURL } from "node:url";
5
6
  import path from "node:path";
6
7
  import fs from "node:fs";
7
8
  import flowRemoveTypes from "flow-remove-types";
@@ -38,95 +39,6 @@ function getPlatformExtensions(platform) {
38
39
  return platform === "ios" ? PLATFORM_EXTENSIONS_IOS : PLATFORM_EXTENSIONS_ANDROID;
39
40
  }
40
41
  //#endregion
41
- //#region src/validate.ts
42
- const KNOWN_OPTIONS = [
43
- "platform",
44
- "presets",
45
- "mocks",
46
- "diagnostics",
47
- "assetExts",
48
- "engine",
49
- "transform",
50
- "hotRuntime"
51
- ];
52
- const KNOWN_HOT_RUNTIME_OPTIONS = [
53
- "recycleAfterFiles",
54
- "memoryLimit",
55
- "preserveGlobals"
56
- ];
57
- function assertStringArray(value, option) {
58
- if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string" || entry.length === 0)) throw new TypeError(`[vitest-native] "${option}" must be an array of non-empty strings.`);
59
- }
60
- function assertNonNegativeInteger(value, option) {
61
- if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw new TypeError(`[vitest-native] "${option}" must be a non-negative safe integer.`);
62
- }
63
- function validateOptions(options) {
64
- if (options.engine !== void 0 && options.engine !== "auto" && options.engine !== "mock" && options.engine !== "native") throw new TypeError(`[vitest-native] "engine" must be "auto", "mock", or "native".`);
65
- if (options.platform !== void 0 && options.platform !== "ios" && options.platform !== "android") throw new TypeError(`[vitest-native] "platform" must be "ios" or "android".`);
66
- if (options.diagnostics !== void 0 && typeof options.diagnostics !== "boolean") throw new TypeError(`[vitest-native] "diagnostics" must be a boolean.`);
67
- if (options.assetExts !== void 0) assertStringArray(options.assetExts, "assetExts");
68
- if (options.transform !== void 0) assertStringArray(options.transform, "transform");
69
- if (options.presets !== void 0 && !Array.isArray(options.presets)) throw new TypeError(`[vitest-native] "presets" must be an array.`);
70
- if (options.mocks !== void 0 && (options.mocks === null || Array.isArray(options.mocks) || typeof options.mocks !== "object")) throw new TypeError(`[vitest-native] "mocks" must be a plain object.`);
71
- const hotRuntime = options.hotRuntime;
72
- if (hotRuntime === void 0 || typeof hotRuntime === "boolean") return;
73
- if (hotRuntime === null || Array.isArray(hotRuntime) || typeof hotRuntime !== "object") throw new TypeError(`[vitest-native] "hotRuntime" must be a boolean or an options object.`);
74
- const hotOptions = hotRuntime;
75
- for (const key of Object.keys(hotOptions)) if (!KNOWN_HOT_RUNTIME_OPTIONS.includes(key)) throw new TypeError(`[vitest-native] Unknown hotRuntime option "${key}".`);
76
- if (hotOptions.recycleAfterFiles !== void 0) assertNonNegativeInteger(hotOptions.recycleAfterFiles, "hotRuntime.recycleAfterFiles");
77
- if (hotOptions.memoryLimit !== void 0) assertNonNegativeInteger(hotOptions.memoryLimit, "hotRuntime.memoryLimit");
78
- if (hotOptions.preserveGlobals !== void 0) assertStringArray(hotOptions.preserveGlobals, "hotRuntime.preserveGlobals");
79
- }
80
- function satisfiesMinimum(version, minimum) {
81
- const parse = (v) => v.replace(/^[^0-9]*/, "").split(".").map(Number);
82
- const [aMaj, aMin = 0, aPat = 0] = parse(version);
83
- const [bMaj, bMin = 0, bPat = 0] = parse(minimum);
84
- if (aMaj !== bMaj) return aMaj > bMaj;
85
- if (aMin !== bMin) return aMin > bMin;
86
- return aPat >= bPat;
87
- }
88
- function validatePeerDependency(pkgName, minimumVersion, projectRoot, maximumMajorExclusive, minimumByMajor) {
89
- const req = createRequire(path.join(projectRoot, "package.json"));
90
- try {
91
- const { version } = req(req.resolve(`${pkgName}/package.json`));
92
- const major = Number(version.replace(/^[^0-9]*/, "").split(".")[0]);
93
- const requiredMinimum = minimumByMajor?.[major] ?? minimumVersion;
94
- if (!satisfiesMinimum(version, requiredMinimum)) return `vitest-native requires ${pkgName} >= ${requiredMinimum} for ${major}.x, but found ${version}. Please upgrade.`;
95
- if (maximumMajorExclusive !== void 0 && major >= maximumMajorExclusive) return `vitest-native supports ${pkgName} >= ${minimumVersion} and < ${maximumMajorExclusive}, but found ${version}.`;
96
- return null;
97
- } catch {
98
- return `vitest-native requires ${pkgName} >= ${minimumVersion}, but it was not found. Please install it.`;
99
- }
100
- }
101
- function warnUnknownOptions(options) {
102
- for (const key of Object.keys(options)) if (!KNOWN_OPTIONS.includes(key)) {
103
- const suggestion = findClosest(key, KNOWN_OPTIONS);
104
- const hint = suggestion ? ` Did you mean '${suggestion}'?` : "";
105
- console.warn(`[vitest-native] Unknown option '${key}'.${hint}`);
106
- }
107
- }
108
- function findClosest(input, candidates) {
109
- let best = null;
110
- let bestDist = Infinity;
111
- for (const c of candidates) {
112
- const d = levenshtein(input.toLowerCase(), c.toLowerCase());
113
- if (d < bestDist && d <= 3) {
114
- bestDist = d;
115
- best = c;
116
- }
117
- }
118
- return best;
119
- }
120
- function levenshtein(a, b) {
121
- const m = a.length;
122
- const n = b.length;
123
- const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
124
- for (let i = 0; i <= m; i++) dp[i][0] = i;
125
- for (let j = 0; j <= n; j++) dp[0][j] = j;
126
- for (let i = 1; i <= m; i++) for (let j = 1; j <= n; j++) dp[i][j] = a[i - 1] === b[j - 1] ? dp[i - 1][j - 1] : 1 + Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]);
127
- return dp[m][n];
128
- }
129
- //#endregion
130
42
  //#region src/native/apply.ts
131
43
  /**
132
44
  * Vite/Vitest config fragment for the native engine. RN is externalized so it
@@ -137,14 +49,53 @@ function levenshtein(a, b) {
137
49
  function escapeRe(s) {
138
50
  return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
139
51
  }
140
- function nativeEngineConfig(setupFilePath, env, extensions, transformPkgs = [], hot, jsxTransform = { esbuild: { jsx: "automatic" } }) {
141
- const extraExternal = transformPkgs.map((p) => new RegExp(`[\\\\/]${escapeRe(p)}[\\\\/]`));
52
+ /**
53
+ * The on-disk directory a package resolves to, or null. Used alongside the
54
+ * node_modules-anchored patterns so workspace and `file:` dependencies — which
55
+ * resolve to a real path with no node_modules segment — are matched too.
56
+ */
57
+ function resolvePackageDir(name, projectRoot) {
58
+ try {
59
+ const req = createRequire(path.join(projectRoot, "package.json"));
60
+ return path.dirname(req.resolve(`${name}/package.json`));
61
+ } catch {
62
+ return null;
63
+ }
64
+ }
65
+ function nativeEngineConfig(setupFilePath, env, extensions, transformPkgs = [], hot, jsxTransform = { esbuild: { jsx: "automatic" } }, userPool, inlinePkgs = [], projectRoot = process.cwd()) {
66
+ const extraExternal = transformPkgs.flatMap((p) => {
67
+ const patterns = [new RegExp(`[\\\\/]node_modules[\\\\/]${escapeRe(p)}[\\\\/]`)];
68
+ const dir = resolvePackageDir(p, projectRoot);
69
+ if (dir) patterns.push(new RegExp(`^${escapeRe(dir.replace(/\\/g, "/"))}[\\\\/]`));
70
+ return patterns;
71
+ });
72
+ const ecosystemInline = inlinePkgs.flatMap((p) => {
73
+ const patterns = [new RegExp(`[\\\\/]node_modules[\\\\/]${escapeRe(p)}[\\\\/]`)];
74
+ const dir = resolvePackageDir(p, projectRoot);
75
+ if (dir) patterns.push(new RegExp(`^${escapeRe(dir.replace(/\\/g, "/"))}[\\\\/]`));
76
+ return patterns;
77
+ });
142
78
  const fullEnv = { ...env };
143
79
  if (transformPkgs.length > 0) fullEnv.VITEST_NATIVE_TRANSFORM = JSON.stringify(transformPkgs);
144
80
  return {
145
81
  ...jsxTransform,
82
+ ssr: { resolve: {
83
+ conditions: ["react-native"],
84
+ mainFields: [
85
+ "react-native",
86
+ "module",
87
+ "jsnext:main",
88
+ "jsnext"
89
+ ]
90
+ } },
146
91
  resolve: {
147
92
  conditions: ["react-native"],
93
+ mainFields: [
94
+ "react-native",
95
+ "module",
96
+ "jsnext:main",
97
+ "jsnext"
98
+ ],
148
99
  extensions,
149
100
  dedupe: [
150
101
  "react",
@@ -160,56 +111,18 @@ function nativeEngineConfig(setupFilePath, env, extensions, transformPkgs = [],
160
111
  pool: hot.pool,
161
112
  isolate: false,
162
113
  runner: hot.runnerPath
163
- } : { pool: "threads" },
164
- server: { deps: { external: [
165
- /[\\/]node_modules[\\/]react-native[\\/]/,
166
- /[\\/]node_modules[\\/]@react-native[\\/]/,
167
- ...extraExternal
168
- ] } }
114
+ } : { pool: userPool ?? "threads" },
115
+ server: { deps: {
116
+ external: [
117
+ /[\\/]node_modules[\\/]react-native[\\/]/,
118
+ /[\\/]node_modules[\\/]@react-native[\\/]/,
119
+ ...extraExternal
120
+ ],
121
+ ...ecosystemInline.length > 0 ? { inline: ecosystemInline } : {}
122
+ } }
169
123
  }
170
124
  };
171
125
  }
172
- /** Can this project run the native engine? (Both transform deps resolvable.) */
173
- function isNativeCapable(projectRoot) {
174
- try {
175
- const req = createRequire(path.join(projectRoot, "package.json"));
176
- req.resolve("@react-native/babel-preset");
177
- req.resolve("@babel/core");
178
- return true;
179
- } catch {
180
- return false;
181
- }
182
- }
183
- /** Resolve the concrete engine for a run. Pure; never throws. */
184
- function detectEngine(requested, projectRoot, opts) {
185
- const nativeAvailable = isNativeCapable(projectRoot);
186
- if (requested === "native") return {
187
- engine: "native",
188
- nativeAvailable,
189
- notice: null
190
- };
191
- if (requested === "mock") return {
192
- engine: "mock",
193
- nativeAvailable,
194
- notice: null
195
- };
196
- const prefersNative = opts?.autoPrefersNative ?? true;
197
- if (prefersNative && nativeAvailable) return {
198
- engine: "native",
199
- nativeAvailable,
200
- notice: null
201
- };
202
- if (prefersNative) return {
203
- engine: "mock",
204
- nativeAvailable: false,
205
- 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."
206
- };
207
- return {
208
- engine: "mock",
209
- nativeAvailable,
210
- notice: null
211
- };
212
- }
213
126
  //#endregion
214
127
  //#region src/plugin.ts
215
128
  const DEFAULT_ASSET_EXTS = [
@@ -270,11 +183,91 @@ function resolvePackageVersion(packageName, projectRoot) {
270
183
  return null;
271
184
  }
272
185
  }
186
+ /**
187
+ * One line, once per process, stating which engine this run actually uses.
188
+ * Tests pass either way; a team that believes it's exercising real React Native
189
+ * while running the mock (or vice versa) must be able to see it in every log.
190
+ * Guarded via globalThis (like the require-hook install) so workspace setups
191
+ * that call config() per project print it once.
192
+ *
193
+ * Written to stderr: this is the plugin's only unconditional output, and stdout
194
+ * must stay parseable for pipelines like `vitest --reporter=json > results.json`.
195
+ */
196
+ function printEngineBanner(engine, platform, projectRoot) {
197
+ const g = globalThis;
198
+ if (g.__vitest_native_banner_printed) return;
199
+ g.__vitest_native_banner_printed = true;
200
+ if (engine === "native") {
201
+ const rn = resolvePackageVersion("react-native", projectRoot);
202
+ console.error(`[vitest-native] engine: native — real react-native${rn ? `@${rn}` : ""} (platform ${platform})`);
203
+ } else console.error(`[vitest-native] engine: mock — React Native reimplementation, cross-checked against real RN (platform ${platform})`);
204
+ }
273
205
  function getJsxTransformConfig(projectRoot) {
274
206
  const viteVersion = resolvePackageVersion("vite", projectRoot);
275
207
  return Number(viteVersion?.split(".")[0]) >= 8 ? { oxc: { jsx: { runtime: "automatic" } } } : { esbuild: { jsx: "automatic" } };
276
208
  }
277
209
  /**
210
+ * The names React Native's index exports.
211
+ *
212
+ * They cannot be read with a normal import: the index is Flow source, and its
213
+ * exports are lazy getters that neither a bundler nor cjs-module-lexer can see.
214
+ * They also cannot be read by requiring the module here — that would execute React
215
+ * Native inside the Vite process, before any of the engine's globals exist.
216
+ *
217
+ * So they are parsed out of the `module.exports = { … }` object literal, whose
218
+ * members sit at one indentation level. React Native uses three member shapes
219
+ * there: lazy getters (`get View() {`), method shorthand
220
+ * (`unstable_batchedUpdates<T>(fn) {`), and plain properties (`Systrace: …`).
221
+ * A name missed here surfaces immediately as "does not provide an export named X"
222
+ * rather than silently, and the facade's export surface is asserted against the
223
+ * real module in the native suite, across every React Native version in CI.
224
+ */
225
+ function parseReactNativeExports(indexSource) {
226
+ const start = indexSource.indexOf("module.exports = {");
227
+ if (start === -1) return [];
228
+ const body = indexSource.slice(start);
229
+ const names = /* @__PURE__ */ new Set();
230
+ for (const match of body.matchAll(/^ {2}(?:get\s+)?([A-Za-z_$][\w$]*)\s*(?:<[^>]*>)?\s*[(:,]/gm)) {
231
+ const name = match[1];
232
+ if (name !== "default" && name !== "__esModule" && name !== "get") names.add(name);
233
+ }
234
+ return [...names];
235
+ }
236
+ /**
237
+ * Build (or reuse) the precompiled React Native registry for a project.
238
+ *
239
+ * The builder ships as runtime `.mjs` next to this file (it is also imported by the
240
+ * native setup file, which Node loads directly), so it is reached through a computed
241
+ * dynamic import rather than a static one — a static specifier would bundle a second
242
+ * copy into the plugin entry. Returns the registry path, or null when one could not
243
+ * be produced, in which case the engine keeps loading RN file by file.
244
+ */
245
+ async function buildRegistryFor(options) {
246
+ try {
247
+ const dir = path.dirname(fileURLToPath(import.meta.url));
248
+ return (await import(pathToFileURL(path.resolve(dir, "native/registry.mjs")).href)).buildRegistry(options);
249
+ } catch (error) {
250
+ if (options.diagnostics) console.warn(`[vitest-native] could not precompile the React Native registry (${error?.message}); using per-file module loading.`);
251
+ return null;
252
+ }
253
+ }
254
+ /**
255
+ * Compile one inlined ecosystem file with the project's React Native Babel preset.
256
+ *
257
+ * The transformer ships as runtime `.mjs` (Node's loader hooks use it too), so it is
258
+ * loaded through a computed path rather than a static import, and synchronously —
259
+ * Vite's transform hook may be sync and the module is already resident by the time
260
+ * any file reaches this point.
261
+ */
262
+ let ecosystemTransformer = null;
263
+ function transformEcosystem(file, code, projectRoot, platform) {
264
+ if (!ecosystemTransformer) {
265
+ const dir = path.dirname(fileURLToPath(import.meta.url));
266
+ ecosystemTransformer = createRequire(import.meta.url)(path.resolve(dir, "native/transform.mjs")).transformRN;
267
+ }
268
+ return ecosystemTransformer(file, code, projectRoot, platform);
269
+ }
270
+ /**
278
271
  * Vite 6/7 and Vite 8 expose mutually exclusive JSX config types:
279
272
  * `esbuild.jsx` before Vite 8 and `oxc.jsx` from Vite 8 onward. The runtime
280
273
  * version check above guarantees that only the matching shape is returned,
@@ -411,6 +404,54 @@ const RN_EXPORT_NAMES = [
411
404
  "NativeDialogManagerAndroid",
412
405
  "usePressability"
413
406
  ];
407
+ /**
408
+ * A file inside a React Native ecosystem package under node_modules — one whose
409
+ * package NAME begins with `react-native` (with or without a scope, so
410
+ * `@shopify/react-native-skia` counts), or whose scope begins with `@react-native`.
411
+ *
412
+ * The name must BEGIN with it, which is what separates this from the substring test
413
+ * it replaced: `eslint-plugin-react-native` and a project directory called
414
+ * `react-native-app` both contain the words without being React Native packages.
415
+ */
416
+ const RN_ECOSYSTEM_PATH = /[\\/]node_modules[\\/](?:@react-native[^\\/]*[\\/][^\\/]+|(?:@[^\\/]+[\\/])?react-native[^\\/]*)[\\/]/;
417
+ /** Fast membership check for leaf-name lookups on subpath imports. */
418
+ const RN_EXPORT_NAME_SET = new Set(RN_EXPORT_NAMES);
419
+ /**
420
+ * The bare package name of an import specifier ("@scope/pkg/sub" → "@scope/pkg",
421
+ * "pkg/sub" → "pkg"). Mirrors native/match.mjs for the Vite-graph side.
422
+ */
423
+ function packageNameOf(specifier) {
424
+ if (specifier.startsWith("@")) {
425
+ const [scope, name] = specifier.split("/");
426
+ return name ? `${scope}/${name}` : specifier;
427
+ }
428
+ return specifier.split("/")[0];
429
+ }
430
+ /**
431
+ * The leaf module name a subpath import points at ("pkg/lib/Swipeable" or
432
+ * "react-native/Libraries/Utilities/Platform.ios.js" → "Platform"), used to pick
433
+ * the matching export off the mock. Mirrors native/match.mjs.
434
+ */
435
+ function subpathLeafOf(specifier) {
436
+ const base = specifier.split("/").pop();
437
+ if (!base) return null;
438
+ return base.split(".")[0] || null;
439
+ }
440
+ /**
441
+ * Deep entries of preset packages that are deliberately Node-safe and must NOT
442
+ * be shadowed (test utilities and tooling entry points). Mirrors
443
+ * native/match.mjs.
444
+ */
445
+ const UTILITY_SUBPATH_LEAVES = new Set([
446
+ "jest-utils",
447
+ "jestSetup",
448
+ "mock",
449
+ "plugin"
450
+ ]);
451
+ function isUtilitySubpath(specifier) {
452
+ const leaf = subpathLeafOf(specifier);
453
+ return leaf !== null && UTILITY_SUBPATH_LEAVES.has(leaf);
454
+ }
414
455
  /** Check if a value (or any nested value) contains functions. */
415
456
  function containsFunctions(value, visited = /* @__PURE__ */ new WeakSet()) {
416
457
  if (typeof value === "function") return true;
@@ -437,6 +478,11 @@ function reactNative(options) {
437
478
  const presetModules = /* @__PURE__ */ new Map();
438
479
  const presetExportNames = /* @__PURE__ */ new Map();
439
480
  let assetPattern;
481
+ let realRnPackageJson;
482
+ let rnFacadeExports = null;
483
+ let rnFacadeRoot = "";
484
+ let ecosystemPattern = null;
485
+ let ecosystemRoot = "";
440
486
  const resolveCache = /* @__PURE__ */ new Map();
441
487
  const virtualCodeCache = /* @__PURE__ */ new Map();
442
488
  const thisDir = path.dirname(fileURLToPath(import.meta.url));
@@ -457,6 +503,13 @@ function reactNative(options) {
457
503
  const hotRecycle = typeof hotRuntimeOpt === "object" ? hotRuntimeOpt : {};
458
504
  let engine = requestedEngine === "native" ? "native" : "mock";
459
505
  const extensions = getPlatformExtensions(platform);
506
+ const resolvePresetId = (source) => {
507
+ if (presetModules.has(source)) return `\0virtual:preset:${source}`;
508
+ if (!assetPattern) return void 0;
509
+ if (source.endsWith(".json") || assetPattern.test(source) || isUtilitySubpath(source)) return;
510
+ const pkg = packageNameOf(source);
511
+ if (pkg !== source && presetModules.has(pkg)) return `\0virtual:preset:${source}`;
512
+ };
460
513
  return {
461
514
  name: "vitest-native",
462
515
  enforce: "pre",
@@ -465,7 +518,9 @@ function reactNative(options) {
465
518
  const jsxTransform = getJsxTransformConfig(resolvedRoot);
466
519
  const decision = detectEngine(requestedEngine, resolvedRoot);
467
520
  engine = decision.engine;
468
- if (decision.notice) console.log(decision.notice);
521
+ if (engine === "native" && !decision.nativeAvailable) throw new Error(`[vitest-native] engine:'native' requires '@react-native/babel-preset' and '@babel/core' to resolve from ${resolvedRoot}. Install them as devDependencies (React Native projects ship them by default):\n\n npm install -D @react-native/babel-preset @babel/core\n\nOr set engine:'mock' to run without a React Native install.`);
522
+ if (decision.notice) console.warn(decision.notice);
523
+ printEngineBanner(engine, platform, resolvedRoot);
469
524
  const env = {
470
525
  VITEST_NATIVE_PLATFORM: platform,
471
526
  VITEST_NATIVE_DIAGNOSTICS: String(diagnostics),
@@ -473,7 +528,8 @@ function reactNative(options) {
473
528
  };
474
529
  const reactNativeVersion = resolvePackageVersion("react-native", resolvedRoot);
475
530
  if (reactNativeVersion) env.VITEST_NATIVE_RN_VERSION = reactNativeVersion;
476
- env.VITEST_NATIVE_ASSET_EXTS = JSON.stringify([...DEFAULT_ASSET_EXTS, ...(options?.assetExts ?? []).map((e) => e.replace(/^\./, ""))]);
531
+ const assetExtList = [...DEFAULT_ASSET_EXTS, ...(options?.assetExts ?? []).map((e) => e.replace(/^\./, ""))];
532
+ env.VITEST_NATIVE_ASSET_EXTS = JSON.stringify(assetExtList);
477
533
  if (hotRuntime && hotRecycle.preserveGlobals?.length) env.VITEST_NATIVE_HOT_PRESERVE_GLOBALS = JSON.stringify(hotRecycle.preserveGlobals);
478
534
  if (engine === "native") {
479
535
  if (options?.mocks && Object.keys(options.mocks).length > 0) throw new Error("[vitest-native] 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'.");
@@ -484,24 +540,63 @@ function reactNative(options) {
484
540
  for (const p of options.presets) if (p.config && Object.keys(p.config).length > 0) presetConfig[p.name] = p.config;
485
541
  if (Object.keys(presetConfig).length > 0) env.VITEST_NATIVE_PRESET_CONFIG = JSON.stringify(presetConfig);
486
542
  }
487
- return asCompatibleViteConfig(nativeEngineConfig(nativeSetupPath, env, extensions, transformPkgs, hotRuntime ? {
488
- pool: (await import("./pool-B7LBfcMQ.mjs")).nativePool({
489
- workerEntry: nativeWorkerPath,
490
- recycleAfterFiles: hotRecycle.recycleAfterFiles,
491
- memoryLimit: hotRecycle.memoryLimit,
492
- diagnostics
493
- }),
494
- runnerPath: nativeRunnerPath
495
- } : void 0, jsxTransform));
543
+ const ecosystem = detectEcosystemPackages(resolvedRoot, transformPkgs);
544
+ if (ecosystem.length > 0) {
545
+ ecosystemRoot = resolvedRoot;
546
+ ecosystemPattern = new RegExp(`[\\\\/]node_modules[\\\\/](?:${ecosystem.map((p) => p.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})[\\\\/]`);
547
+ if (diagnostics) console.log(`[vitest-native] inlining React Native packages: ${ecosystem.join(", ")}`);
548
+ }
549
+ const registryFile = await buildRegistryFor({
550
+ projectRoot: resolvedRoot,
551
+ platform,
552
+ reactNativeVersion: reactNativeVersion ?? "0.0.0",
553
+ assetExts: assetExtList,
554
+ diagnostics
555
+ });
556
+ if (registryFile) env.VITEST_NATIVE_RN_REGISTRY = registryFile;
557
+ let hot;
558
+ if (hotRuntime) {
559
+ const { nativePool, defaultHotMemoryLimit } = await import("./pool-CJmjRgsB.mjs");
560
+ const memoryLimit = hotRecycle.memoryLimit ?? (hotRecycle.recycleAfterFiles == null ? defaultHotMemoryLimit() : void 0);
561
+ hot = {
562
+ pool: nativePool({
563
+ workerEntry: nativeWorkerPath,
564
+ projectRoot: resolvedRoot,
565
+ recycleAfterFiles: hotRecycle.recycleAfterFiles,
566
+ memoryLimit,
567
+ diagnostics
568
+ }),
569
+ runnerPath: nativeRunnerPath
570
+ };
571
+ }
572
+ const userPool = userConfig.test?.pool;
573
+ if (userPool === "vmThreads" || userPool === "vmForks") throw new Error(`[vitest-native] engine:'native' cannot run on the '${userPool}' 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.`);
574
+ if (hot && userPool) console.warn(`[vitest-native] 'hotRuntime' supplies its own pool, overriding the configured pool '${typeof userPool === "string" ? userPool : "(custom)"}'.`);
575
+ return asCompatibleViteConfig(nativeEngineConfig(nativeSetupPath, env, extensions, transformPkgs, hot, jsxTransform, userPool, ecosystem, resolvedRoot));
496
576
  }
497
577
  if (hotRuntime) console.warn(`[vitest-native] 'hotRuntime' only applies to engine:'native' (resolved engine: '${engine}'); ignoring.`);
498
578
  if (options?.mocks && Object.keys(options.mocks).length > 0) env.VITEST_NATIVE_MOCKS = JSON.stringify(options.mocks);
499
579
  if (options?.presets) env.VITEST_NATIVE_PRESET_NAMES = JSON.stringify(options.presets.map((p) => p.name));
500
580
  return asCompatibleViteConfig({
501
581
  ...jsxTransform,
582
+ ssr: { resolve: {
583
+ conditions: ["react-native"],
584
+ mainFields: [
585
+ "react-native",
586
+ "module",
587
+ "jsnext:main",
588
+ "jsnext"
589
+ ]
590
+ } },
502
591
  resolve: {
503
592
  extensions,
504
593
  conditions: ["react-native"],
594
+ mainFields: [
595
+ "react-native",
596
+ "module",
597
+ "jsnext:main",
598
+ "jsnext"
599
+ ],
505
600
  dedupe: [
506
601
  "react",
507
602
  "react-test-renderer",
@@ -516,29 +611,8 @@ function reactNative(options) {
516
611
  });
517
612
  },
518
613
  async configResolved(config) {
519
- const peers = [
520
- {
521
- name: "vitest",
522
- minimum: "4.0.0",
523
- maximumMajor: 5
524
- },
525
- {
526
- name: "vite",
527
- minimum: "6.4.2",
528
- maximumMajor: 9,
529
- minimumByMajor: {
530
- 6: "6.4.2",
531
- 7: "7.3.2",
532
- 8: "8.0.5"
533
- }
534
- },
535
- {
536
- name: "react",
537
- minimum: "18.0.0"
538
- }
539
- ];
540
614
  const peerErrors = [];
541
- for (const { name, minimum, maximumMajor, minimumByMajor } of peers) {
615
+ for (const { name, minimum, maximumMajor, minimumByMajor } of PEER_REQUIREMENTS) {
542
616
  const error = validatePeerDependency(name, minimum, config.root, maximumMajor, minimumByMajor);
543
617
  if (error) peerErrors.push(error);
544
618
  }
@@ -546,21 +620,39 @@ function reactNative(options) {
546
620
  const rntlError = validatePeerDependency("@testing-library/react-native", "12.0.0", config.root, 15);
547
621
  if (rntlError && !rntlError.includes("not found")) console.warn(`[vitest-native] ${rntlError}`);
548
622
  resolved = await resolveOptions(options, config.root);
623
+ try {
624
+ realRnPackageJson = createRequire(path.join(config.root, "package.json")).resolve("react-native/package.json");
625
+ } catch {}
549
626
  resolved.engine = engine;
550
627
  for (const preset of resolved.presets) for (const [moduleName, presetModule] of Object.entries(preset.modules)) {
551
628
  presetModules.set(moduleName, presetModule.factory);
552
629
  presetExportNames.set(moduleName, presetModule.exports);
553
630
  }
554
- assetPattern = new RegExp(`\\.(${resolved.assetExts.join("|")})$`);
631
+ if (engine === "native") {
632
+ rnFacadeRoot = config.root;
633
+ try {
634
+ const indexPath = createRequire(path.join(config.root, "package.json")).resolve("react-native");
635
+ const names = parseReactNativeExports(fs.readFileSync(indexPath, "utf8"));
636
+ rnFacadeExports = names.length > 0 ? names : null;
637
+ } catch {
638
+ rnFacadeExports = null;
639
+ }
640
+ }
641
+ const escaped = resolved.assetExts.map((e) => e.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
642
+ assetPattern = new RegExp(`\\.(${escaped.join("|")})$`, "i");
555
643
  },
556
644
  resolveId(source, importer) {
557
645
  if (engine === "native") {
558
- if (presetModules.has(source)) return `\0virtual:preset:${source}`;
559
- return;
646
+ if (source === "react-native" && rnFacadeExports !== null) return "\0virtual:rn-facade";
647
+ return resolvePresetId(source);
560
648
  }
561
649
  if (source === "react-native") return "\0virtual:react-native";
562
- if (source.startsWith("react-native/")) return `\0virtual:rn-subpath:${source}`;
563
- if (presetModules.has(source)) return `\0virtual:preset:${source}`;
650
+ if (source.startsWith("react-native/")) {
651
+ if (source === "react-native/package.json" && realRnPackageJson) return realRnPackageJson;
652
+ return `\0virtual:rn-subpath:${source}`;
653
+ }
654
+ const presetId = resolvePresetId(source);
655
+ if (presetId) return presetId;
564
656
  if (importer && importer.includes("node_modules") && source.startsWith(".") && !path.extname(source)) {
565
657
  const cacheKey = `${importer}\0${source}`;
566
658
  const cached = resolveCache.get(cacheKey);
@@ -585,46 +677,99 @@ function reactNative(options) {
585
677
  }
586
678
  },
587
679
  load(id) {
680
+ if (id === "\0virtual:rn-facade" && rnFacadeExports !== null) {
681
+ const cached = virtualCodeCache.get(id);
682
+ if (cached) return cached;
683
+ const code = [
684
+ `import { createRequire } from "node:module";`,
685
+ `const _rn = createRequire(${JSON.stringify(path.join(rnFacadeRoot, "package.json"))})("react-native");`,
686
+ ...rnFacadeExports.map((n) => `export const ${n} = _rn[${JSON.stringify(n)}];`),
687
+ `export default _rn;`
688
+ ].join("\n");
689
+ virtualCodeCache.set(id, code);
690
+ return code;
691
+ }
588
692
  if (id.startsWith("\0virtual:preset:")) {
589
693
  const cached = virtualCodeCache.get(id);
590
694
  if (cached) return cached;
591
- const moduleName = id.slice(16);
592
- const exportNames = presetExportNames.get(moduleName) || [];
695
+ const specifier = id.slice(16);
696
+ const pkg = packageNameOf(specifier);
697
+ const exportNames = presetExportNames.get(pkg) || [];
698
+ const leaf = specifier === pkg ? null : subpathLeafOf(specifier);
699
+ const fallback = `('default' in _m ? _m['default'] : _m)`;
593
700
  const code = [
594
- `const _m = (globalThis.__vitest_native_preset_mocks || {})['${moduleName}'] || {};`,
701
+ `const _m = (globalThis.__vitest_native_preset_mocks || {})[${JSON.stringify(pkg)}] || {};`,
595
702
  ...exportNames.map((n) => `export const ${n} = _m['${n}'];`),
596
- `export default ('default' in _m ? _m['default'] : _m);`
703
+ ...leaf ? [
704
+ `const _hit = ${JSON.stringify(leaf)} in _m;`,
705
+ `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.`)});`,
706
+ `export default (_hit ? _m[${JSON.stringify(leaf)}] : ${fallback});`
707
+ ] : [`export default ${fallback};`]
597
708
  ].join("\n");
598
709
  virtualCodeCache.set(id, code);
599
710
  return code;
600
711
  }
601
712
  const fsPath = stripFsPrefix(id);
602
- if (assetPattern.test(fsPath)) return `export default "${fsPath.split("/").pop() ?? fsPath}";`;
713
+ if (assetPattern.test(fsPath)) {
714
+ const basename = fsPath.split("/").pop() ?? fsPath;
715
+ return `export default ${JSON.stringify(basename)};`;
716
+ }
603
717
  if (engine === "native") return void 0;
604
- if (id === "\0virtual:react-native") return "export default {};";
605
- if (id.startsWith("\0virtual:rn-subpath:")) {
606
- let code = virtualCodeCache.get("\0rn-subpath");
718
+ if (id === "\0virtual:react-native") {
719
+ const cacheKey = "\0rn-root";
720
+ let code = virtualCodeCache.get(cacheKey);
607
721
  if (!code) {
608
722
  code = [
609
723
  `const _rn = globalThis.__vitest_native_mock || {};`,
610
724
  ...RN_EXPORT_NAMES.map((n) => `export const ${n} = _rn['${n}'];`),
611
725
  `export default _rn;`
612
726
  ].join("\n");
613
- virtualCodeCache.set("\0rn-subpath", code);
727
+ virtualCodeCache.set(cacheKey, code);
728
+ }
729
+ return code;
730
+ }
731
+ if (id.startsWith("\0virtual:rn-subpath:")) {
732
+ const leaf = subpathLeafOf(id.slice(20));
733
+ const known = leaf && RN_EXPORT_NAME_SET.has(leaf) ? leaf : null;
734
+ const cacheKey = `\0rn-subpath:${known ?? ""}`;
735
+ let code = virtualCodeCache.get(cacheKey);
736
+ if (!code) {
737
+ code = [
738
+ `const _rn = globalThis.__vitest_native_mock || {};`,
739
+ ...RN_EXPORT_NAMES.map((n) => `export const ${n} = _rn['${n}'];`),
740
+ known ? `export default _rn[${JSON.stringify(known)}];` : `export default _rn;`
741
+ ].join("\n");
742
+ virtualCodeCache.set(cacheKey, code);
614
743
  }
615
744
  return code;
616
745
  }
617
746
  },
618
747
  transform(code, id) {
619
- if (engine === "native") return void 0;
620
- if (!id.includes("node_modules")) return void 0;
621
- if (!id.includes("react-native") || !id.endsWith(".js")) return void 0;
748
+ if (engine === "native") {
749
+ if (!ecosystemPattern || !ecosystemPattern.test(id)) return void 0;
750
+ if (!/\.[cm]?[jt]sx?$/.test(id.split("?")[0])) return void 0;
751
+ try {
752
+ return {
753
+ code: transformEcosystem(id, code, ecosystemRoot, platform),
754
+ map: null
755
+ };
756
+ } catch (error) {
757
+ if (diagnostics) console.warn(`[vitest-native] could not compile inlined ${id} (${error?.message}); serving it untouched.`);
758
+ return;
759
+ }
760
+ }
761
+ if (!RN_ECOSYSTEM_PATH.test(id) || !id.endsWith(".js")) return void 0;
622
762
  if (!code.includes("@flow")) return void 0;
623
- const stripped = flowRemoveTypes(code, { all: true });
624
- return {
625
- code: stripped.toString(),
626
- map: stripped.generateMap()
627
- };
763
+ try {
764
+ const stripped = flowRemoveTypes(code, { all: true });
765
+ return {
766
+ code: stripped.toString(),
767
+ map: stripped.generateMap()
768
+ };
769
+ } catch (e) {
770
+ console.warn(`[vitest-native] Flow strip skipped for ${id} (parse failed: ${e?.message}); serving the file untouched.`);
771
+ return;
772
+ }
628
773
  }
629
774
  };
630
775
  }