vitest-native 0.9.0 → 0.11.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 (64) hide show
  1. package/CHANGELOG.md +921 -0
  2. package/README.md +33 -1
  3. package/dist/cli.cjs +185 -31
  4. package/dist/cli.mjs +182 -28
  5. package/dist/ecosystem-BJzJU3Cf.cjs +568 -0
  6. package/dist/ecosystem-C4qT_vl3.mjs +506 -0
  7. package/dist/errors-B3lJK46O.cjs +75 -0
  8. package/dist/errors-CxoBUfVJ.mjs +64 -0
  9. package/dist/errors.d.mts +46 -0
  10. package/dist/errors.mjs +78 -0
  11. package/dist/helpers.cjs +6 -23
  12. package/dist/helpers.d.cts +0 -6
  13. package/dist/helpers.d.mts +0 -6
  14. package/dist/helpers.mjs +6 -23
  15. package/dist/{index-CEgRDdhd.d.cts → index-CrMeE8rd.d.mts} +14 -9
  16. package/dist/{index-j-0tueBr.d.mts → index-DIMbjH8R.d.cts} +15 -7
  17. package/dist/index.d.mts +8 -7
  18. package/dist/index.mjs +307 -91
  19. package/dist/jest-compat/interop.mjs +15 -0
  20. package/dist/jest-compat/setup.mjs +102 -7
  21. package/dist/jest-compat.cjs +4 -4
  22. package/dist/jest-compat.d.cts +0 -1
  23. package/dist/jest-compat.d.mts +0 -1
  24. package/dist/jest-compat.mjs +2 -2
  25. package/dist/matchers.cjs +16 -7
  26. package/dist/matchers.mjs +16 -7
  27. package/dist/native/hooks.mjs +152 -13
  28. package/dist/native/loader.mjs +36 -11
  29. package/dist/native/match.d.mts +33 -0
  30. package/dist/native/match.mjs +94 -22
  31. package/dist/native/module-reset.mjs +63 -0
  32. package/dist/native/registry.mjs +110 -13
  33. package/dist/native/resolve.d.mts +22 -0
  34. package/dist/native/resolve.mjs +21 -13
  35. package/dist/native/runner.mjs +21 -0
  36. package/dist/native/setup.mjs +4 -2
  37. package/dist/native/transform.mjs +108 -3
  38. package/dist/native/worker.mjs +59 -16
  39. package/dist/{pool-DzsEo9vv.cjs → pool-BU-1ecIF.cjs} +7 -6
  40. package/dist/{pool-CJmjRgsB.mjs → pool-Bcxn9a3I.mjs} +4 -3
  41. package/dist/{preset-map-CG4FMtsl.cjs → preset-map-BoG19dLa.cjs} +1 -1
  42. package/dist/{preset-map-CNsZKfvu.mjs → preset-map-DuX0ocdn.mjs} +1 -1
  43. package/dist/{presets-C4faM3ds.cjs → presets-CwO_c4aL.cjs} +224 -55
  44. package/dist/{presets-CuDrNA_W.mjs → presets-IStcJEOa.mjs} +216 -53
  45. package/dist/presets.d.mts +2 -2
  46. package/dist/presets.mjs +2 -2
  47. package/dist/rntl-matchers.d.ts +35 -0
  48. package/dist/{chunk-CjcI7cDX.mjs → rolldown-runtime-BhDjJH2R.mjs} +1 -1
  49. package/dist/{chunk-CZWwpsFl.cjs → rolldown-runtime-C0BPl7ul.cjs} +1 -1
  50. package/dist/serializer.cjs +34 -4
  51. package/dist/serializer.mjs +34 -4
  52. package/dist/setup.d.mts +1 -1
  53. package/dist/setup.mjs +237 -74
  54. package/docs/release-readiness.md +22 -5
  55. package/docs/versioning.md +133 -0
  56. package/package.json +38 -46
  57. package/dist/ecosystem-BIWaVwYL.cjs +0 -294
  58. package/dist/ecosystem-EFtHnKS9.mjs +0 -256
  59. package/dist/index.cjs +0 -788
  60. package/dist/index.d.cts +0 -14
  61. package/dist/presets.cjs +0 -18
  62. package/dist/presets.d.cts +0 -2
  63. package/dist/setup.cjs +0 -2702
  64. package/dist/setup.d.cts +0 -1
package/dist/index.mjs CHANGED
@@ -1,82 +1,75 @@
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";
1
+ import { t as VitestNativeError } from "./errors-CxoBUfVJ.mjs";
2
+ import { a as packageDirOf, c as validateOptions, i as containsPath, l as validatePeerDependency, n as detectEngine, o as packagePatterns, r as REACT_NATIVE_PATH, s as PEER_REQUIREMENTS, t as detectEcosystemPackages, u as warnUnknownOptions } from "./ecosystem-C4qT_vl3.mjs";
3
+ import { t as AUTO_DETECT_PRESETS } from "./preset-map-DuX0ocdn.mjs";
4
+ import { t as presets_exports } from "./presets-IStcJEOa.mjs";
4
5
  import { createRequire } from "node:module";
5
- import { fileURLToPath, pathToFileURL } from "node:url";
6
- import path from "node:path";
7
6
  import fs from "node:fs";
7
+ import path from "node:path";
8
+ import { fileURLToPath, pathToFileURL } from "node:url";
8
9
  import flowRemoveTypes from "flow-remove-types";
9
- //#region src/resolve.ts
10
- const PLATFORM_EXTENSIONS_IOS = [
11
- ".ios.tsx",
12
- ".ios.ts",
13
- ".ios.jsx",
14
- ".ios.js",
15
- ".native.tsx",
16
- ".native.ts",
17
- ".native.jsx",
18
- ".native.js",
19
- ".tsx",
20
- ".ts",
21
- ".jsx",
22
- ".js"
23
- ];
24
- const PLATFORM_EXTENSIONS_ANDROID = [
25
- ".android.tsx",
26
- ".android.ts",
27
- ".android.jsx",
28
- ".android.js",
29
- ".native.tsx",
30
- ".native.ts",
31
- ".native.jsx",
32
- ".native.js",
33
- ".tsx",
34
- ".ts",
35
- ".jsx",
36
- ".js"
10
+ //#region src/native/resolve.mjs
11
+ /**
12
+ * Metro's default `sourceExts`, in its order. Kept as data rather than spelled out
13
+ * per platform so the Vite graph and the Node graph cannot drift apart — both build
14
+ * their list from this one array (see `getPlatformExtensions` in ../resolve.ts).
15
+ *
16
+ * The order is load-bearing where a module has more than one variant on disk:
17
+ * Metro picks `Foo.js` over `Foo.tsx`, so this list must too, or a project with a
18
+ * compiled file beside its source tests a different file than it ships. `json` is
19
+ * a source extension to Metro, which is why `import config from './config'`
20
+ * resolves `config.json` in an app.
21
+ */
22
+ const METRO_SOURCE_EXTS = [
23
+ "js",
24
+ "jsx",
25
+ "json",
26
+ "ts",
27
+ "tsx"
37
28
  ];
38
- function getPlatformExtensions(platform) {
39
- return platform === "ios" ? PLATFORM_EXTENSIONS_IOS : PLATFORM_EXTENSIONS_ANDROID;
29
+ /**
30
+ * Metro tries every platform-suffixed variant first, then every `.native` one,
31
+ * then the bare extensions — not extension-major.
32
+ */
33
+ function extensionsFor(platform) {
34
+ const suffix = platform === "android" ? "android" : "ios";
35
+ return [
36
+ ...METRO_SOURCE_EXTS.map((e) => `.${suffix}.${e}`),
37
+ ...METRO_SOURCE_EXTS.map((e) => `.native.${e}`),
38
+ ...METRO_SOURCE_EXTS.map((e) => `.${e}`)
39
+ ];
40
40
  }
41
41
  //#endregion
42
- //#region src/native/apply.ts
42
+ //#region src/resolve.ts
43
43
  /**
44
- * Vite/Vitest config fragment for the native engine. RN is externalized so it
45
- * loads through Node's single CJS graph, where the native setup file's hooks
46
- * Flow-strip it and mock the native boundary.
44
+ * Extension search order for the Vite graph, taken from the same definition the
45
+ * Node graph uses. Vite's default list is replaced wholesale by whatever is set
46
+ * here, so anything Metro treats as a source extension has to appear — `.json`
47
+ * included, or `import config from './config'` resolves in the app and fails in
48
+ * the test.
47
49
  */
48
- /** Escape a package name for use inside a RegExp character-delimited path match. */
49
- function escapeRe(s) {
50
- return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
50
+ const PLATFORM_EXTENSIONS_IOS = extensionsFor("ios");
51
+ const PLATFORM_EXTENSIONS_ANDROID = extensionsFor("android");
52
+ function getPlatformExtensions(platform) {
53
+ return platform === "ios" ? PLATFORM_EXTENSIONS_IOS : PLATFORM_EXTENSIONS_ANDROID;
51
54
  }
55
+ //#endregion
56
+ //#region src/native/apply.ts
52
57
  /**
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.
58
+ * Files outside any installed package that Vitest may be running as an ENTRY rather
59
+ * than importing as a module: the two naming conventions test runners use.
60
+ *
61
+ * Neither is exhaustive — a project can point `test.include` anywhere — but a file
62
+ * that matches one of these is a test by convention and never library source, which
63
+ * is what makes it safe to keep out of Node's graph unconditionally.
56
64
  */
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
- });
65
+ const OUTSIDE_NODE_MODULES = String.raw`^(?!.*[\\/]node_modules[\\/])`;
66
+ const TEST_ENTRY_PATTERNS = [new RegExp(String.raw`${OUTSIDE_NODE_MODULES}.*\.(?:test|spec)\.[cm]?[jt]sx?$`), new RegExp(String.raw`${OUTSIDE_NODE_MODULES}.*[\\/]__tests__[\\/].*\.[cm]?[jt]sx?$`)];
67
+ function nativeEngineConfig(setupFilePath, env, extensions, transformPkgs = [], hot, jsxTransform = { esbuild: { jsx: "automatic" } }, userPool, inlinePkgs = [], projectRoot = process.cwd(), userInlinesEverything = false) {
68
+ const extraExternal = transformPkgs.flatMap((p) => packagePatterns(p, projectRoot));
69
+ const ecosystemExternal = inlinePkgs.flatMap((p) => packagePatterns(p, projectRoot));
70
+ const nodeTransformed = [.../* @__PURE__ */ new Set([...transformPkgs, ...inlinePkgs])];
78
71
  const fullEnv = { ...env };
79
- if (transformPkgs.length > 0) fullEnv.VITEST_NATIVE_TRANSFORM = JSON.stringify(transformPkgs);
72
+ if (nodeTransformed.length > 0) fullEnv.VITEST_NATIVE_TRANSFORM = JSON.stringify(nodeTransformed);
80
73
  return {
81
74
  ...jsxTransform,
82
75
  ssr: { resolve: {
@@ -113,12 +106,12 @@ function nativeEngineConfig(setupFilePath, env, extensions, transformPkgs = [],
113
106
  runner: hot.runnerPath
114
107
  } : { pool: userPool ?? "threads" },
115
108
  server: { deps: {
109
+ ...userInlinesEverything ? {} : { inline: TEST_ENTRY_PATTERNS },
116
110
  external: [
117
- /[\\/]node_modules[\\/]react-native[\\/]/,
118
- /[\\/]node_modules[\\/]@react-native[\\/]/,
119
- ...extraExternal
120
- ],
121
- ...ecosystemInline.length > 0 ? { inline: ecosystemInline } : {}
111
+ REACT_NATIVE_PATH,
112
+ ...extraExternal,
113
+ ...ecosystemExternal
114
+ ]
122
115
  } }
123
116
  }
124
117
  };
@@ -175,6 +168,51 @@ async function autoDetectPresets(diagnostics, projectRoot) {
175
168
  }
176
169
  return detected;
177
170
  }
171
+ /**
172
+ * The directories a set of `test.include` globs point into, resolved against the run
173
+ * root — the literal part of each pattern, up to its first wildcard.
174
+ *
175
+ * `packages/ui/src/**\/*.test.ts` names `packages/ui/src`, which is enough to know
176
+ * the run's tests live in that package. `**\/*.test.ts` names nothing above the root
177
+ * and is dropped: treating it as a hint would mark every workspace member as the
178
+ * project and undo their detection entirely.
179
+ */
180
+ function testIncludeRoots(include, projectRoot) {
181
+ if (!Array.isArray(include)) return [];
182
+ const dirs = /* @__PURE__ */ new Set();
183
+ for (const pattern of include) {
184
+ if (typeof pattern !== "string" || pattern.startsWith("!")) continue;
185
+ const literal = pattern.slice(0, firstWildcard(pattern));
186
+ const slash = literal.replace(/\\/g, "/").lastIndexOf("/");
187
+ if (slash <= 0) continue;
188
+ dirs.add(path.resolve(projectRoot, literal.slice(0, slash)));
189
+ }
190
+ return [...dirs];
191
+ }
192
+ /**
193
+ * Where a glob stops being a literal path.
194
+ *
195
+ * `!`, `+` and `@` only introduce a pattern as part of an extglob — `@(a|b)` — and
196
+ * are ordinary characters otherwise. Treating them as wildcards on their own cut
197
+ * `packages/@scope/ui/**\/*.test.ts` down to `packages/`, which would have named the
198
+ * whole workspace as the project and switched detection off for every member of it.
199
+ */
200
+ function firstWildcard(pattern) {
201
+ const plain = pattern.search(/[*?[{]/);
202
+ const extglob = pattern.search(/[!+@]\(/);
203
+ if (plain === -1) return extglob === -1 ? pattern.length : extglob;
204
+ return extglob === -1 ? plain : Math.min(plain, extglob);
205
+ }
206
+ /** The nearest directory at or above `from` holding a package.json, or null. */
207
+ function nearestPackageDir(from) {
208
+ let dir = path.resolve(from);
209
+ for (;;) {
210
+ if (fs.existsSync(path.join(dir, "package.json"))) return dir;
211
+ const parent = path.dirname(dir);
212
+ if (parent === dir) return null;
213
+ dir = parent;
214
+ }
215
+ }
178
216
  function resolvePackageVersion(packageName, projectRoot) {
179
217
  const req = createRequire(path.join(projectRoot, "package.json"));
180
218
  try {
@@ -301,8 +339,12 @@ async function resolveOptions(options = {}, projectRoot) {
301
339
  const engine = options.engine === "native" ? "native" : "mock";
302
340
  const userExts = (options.assetExts ?? []).map((e) => e.replace(/^\./, ""));
303
341
  let presets;
304
- if (options.presets) presets = options.presets;
305
- else presets = await autoDetectPresets(diagnostics, projectRoot ?? process.cwd());
342
+ if (Array.isArray(options.presets)) presets = options.presets;
343
+ else {
344
+ const detected = await autoDetectPresets(diagnostics, projectRoot ?? process.cwd());
345
+ const disabled = disabledPresetNames(options.presets);
346
+ presets = disabled.size > 0 ? detected.filter((p) => !disabled.has(p.name)) : detected;
347
+ }
306
348
  return {
307
349
  platform,
308
350
  engine,
@@ -413,6 +455,34 @@ const RN_EXPORT_NAMES = [
413
455
  * it replaced: `eslint-plugin-react-native` and a project directory called
414
456
  * `react-native-app` both contain the words without being React Native packages.
415
457
  */
458
+ /**
459
+ * Two copies of React in one test process produce a null hooks dispatcher, which
460
+ * surfaces as `Cannot read properties of null (reading 'use')` — usually wrapped by
461
+ * React Native Testing Library as "Trying to detect host component names triggered the
462
+ * following error", whose own advice is only that something is wrong with the
463
+ * configuration. `resolve.dedupe` prevents it in the normal case; this reports the
464
+ * cases dedupe cannot reach, such as a nested install, so the cause is named rather
465
+ * than discovered.
466
+ *
467
+ * Pure and exported for testing: `resolve` is the resolver, so the check can be
468
+ * exercised without building a broken node_modules tree.
469
+ */
470
+ function findDuplicateReact(resolve, projectRoot, consumers) {
471
+ const projectCopy = resolve("react/package.json", projectRoot);
472
+ if (!projectCopy) return null;
473
+ for (const consumer of consumers) {
474
+ const consumerRoot = resolve(`${consumer}/package.json`, projectRoot);
475
+ if (!consumerRoot) continue;
476
+ const otherCopy = resolve("react/package.json", consumerRoot);
477
+ if (otherCopy && otherCopy !== projectCopy) return {
478
+ projectCopy,
479
+ otherCopy,
480
+ consumer
481
+ };
482
+ }
483
+ return null;
484
+ }
485
+ const HAS_JEST_MOCK_CALL = /\bjest\s*\.\s*(?:mock|unmock|doMock|doUnmock)\s*\(/;
416
486
  const RN_ECOSYSTEM_PATH = /[\\/]node_modules[\\/](?:@react-native[^\\/]*[\\/][^\\/]+|(?:@[^\\/]+[\\/])?react-native[^\\/]*)[\\/]/;
417
487
  /** Fast membership check for leaf-name lookups on subpath imports. */
418
488
  const RN_EXPORT_NAME_SET = new Set(RN_EXPORT_NAMES);
@@ -442,7 +512,7 @@ function subpathLeafOf(specifier) {
442
512
  * be shadowed (test utilities and tooling entry points). Mirrors
443
513
  * native/match.mjs.
444
514
  */
445
- const UTILITY_SUBPATH_LEAVES = new Set([
515
+ const UTILITY_SUBPATH_LEAVES = /* @__PURE__ */ new Set([
446
516
  "jest-utils",
447
517
  "jestSetup",
448
518
  "mock",
@@ -468,12 +538,91 @@ function containsFunctions(value, visited = /* @__PURE__ */ new WeakSet()) {
468
538
  * modules, and automatic setup-file injection so tests can run against
469
539
  * React Native code in a Node/JSDOM environment.
470
540
  */
541
+ /**
542
+ * Fields that select a different FORMAT of the same code — an ESM build beside a CJS
543
+ * one. Vite prefers them, Node reads `main`, and the two builds are interchangeable,
544
+ * so pointing Vite at `main` costs nothing and collapses the pair into one instance.
545
+ *
546
+ * `react-native` is deliberately NOT here. That field selects a different
547
+ * IMPLEMENTATION — the native build rather than the web one — and Metro resolves it
548
+ * ahead of `main`, so the engine must too (see tests-native/export-conditions.test.ts).
549
+ * Aligning it downward would quietly load the web build, which is a fidelity
550
+ * regression, not a deduplication. Packages using it stay split and are reported by
551
+ * the duplicate-instance warning instead; fixing those means teaching Node to load
552
+ * the native build, which needs the transform pipeline and is a separate change.
553
+ */
554
+ const FORMAT_ONLY_FIELDS = [
555
+ "module",
556
+ "jsnext:main",
557
+ "jsnext"
558
+ ];
559
+ /**
560
+ * Make Vite resolve a package to the same file Node will.
561
+ *
562
+ * The native engine runs two module systems. Vitest already forwards
563
+ * `resolve.conditions` to the worker's Node (`--conditions react-native ...`), so a
564
+ * package using an `exports` map resolves identically on both sides. Legacy
565
+ * top-level fields have no such bridge: Vite reads `react-native`/`module`, Node
566
+ * reads `main`, and a package publishing both ends up loaded twice with separate
567
+ * module-level state. A store written through one copy reads back unset through the
568
+ * other — silently, since nothing fails.
569
+ *
570
+ * Aligning downward, onto the file Node picks, is the direction that cannot break a
571
+ * working suite: the `main` build is by definition something Node can execute,
572
+ * whereas the `react-native` field usually points at untranspiled source that Node
573
+ * cannot parse at all. Aligning upward would turn a wrong-value bug into a crash for
574
+ * any package the engine does not also transform.
575
+ *
576
+ * Packages the engine inlines and transforms are left alone: Vite is meant to own
577
+ * their source, and rewriting them to `main` would undo the reason they are inlined.
578
+ *
579
+ * @returns the absolute file to use, or null to leave resolution alone
580
+ */
581
+ function alignLegacyFieldsWithNode(source, packageDirFor, readManifest, resolveAsNodeWould, isEngineOwned) {
582
+ if (!source || source.startsWith(".") || source.startsWith("/") || source.startsWith("\0")) return null;
583
+ const segments = source.split("/");
584
+ const name = source.startsWith("@") ? segments.slice(0, 2).join("/") : segments[0];
585
+ if (!name || segments.length > (source.startsWith("@") ? 2 : 1)) return null;
586
+ if (isEngineOwned(name)) return null;
587
+ const dir = packageDirFor(name);
588
+ if (!dir) return null;
589
+ const manifest = readManifest(dir);
590
+ if (!manifest) return null;
591
+ if (manifest.exports !== void 0) return null;
592
+ if (typeof manifest["react-native"] === "string") return null;
593
+ const legacy = FORMAT_ONLY_FIELDS.map((f) => manifest[f]).find((v) => typeof v === "string");
594
+ if (typeof legacy !== "string") return null;
595
+ const nodeFile = resolveAsNodeWould(name);
596
+ if (!nodeFile) return null;
597
+ if (path.resolve(dir, legacy) === nodeFile) return null;
598
+ return nodeFile;
599
+ }
600
+ /**
601
+ * Preset names switched off by the object form of the `presets` option.
602
+ *
603
+ * The array form replaces auto-detection wholesale, which meant that turning ONE
604
+ * preset off required listing every other detected preset by hand — tedious, and a
605
+ * list that silently rots as dependencies change. The object form keeps detection
606
+ * and names only what to drop.
607
+ */
608
+ function disabledPresetNames(presets) {
609
+ if (!presets || Array.isArray(presets) || typeof presets !== "object") return /* @__PURE__ */ new Set();
610
+ return new Set(Object.entries(presets).filter(([, enabled]) => enabled === false).map(([name]) => name));
611
+ }
471
612
  function reactNative(options) {
613
+ let jestMockTransformPresent = true;
614
+ let warnedMissingJestMockTransform = false;
615
+ const warnIfJestMockUnhoisted = (code, id) => {
616
+ if (jestMockTransformPresent || warnedMissingJestMockTransform) return;
617
+ if (!HAS_JEST_MOCK_CALL.test(code)) return;
618
+ warnedMissingJestMockTransform = true;
619
+ console.warn(`[vitest-native] ${id} calls jest.mock(), but jestMockTransform() is not in your plugins. Vitest only hoists mocks written on the vi/vitest identifier, so this call runs after the imports it should intercept and the mock will not apply.\nAdd it AFTER reactNative():\n\n import { jestMockTransform } from 'vitest-native/jest-compat'\n plugins: [reactNative(), jestMockTransform()]`);
620
+ };
472
621
  if (options) {
473
622
  validateOptions(options);
474
623
  warnUnknownOptions(options);
475
624
  }
476
- 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 });");
625
+ if (options?.mocks && containsFunctions(options.mocks)) throw new VitestNativeError("INVALID_OPTION", "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 });");
477
626
  let resolved;
478
627
  const presetModules = /* @__PURE__ */ new Map();
479
628
  const presetExportNames = /* @__PURE__ */ new Map();
@@ -482,7 +631,43 @@ function reactNative(options) {
482
631
  let rnFacadeExports = null;
483
632
  let rnFacadeRoot = "";
484
633
  let ecosystemPattern = null;
634
+ let alignRoot = "";
485
635
  let ecosystemRoot = "";
636
+ const alignedCache = /* @__PURE__ */ new Map();
637
+ const alignedResolution = (source, importer) => {
638
+ if (engine !== "native") return void 0;
639
+ const from = importer && path.isAbsolute(importer) && !importer.startsWith("\0") ? importer : path.join(alignRoot || process.cwd(), "package.json");
640
+ const key = `${from}\u0000${source}`;
641
+ const cached = alignedCache.get(key);
642
+ if (cached !== void 0) return cached ?? void 0;
643
+ let result = null;
644
+ try {
645
+ const req = createRequire(from);
646
+ result = alignLegacyFieldsWithNode(source, (name) => {
647
+ try {
648
+ return path.dirname(req.resolve(`${name}/package.json`));
649
+ } catch {
650
+ return null;
651
+ }
652
+ }, (dir) => {
653
+ try {
654
+ return JSON.parse(fs.readFileSync(path.join(dir, "package.json"), "utf8"));
655
+ } catch {
656
+ return null;
657
+ }
658
+ }, (name) => {
659
+ try {
660
+ return req.resolve(name);
661
+ } catch {
662
+ return null;
663
+ }
664
+ }, (name) => name === "react-native" || name.startsWith("@react-native"));
665
+ } catch {
666
+ result = null;
667
+ }
668
+ alignedCache.set(key, result);
669
+ return result ?? void 0;
670
+ };
486
671
  const resolveCache = /* @__PURE__ */ new Map();
487
672
  const virtualCodeCache = /* @__PURE__ */ new Map();
488
673
  const thisDir = path.dirname(fileURLToPath(import.meta.url));
@@ -515,10 +700,11 @@ function reactNative(options) {
515
700
  enforce: "pre",
516
701
  async config(userConfig, _env) {
517
702
  const resolvedRoot = userConfig.root ? path.resolve(userConfig.root) : process.cwd();
703
+ alignRoot = resolvedRoot;
518
704
  const jsxTransform = getJsxTransformConfig(resolvedRoot);
519
705
  const decision = detectEngine(requestedEngine, resolvedRoot);
520
706
  engine = decision.engine;
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.`);
707
+ if (engine === "native" && !decision.nativeAvailable) throw new VitestNativeError("ENGINE_REQUIRES_BABEL", `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
708
  if (decision.notice) console.warn(decision.notice);
523
709
  printEngineBanner(engine, platform, resolvedRoot);
524
710
  const env = {
@@ -532,15 +718,20 @@ function reactNative(options) {
532
718
  env.VITEST_NATIVE_ASSET_EXTS = JSON.stringify(assetExtList);
533
719
  if (hotRuntime && hotRecycle.preserveGlobals?.length) env.VITEST_NATIVE_HOT_PRESERVE_GLOBALS = JSON.stringify(hotRecycle.preserveGlobals);
534
720
  if (engine === "native") {
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'.");
536
- const nativePresetNames = options?.presets ? options.presets.map((p) => p.name) : autoDetectPresetNames(resolvedRoot, diagnostics);
721
+ if (options?.mocks && Object.keys(options.mocks).length > 0) throw new VitestNativeError("MOCKS_REQUIRE_MOCK_ENGINE", "The \"mocks\" option is only supported by engine:'mock'. The native engine runs the real react-native module and cannot safely merge arbitrary exports into it. Use vi.mock() in a setup file, mockNativeModule() for native modules, or set engine:'mock'.");
722
+ const disabledNative = disabledPresetNames(options?.presets);
723
+ const nativePresetNames = Array.isArray(options?.presets) ? options.presets.map((p) => p.name) : autoDetectPresetNames(resolvedRoot, diagnostics).filter((n) => !disabledNative.has(n));
537
724
  if (nativePresetNames.length > 0) env.VITEST_NATIVE_PRESET_NAMES = JSON.stringify(nativePresetNames);
538
- if (options?.presets) {
725
+ if (Array.isArray(options?.presets)) {
539
726
  const presetConfig = {};
540
727
  for (const p of options.presets) if (p.config && Object.keys(p.config).length > 0) presetConfig[p.name] = p.config;
541
728
  if (Object.keys(presetConfig).length > 0) env.VITEST_NATIVE_PRESET_CONFIG = JSON.stringify(presetConfig);
542
729
  }
543
- const ecosystem = detectEcosystemPackages(resolvedRoot, transformPkgs);
730
+ const includeRoots = testIncludeRoots(userConfig.test?.include, resolvedRoot);
731
+ const ecosystem = detectEcosystemPackages([resolvedRoot, ...includeRoots], transformPkgs, includeRoots);
732
+ const linkedDetectedDirs = ecosystem.map((name) => packageDirOf(name, resolvedRoot)).filter((dir) => dir !== null && !/[\\/]node_modules[\\/]/.test(dir));
733
+ const projectDirs = [...new Set([resolvedRoot, ...includeRoots].map((dir) => nearestPackageDir(dir)).filter((dir) => dir !== null))].filter((dir) => !linkedDetectedDirs.some((detected) => containsPath(dir, detected)));
734
+ if (projectDirs.length > 0) env.VITEST_NATIVE_PROJECT_DIRS = JSON.stringify(projectDirs);
544
735
  if (ecosystem.length > 0) {
545
736
  ecosystemRoot = resolvedRoot;
546
737
  ecosystemPattern = new RegExp(`[\\\\/]node_modules[\\\\/](?:${ecosystem.map((p) => p.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})[\\\\/]`);
@@ -556,7 +747,7 @@ function reactNative(options) {
556
747
  if (registryFile) env.VITEST_NATIVE_RN_REGISTRY = registryFile;
557
748
  let hot;
558
749
  if (hotRuntime) {
559
- const { nativePool, defaultHotMemoryLimit } = await import("./pool-CJmjRgsB.mjs");
750
+ const { nativePool, defaultHotMemoryLimit } = await import("./pool-Bcxn9a3I.mjs");
560
751
  const memoryLimit = hotRecycle.memoryLimit ?? (hotRecycle.recycleAfterFiles == null ? defaultHotMemoryLimit() : void 0);
561
752
  hot = {
562
753
  pool: nativePool({
@@ -570,13 +761,18 @@ function reactNative(options) {
570
761
  };
571
762
  }
572
763
  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.`);
764
+ const userInlinesEverything = userConfig.test?.server?.deps?.inline === true;
765
+ if (userPool === "vmThreads" || userPool === "vmForks") throw new VitestNativeError("UNSUPPORTED_POOL", `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
766
  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));
767
+ return asCompatibleViteConfig(nativeEngineConfig(nativeSetupPath, env, extensions, transformPkgs, hot, jsxTransform, userPool, ecosystem, resolvedRoot, userInlinesEverything));
576
768
  }
577
769
  if (hotRuntime) console.warn(`[vitest-native] 'hotRuntime' only applies to engine:'native' (resolved engine: '${engine}'); ignoring.`);
578
770
  if (options?.mocks && Object.keys(options.mocks).length > 0) env.VITEST_NATIVE_MOCKS = JSON.stringify(options.mocks);
579
- if (options?.presets) env.VITEST_NATIVE_PRESET_NAMES = JSON.stringify(options.presets.map((p) => p.name));
771
+ if (Array.isArray(options?.presets)) env.VITEST_NATIVE_PRESET_NAMES = JSON.stringify(options.presets.map((p) => p.name));
772
+ else {
773
+ const disabled = disabledPresetNames(options?.presets);
774
+ if (disabled.size > 0) env.VITEST_NATIVE_PRESET_DISABLED = JSON.stringify([...disabled]);
775
+ }
580
776
  return asCompatibleViteConfig({
581
777
  ...jsxTransform,
582
778
  ssr: { resolve: {
@@ -611,14 +807,31 @@ function reactNative(options) {
611
807
  });
612
808
  },
613
809
  async configResolved(config) {
810
+ jestMockTransformPresent = (config.plugins ?? []).some((plugin) => plugin?.name === "vitest-native:jest-mock-hoist");
811
+ const duplicateReact = findDuplicateReact((specifier, from) => {
812
+ try {
813
+ return createRequire(path.join(from, "package.json")).resolve(specifier);
814
+ } catch {
815
+ return null;
816
+ }
817
+ }, config.root, [
818
+ "@testing-library/react-native",
819
+ "react-test-renderer",
820
+ "react-native"
821
+ ]);
822
+ if (duplicateReact) console.warn(`[vitest-native] Two copies of React are resolvable: your project loads one, and '${duplicateReact.consumer}' loads another.\n project: ${duplicateReact.projectCopy}\n ${duplicateReact.consumer}: ${duplicateReact.otherCopy}\nReact throws "Cannot read properties of null (reading 'use')" when hooks run through a second copy, which React Native Testing Library reports as a failure to detect host component names. Install a single React version at the project root (npm dedupe, or match the version '${duplicateReact.consumer}' expects).`);
614
823
  const peerErrors = [];
615
- for (const { name, minimum, maximumMajor, minimumByMajor } of PEER_REQUIREMENTS) {
824
+ for (const { name, minimum, maximumMajor, minimumByMajor, optional } of PEER_REQUIREMENTS) {
825
+ if (optional) continue;
616
826
  const error = validatePeerDependency(name, minimum, config.root, maximumMajor, minimumByMajor);
617
827
  if (error) peerErrors.push(error);
618
828
  }
619
- if (peerErrors.length > 0) throw new Error(`[vitest-native] Unsupported peer dependencies:\n- ${peerErrors.join("\n- ")}`);
620
- const rntlError = validatePeerDependency("@testing-library/react-native", "12.0.0", config.root, 15);
621
- if (rntlError && !rntlError.includes("not found")) console.warn(`[vitest-native] ${rntlError}`);
829
+ if (peerErrors.length > 0) throw new VitestNativeError("UNSUPPORTED_PEER", `Unsupported peer dependencies:\n- ${peerErrors.join("\n- ")}`);
830
+ for (const { name, minimum, maximumMajor, minimumByMajor, optional } of PEER_REQUIREMENTS) {
831
+ if (!optional) continue;
832
+ const error = validatePeerDependency(name, minimum, config.root, maximumMajor, minimumByMajor);
833
+ if (error && !error.includes("not found")) console.warn(`[vitest-native] ${error}`);
834
+ }
622
835
  resolved = await resolveOptions(options, config.root);
623
836
  try {
624
837
  realRnPackageJson = createRequire(path.join(config.root, "package.json")).resolve("react-native/package.json");
@@ -644,7 +857,9 @@ function reactNative(options) {
644
857
  resolveId(source, importer) {
645
858
  if (engine === "native") {
646
859
  if (source === "react-native" && rnFacadeExports !== null) return "\0virtual:rn-facade";
647
- return resolvePresetId(source);
860
+ const presetHit = resolvePresetId(source);
861
+ if (presetHit) return presetHit;
862
+ return alignedResolution(source, importer);
648
863
  }
649
864
  if (source === "react-native") return "\0virtual:react-native";
650
865
  if (source.startsWith("react-native/")) {
@@ -745,6 +960,7 @@ function reactNative(options) {
745
960
  }
746
961
  },
747
962
  transform(code, id) {
963
+ warnIfJestMockUnhoisted(code, id);
748
964
  if (engine === "native") {
749
965
  if (!ecosystemPattern || !ecosystemPattern.test(id)) return void 0;
750
966
  if (!/\.[cm]?[jt]sx?$/.test(id.split("?")[0])) return void 0;
@@ -774,4 +990,4 @@ function reactNative(options) {
774
990
  };
775
991
  }
776
992
  //#endregion
777
- export { presets_exports as presets, reactNative };
993
+ export { disabledPresetNames, presets_exports as presets, reactNative };
@@ -16,6 +16,21 @@
16
16
  // returns (those with `__esModule` or an explicit `default`) untouched.
17
17
  export function jestMockInterop(mod) {
18
18
  if (mod == null) return mod;
19
+ // An async factory — or any factory returning a promise — resolves to the module
20
+ // shape, so interop applies to the resolved value. Vitest awaits a factory result,
21
+ // so handing the promise back is enough. Without this the promise itself fell into
22
+ // the object branch below, where it has no own enumerable keys and no `default`,
23
+ // producing `{ default: Promise }`: every named export vanished and Vitest reported
24
+ // `No "x" export is defined on the mock` about a vi.mock the author never wrote.
25
+ //
26
+ // Tested by tag rather than by a `then` method: a module may legitimately export a
27
+ // function named `then`, and awaiting that calls it with (resolve, reject) and never
28
+ // settles — a hung test file, which is worse than the bug this fixes. The tag holds
29
+ // for native promises from any realm, and `async` functions and `Promise.resolve`
30
+ // only ever produce those.
31
+ if (Object.prototype.toString.call(mod) === "[object Promise]") {
32
+ return mod.then(jestMockInterop);
33
+ }
19
34
  const t = typeof mod;
20
35
  if (t === "object" || t === "function") {
21
36
  // Already ES-shaped — respect the author's/real module's default export.