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