vitest-native 0.13.0 → 0.14.0-rc.2

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 (77) hide show
  1. package/CHANGELOG.md +339 -0
  2. package/README.md +138 -48
  3. package/dist/cli.cjs +70 -5
  4. package/dist/cli.d.cts +2 -3
  5. package/dist/cli.d.mts +2 -3
  6. package/dist/cli.mjs +70 -5
  7. package/dist/{ecosystem-Duw40-mO.mjs → ecosystem-DFbU_MPe.mjs} +389 -18
  8. package/dist/{ecosystem-CEIF_-jq.cjs → ecosystem-DI1AhK_k.cjs} +408 -25
  9. package/dist/errors.d.mts +12 -0
  10. package/dist/helpers.cjs +6 -3
  11. package/dist/helpers.d.cts +8 -9
  12. package/dist/helpers.d.mts +8 -9
  13. package/dist/helpers.mjs +6 -3
  14. package/dist/{index-CPGq6p95.d.cts → index-BxzW2D7K.d.cts} +33 -9
  15. package/dist/{index-CmETArCM.d.mts → index-CEbwa4QU.d.mts} +33 -9
  16. package/dist/index.d.mts +4 -4
  17. package/dist/index.mjs +537 -118
  18. package/dist/jest-compat/aliases.d.mts +5 -0
  19. package/dist/jest-compat/aliases.mjs +65 -0
  20. package/dist/jest-compat/caller.mjs +53 -0
  21. package/dist/jest-compat/setup.mjs +72 -36
  22. package/dist/jest-compat.cjs +1 -3
  23. package/dist/jest-compat.d.cts +4 -5
  24. package/dist/jest-compat.d.mts +4 -5
  25. package/dist/jest-compat.mjs +1 -1
  26. package/dist/matchers.d.cts +9 -9
  27. package/dist/matchers.d.mts +9 -9
  28. package/dist/memory-6EPHrJA1.cjs +144 -0
  29. package/dist/memory-FYbP0_gg.mjs +126 -0
  30. package/dist/native/boundary.mjs +13 -2
  31. package/dist/native/bounded-process.mjs +165 -0
  32. package/dist/native/export-condition-recovery-preload.mjs +5 -0
  33. package/dist/native/export-condition-recovery.mjs +195 -0
  34. package/dist/native/globals.mjs +133 -5
  35. package/dist/native/hooks.mjs +131 -71
  36. package/dist/native/loader.mjs +41 -28
  37. package/dist/native/match.d.mts +3 -0
  38. package/dist/native/match.mjs +38 -2
  39. package/dist/native/metro-profile-compiler.mjs +234 -0
  40. package/dist/native/metro-profile.mjs +115 -0
  41. package/dist/native/module-reset.mjs +111 -6
  42. package/dist/native/ownership.d.mts +105 -0
  43. package/dist/native/ownership.mjs +474 -0
  44. package/dist/native/registry-compiler.mjs +43 -0
  45. package/dist/native/registry-process.mjs +124 -0
  46. package/dist/native/registry.mjs +139 -32
  47. package/dist/native/reset.mjs +305 -135
  48. package/dist/native/resolve.d.mts +20 -3
  49. package/dist/native/resolve.mjs +32 -12
  50. package/dist/native/rntl-hooks.mjs +76 -0
  51. package/dist/native/setup.mjs +81 -32
  52. package/dist/native/state-manifest.d.mts +22 -0
  53. package/dist/native/state-manifest.mjs +136 -0
  54. package/dist/native/transform.mjs +29 -8
  55. package/dist/native/worker.mjs +52 -4
  56. package/dist/pool-B4yesGhI.cjs +121 -0
  57. package/dist/pool-DjpOjOf3.mjs +119 -0
  58. package/dist/{presets-CoNf4ByH.cjs → presets-BYHmi7-W.cjs} +117 -18
  59. package/dist/{presets-DGProTaA.mjs → presets-DC-eM5IA.mjs} +117 -18
  60. package/dist/presets.d.mts +1 -1
  61. package/dist/presets.mjs +1 -1
  62. package/dist/rntl-matchers.d.ts +58 -12
  63. package/dist/serializer.cjs +4 -2
  64. package/dist/serializer.d.cts +3 -4
  65. package/dist/serializer.d.mts +3 -4
  66. package/dist/serializer.mjs +4 -2
  67. package/dist/setup.mjs +61 -50
  68. package/dist/worker-vitest-BGPo0ek6.mjs +49 -0
  69. package/dist/worker-vitest-BfiQB8ND.cjs +62 -0
  70. package/docs/hot-default-design.md +175 -88
  71. package/docs/migrating-from-jest.md +12 -5
  72. package/docs/migrating-from-vitest-react-native.md +4 -4
  73. package/docs/release-readiness.md +39 -13
  74. package/docs/versioning.md +19 -18
  75. package/package.json +42 -31
  76. package/dist/pool-BU-1ecIF.cjs +0 -122
  77. package/dist/pool-Bcxn9a3I.mjs +0 -118
@@ -0,0 +1,126 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-BhDjJH2R.mjs";
2
+ import os from "node:os";
3
+ //#region src/native/memory.mjs
4
+ var memory_exports = /* @__PURE__ */ __exportAll({
5
+ createHotMemoryPlan: () => createHotMemoryPlan,
6
+ defaultRequestedWorkers: () => defaultRequestedWorkers,
7
+ effectiveMemoryLimit: () => effectiveMemoryLimit,
8
+ formatBytes: () => formatBytes,
9
+ formatHotMemoryPlan: () => formatHotMemoryPlan,
10
+ resolveRequestedWorkers: () => resolveRequestedWorkers
11
+ });
12
+ const MIB = 1048576;
13
+ const MIN_WORKER_HEAP = 96 * MIB;
14
+ const MAX_WORKER_HEAP = 512 * MIB;
15
+ const MAIN_PROCESS_RESERVE = 256 * MIB;
16
+ const REPLACEMENT_OVERLAP_RESERVE = 192 * MIB;
17
+ const WORKER_RSS_ADMISSION_COST = 256 * MIB;
18
+ const MAX_AUTO_WORKERS = 4;
19
+ function finitePositive(value) {
20
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : null;
21
+ }
22
+ function effectiveMemoryLimit({ totalMemory, constrainedMemory }) {
23
+ const total = finitePositive(totalMemory);
24
+ const constrained = finitePositive(constrainedMemory);
25
+ if (total === null && constrained === null) return {
26
+ bytes: null,
27
+ source: "unknown"
28
+ };
29
+ if (total === null) return {
30
+ bytes: constrained,
31
+ source: "constrained"
32
+ };
33
+ if (constrained === null || total <= constrained) return {
34
+ bytes: total,
35
+ source: "host"
36
+ };
37
+ return {
38
+ bytes: constrained,
39
+ source: "constrained"
40
+ };
41
+ }
42
+ function defaultRequestedWorkers(parallelism = os.availableParallelism?.() ?? os.cpus().length) {
43
+ return Math.max(1, Math.floor(parallelism) - 1);
44
+ }
45
+ /** Resolve Vitest's number/percentage worker option without importing Vitest internals. */
46
+ function resolveRequestedWorkers(value, { parallelism, fileParallelism = true } = {}) {
47
+ if (fileParallelism === false) return 1;
48
+ const cpus = Math.max(1, Math.floor(parallelism ?? os.availableParallelism?.() ?? os.cpus().length));
49
+ if (typeof value === "number" && Number.isFinite(value)) return Math.max(1, Math.floor(value));
50
+ if (typeof value === "string") {
51
+ const trimmed = value.trim();
52
+ if (/^\d+(?:\.\d+)?%$/.test(trimmed)) return Math.max(1, Math.floor(cpus * Number.parseFloat(trimmed) / 100));
53
+ if (/^\d+$/.test(trimmed)) return Math.max(1, Number.parseInt(trimmed, 10));
54
+ }
55
+ return Math.max(1, cpus - 1);
56
+ }
57
+ /**
58
+ * Compute the automatic hot-runtime envelope.
59
+ *
60
+ * The reserves and four-worker cap were earned by the packed 406-file RNTL
61
+ * experiment. They are conservative defaults, not portable benchmark claims.
62
+ */
63
+ function createHotMemoryPlan({ totalMemory = os.totalmem(), constrainedMemory = process.constrainedMemory?.() ?? 0, requestedWorkers = defaultRequestedWorkers() } = {}) {
64
+ const effective = effectiveMemoryLimit({
65
+ totalMemory,
66
+ constrainedMemory
67
+ });
68
+ const requested = Math.max(1, Math.floor(requestedWorkers));
69
+ if (effective.bytes === null) return Object.freeze({
70
+ version: 1,
71
+ source: effective.source,
72
+ effectiveLimit: null,
73
+ softRssLimit: null,
74
+ hardRssLimit: null,
75
+ requestedWorkers: requested,
76
+ admittedWorkers: Math.min(MAX_AUTO_WORKERS, requested),
77
+ maxWorkers: Math.min(MAX_AUTO_WORKERS, requested),
78
+ workerHeapLimit: 256 * MIB,
79
+ mainProcessReserve: MAIN_PROCESS_RESERVE,
80
+ replacementOverlapReserve: REPLACEMENT_OVERLAP_RESERVE
81
+ });
82
+ const softRssLimit = Math.floor(effective.bytes * .8);
83
+ const hardRssLimit = Math.floor(effective.bytes * .9);
84
+ const workerEnvelope = Math.max(0, softRssLimit - MAIN_PROCESS_RESERVE - REPLACEMENT_OVERLAP_RESERVE);
85
+ const admittedWorkers = Math.max(1, Math.min(MAX_AUTO_WORKERS, Math.floor(workerEnvelope / WORKER_RSS_ADMISSION_COST)));
86
+ const maxWorkers = Math.min(requested, admittedWorkers);
87
+ const perWorkerEnvelope = workerEnvelope / maxWorkers;
88
+ const workerHeapLimit = Math.min(MAX_WORKER_HEAP, Math.max(MIN_WORKER_HEAP, Math.floor(perWorkerEnvelope * .65)));
89
+ return Object.freeze({
90
+ version: 1,
91
+ source: effective.source,
92
+ effectiveLimit: effective.bytes,
93
+ softRssLimit,
94
+ hardRssLimit,
95
+ requestedWorkers: requested,
96
+ admittedWorkers,
97
+ maxWorkers,
98
+ workerHeapLimit,
99
+ mainProcessReserve: MAIN_PROCESS_RESERVE,
100
+ replacementOverlapReserve: REPLACEMENT_OVERLAP_RESERVE
101
+ });
102
+ }
103
+ function formatBytes(bytes) {
104
+ if (bytes == null) return "unknown";
105
+ return `${Math.round(bytes / MIB)} MiB`;
106
+ }
107
+ function formatHotMemoryPlan(plan) {
108
+ return [
109
+ `effective limit: ${formatBytes(plan.effectiveLimit)} (${plan.source})`,
110
+ `RSS soft/hard: ${formatBytes(plan.softRssLimit)} / ${formatBytes(plan.hardRssLimit)}`,
111
+ `workers requested/admitted/selected: ${plan.requestedWorkers} / ${plan.admittedWorkers} / ${plan.maxWorkers}`,
112
+ `worker heap recycle threshold: ${formatBytes(plan.workerHeapLimit)}`,
113
+ `reserves main/replacement: ${formatBytes(plan.mainProcessReserve)} / ${formatBytes(plan.replacementOverlapReserve)}`
114
+ ];
115
+ }
116
+ Object.freeze({
117
+ MIB,
118
+ MIN_WORKER_HEAP,
119
+ MAX_WORKER_HEAP,
120
+ MAIN_PROCESS_RESERVE,
121
+ REPLACEMENT_OVERLAP_RESERVE,
122
+ WORKER_RSS_ADMISSION_COST,
123
+ MAX_AUTO_WORKERS
124
+ });
125
+ //#endregion
126
+ export { formatHotMemoryPlan as n, memory_exports as r, createHotMemoryPlan as t };
@@ -154,6 +154,10 @@ function turboStubSource(platform, version) {
154
154
  const state = getBoundaryState(name);
155
155
  if (state.__stub) return state.__stub;
156
156
  const target = {};
157
+ // Generated methods may be memoized again by later state-manifest entries
158
+ // after this stub is reset. Track their identities so verification can
159
+ // distinguish legitimate regeneration from a test's explicit override.
160
+ const generated = new Map();
157
161
  state.__stub = new Proxy(target, {
158
162
  get: (t, p) => {
159
163
  // Explicitly-set properties win (spies, manual overrides, memoized methods).
@@ -194,6 +198,7 @@ function turboStubSource(platform, version) {
194
198
  enumerable: true,
195
199
  configurable: true,
196
200
  });
201
+ generated.set(p, v);
197
202
  return v;
198
203
  },
199
204
  // Every property reads as a callable stub, so report them all as present —
@@ -205,9 +210,15 @@ function turboStubSource(platform, version) {
205
210
  // resident libraries that captured a reference at import time. Under the
206
211
  // default engine each file gets a fresh process, so this never fires.
207
212
  const resets = globalThis.__vitest_native_resets || (globalThis.__vitest_native_resets = []);
208
- resets.push(() => {
213
+ const reset = () => {
209
214
  for (const k of Reflect.ownKeys(target)) delete target[k];
210
- });
215
+ generated.clear();
216
+ };
217
+ reset.verify = () =>
218
+ Reflect.ownKeys(target).every(
219
+ (key) => generated.has(key) && generated.get(key) === target[key],
220
+ );
221
+ resets.push(reset);
211
222
  return state.__stub;
212
223
  };
213
224
  `;
@@ -0,0 +1,165 @@
1
+ // Shared parent-side controller for short-lived, memory-bounded helpers.
2
+ //
3
+ // Expensive toolchain/configuration modules must not become permanent members of
4
+ // Vite's main process merely because their result is needed once at startup. The
5
+ // child receives one JSON value on stdin and returns one JSON value over fd 3;
6
+ // stdout/stderr remain available to arbitrary user/toolchain code without being
7
+ // able to corrupt the protocol.
8
+ import { spawn } from "node:child_process";
9
+
10
+ // The protocol channel carries the one answer and is capped strictly. stdout/stderr
11
+ // belong to arbitrary user and toolchain code, which may log freely: only a tail is
12
+ // kept, for the error message, and logging never kills the child.
13
+ const MAX_OUTPUT_BYTES = 1024 * 1024;
14
+ const LOG_TAIL_BYTES = 64 * 1024;
15
+ const DEFAULT_TIMEOUT_MS = 120_000;
16
+ const OOM_RE = /heap out of memory|reached heap limit|allocation failed.*heap/i;
17
+
18
+ function attempt(entryFile, input, heapMb, spawnProcess, timeoutMs, label) {
19
+ return new Promise((resolve) => {
20
+ let child;
21
+ try {
22
+ child = spawnProcess(process.execPath, [`--max-old-space-size=${heapMb}`, entryFile], {
23
+ stdio: ["pipe", "pipe", "pipe", "pipe"],
24
+ windowsHide: true,
25
+ });
26
+ } catch (error) {
27
+ resolve({
28
+ ok: false,
29
+ oom: false,
30
+ error: error instanceof Error ? error.message : String(error),
31
+ heapMb,
32
+ });
33
+ return;
34
+ }
35
+
36
+ let stdout = "";
37
+ let stderr = "";
38
+ let protocol = "";
39
+ let outputBytes = 0;
40
+ let overflow = false;
41
+ let settled = false;
42
+ let timer;
43
+ const finish = (result) => {
44
+ if (settled) return;
45
+ settled = true;
46
+ clearTimeout(timer);
47
+ resolve(result);
48
+ };
49
+ const appendProtocol = (current, chunk) => {
50
+ outputBytes += Buffer.byteLength(chunk);
51
+ if (outputBytes > MAX_OUTPUT_BYTES) {
52
+ overflow = true;
53
+ child.kill("SIGKILL");
54
+ finish({
55
+ ok: false,
56
+ oom: false,
57
+ error: `${label} output exceeded 1 MiB`,
58
+ heapMb,
59
+ });
60
+ return current;
61
+ }
62
+ return current + chunk;
63
+ };
64
+ // Truncated tails start at a line boundary, so the first line an error message
65
+ // quotes is a whole one.
66
+ const appendLog = (current, chunk) => {
67
+ const next = current + chunk;
68
+ if (next.length <= LOG_TAIL_BYTES) return next;
69
+ const tail = next.slice(-LOG_TAIL_BYTES);
70
+ const lineStart = tail.indexOf("\n");
71
+ return lineStart === -1 ? tail : tail.slice(lineStart + 1);
72
+ };
73
+
74
+ child.stdout?.setEncoding("utf8");
75
+ child.stderr?.setEncoding("utf8");
76
+ child.stdio?.[3]?.setEncoding("utf8");
77
+ child.stdout?.on("data", (chunk) => {
78
+ stdout = appendLog(stdout, chunk);
79
+ });
80
+ child.stderr?.on("data", (chunk) => {
81
+ stderr = appendLog(stderr, chunk);
82
+ });
83
+ child.stdio?.[3]?.on("data", (chunk) => {
84
+ protocol = appendProtocol(protocol, chunk);
85
+ });
86
+ child.on("error", (error) => {
87
+ finish({ ok: false, oom: false, error: error.message, heapMb });
88
+ });
89
+ // A helper may exit before draining input. EPIPE is emitted asynchronously;
90
+ // catching stdin.end() does not catch it. The close event reports the cause.
91
+ child.stdin?.on("error", () => {});
92
+ child.on("close", (code, signal) => {
93
+ if (settled) return;
94
+ const oom = OOM_RE.test(stderr);
95
+ if (overflow) {
96
+ finish({ ok: false, oom: false, error: `${label} output exceeded 1 MiB`, heapMb });
97
+ return;
98
+ }
99
+ let response = null;
100
+ try {
101
+ response = JSON.parse(protocol);
102
+ } catch {}
103
+ if (code === 0 && response?.ok === true) {
104
+ finish({ ...response, heapMb });
105
+ return;
106
+ }
107
+ finish({
108
+ ok: false,
109
+ oom,
110
+ heapMb,
111
+ error:
112
+ response?.error ||
113
+ stderr.trim().split("\n")[0] ||
114
+ stdout.trim().split("\n")[0] ||
115
+ `${label} exited ${code ?? `on ${signal ?? "an unknown signal"}`}`,
116
+ });
117
+ });
118
+ timer = setTimeout(() => {
119
+ child.kill("SIGKILL");
120
+ finish({
121
+ ok: false,
122
+ oom: false,
123
+ heapMb,
124
+ error: `${label} exceeded ${timeoutMs}ms`,
125
+ });
126
+ }, timeoutMs);
127
+ timer.unref?.();
128
+ try {
129
+ child.stdin?.end(JSON.stringify(input));
130
+ } catch (error) {
131
+ child.kill("SIGKILL");
132
+ finish({
133
+ ok: false,
134
+ oom: false,
135
+ heapMb,
136
+ error: error instanceof Error ? error.message : String(error),
137
+ });
138
+ }
139
+ });
140
+ }
141
+
142
+ /** Run once at the initial heap cap, retrying only for a genuine V8 heap OOM. */
143
+ export async function runBoundedProcess(
144
+ entryFile,
145
+ input,
146
+ {
147
+ initialHeapMb,
148
+ retryHeapMb,
149
+ timeoutMs = DEFAULT_TIMEOUT_MS,
150
+ spawnProcess = spawn,
151
+ label = "helper",
152
+ },
153
+ ) {
154
+ const first = await attempt(entryFile, input, initialHeapMb, spawnProcess, timeoutMs, label);
155
+ if (first.ok || !first.oom || retryHeapMb <= initialHeapMb) {
156
+ return { ...first, attempts: 1 };
157
+ }
158
+ const retry = await attempt(entryFile, input, retryHeapMb, spawnProcess, timeoutMs, label);
159
+ return { ...retry, attempts: 2 };
160
+ }
161
+
162
+ export const boundedProcessDefaults = Object.freeze({
163
+ maxOutputBytes: MAX_OUTPUT_BYTES,
164
+ timeoutMs: DEFAULT_TIMEOUT_MS,
165
+ });
@@ -0,0 +1,5 @@
1
+ // Worker preload (`--import`, from `test.execArgv`): installs the export-condition
2
+ // recovery before Vitest loads the test environment. See export-condition-recovery.mjs.
3
+ import { installExportConditionRecovery } from "./export-condition-recovery.mjs";
4
+
5
+ installExportConditionRecovery();
@@ -0,0 +1,195 @@
1
+ // Recovery for packages whose `react-native` export target was never published.
2
+ //
3
+ // Vitest forwards the project's ssr resolve conditions to each worker as Node
4
+ // `--conditions` flags (resolveConditions in Vitest 4 and 5), and both engines put
5
+ // `react-native` there, because Node-owned React Native packages must load their
6
+ // native build. The flag is process-wide, so it also applies to what Vitest itself
7
+ // loads in the worker before any test runs: the test environment. Jest loads its
8
+ // environment outside the conditioned module registry; Vitest cannot.
9
+ //
10
+ // That is harmless until a package's export map names a `react-native` target it does
11
+ // not ship. lru-cache 11.5.3 (2026-09-18; earlier releases have no `react-native`
12
+ // condition) maps `require` + `react-native` to dist/commonjs/react-native/index.min.js
13
+ // and publishes no such file; jsdom depends on lru-cache ^11.3.5, so a fresh install
14
+ // gets it and `environment: 'jsdom'` failed to start any worker ("Cannot find module
15
+ // …/lru-cache/dist/commonjs/react-native/index.min.js").
16
+ //
17
+ // The preload (export-condition-recovery-preload.mjs, `--import`ed from
18
+ // `test.execArgv`, which Vitest appends after the forwarded conditions) acts only on
19
+ // that failure: a bare request whose package export, chosen under the `react-native`
20
+ // condition, names a file that does not exist.
21
+ // It resolves the same export with the process's other conditions, as Node would
22
+ // without `react-native`, and uses that file if it exists. Every other resolution,
23
+ // successful or not, is left exactly as Node decided it.
24
+ //
25
+ // CommonJS `require` only, which is how Vitest loads jsdom. An ESM `import` under the
26
+ // same condition is resolved by Node's ESM loader and is not recovered here.
27
+ import fs from "node:fs";
28
+ import Module from "node:module";
29
+ import path from "node:path";
30
+
31
+ const RN = "react-native";
32
+
33
+ /**
34
+ * The CommonJS conditions Node matches for this process, without `react-native`.
35
+ * Node's documented set: `require`, `node`, `node-addons`, `module-sync` where
36
+ * require(esm) is enabled, the `--conditions` / `-C` flags, and `default`.
37
+ */
38
+ export function cjsConditionsWithout(
39
+ excluded,
40
+ execArgv = process.execArgv,
41
+ features = process.features,
42
+ ) {
43
+ const conditions = ["require", "node", "node-addons"];
44
+ if (features?.require_module) conditions.push("module-sync");
45
+ const options = [...execArgv, ...(process.env.NODE_OPTIONS ?? "").split(/\s+/).filter(Boolean)];
46
+ for (let i = 0; i < options.length; i++) {
47
+ const option = options[i];
48
+ let value;
49
+ if (option === "--conditions" || option === "-C") value = options[++i];
50
+ else if (option.startsWith("--conditions=")) value = option.slice("--conditions=".length);
51
+ else if (option.startsWith("-C=")) value = option.slice(3);
52
+ if (value && value !== excluded && !conditions.includes(value)) conditions.push(value);
53
+ }
54
+ return conditions;
55
+ }
56
+
57
+ // Node's resolvePackageTarget, for already-valid string targets: `undefined` means no
58
+ // condition matched (keep looking), `null` means the subpath is excluded. In a
59
+ // condition object the first matching key decides, even when its value is null; in an
60
+ // array a null entry falls through to the next.
61
+ function matchTarget(target, conditions) {
62
+ if (typeof target === "string") return target;
63
+ if (Array.isArray(target)) {
64
+ let excluded = false;
65
+ for (const entry of target) {
66
+ const match = matchTarget(entry, conditions);
67
+ if (typeof match === "string") return match;
68
+ if (match === null) excluded = true;
69
+ }
70
+ return excluded || target.length === 0 ? null : undefined;
71
+ }
72
+ if (target !== null && typeof target === "object") {
73
+ for (const [key, value] of Object.entries(target)) {
74
+ if (key === "default" || conditions.includes(key)) {
75
+ const match = matchTarget(value, conditions);
76
+ if (match !== undefined) return match;
77
+ }
78
+ }
79
+ return undefined;
80
+ }
81
+ return null;
82
+ }
83
+
84
+ // Node's patternKeyCompare: the longer base (up to and including `*`) wins, then the
85
+ // longer key. Negative when `a` ranks first.
86
+ function patternKeyCompare(a, b) {
87
+ const aStar = a.indexOf("*");
88
+ const bStar = b.indexOf("*");
89
+ const baseA = aStar === -1 ? a.length : aStar + 1;
90
+ const baseB = bStar === -1 ? b.length : bStar + 1;
91
+ if (baseA !== baseB) return baseB - baseA;
92
+ if (aStar === -1) return 1;
93
+ if (bStar === -1) return -1;
94
+ return b.length - a.length;
95
+ }
96
+
97
+ /**
98
+ * The relative target a package's `exports` gives `subpath` ("." or "./x") under
99
+ * `conditions`, or null when it gives none. Follows Node's PACKAGE_EXPORTS_RESOLVE:
100
+ * the sugar forms, exact subpaths, and single-`*` patterns ranked by patternKeyCompare.
101
+ */
102
+ export function exportTarget(exportsField, subpath, conditions) {
103
+ if (exportsField === undefined || exportsField === null) return null;
104
+ const map =
105
+ typeof exportsField === "string" ||
106
+ Array.isArray(exportsField) ||
107
+ !Object.keys(exportsField).some((key) => key.startsWith("."))
108
+ ? { ".": exportsField }
109
+ : exportsField;
110
+ if (Object.hasOwn(map, subpath) && !subpath.includes("*")) {
111
+ return matchTarget(map[subpath], conditions) ?? null;
112
+ }
113
+ let bestKey = "";
114
+ let bestMatch;
115
+ for (const key of Object.keys(map)) {
116
+ const star = key.indexOf("*");
117
+ if (star === -1 || key.lastIndexOf("*") !== star) continue;
118
+ const trailer = key.slice(star + 1);
119
+ if (
120
+ subpath.startsWith(key.slice(0, star)) &&
121
+ subpath.length >= key.length &&
122
+ subpath.endsWith(trailer) &&
123
+ patternKeyCompare(bestKey, key) > 0
124
+ ) {
125
+ bestKey = key;
126
+ bestMatch = subpath.slice(star, subpath.length - trailer.length);
127
+ }
128
+ }
129
+ if (bestMatch === undefined) return null;
130
+ const target = matchTarget(map[bestKey], conditions);
131
+ return typeof target === "string" ? target.replaceAll("*", bestMatch) : null;
132
+ }
133
+
134
+ function packageName(request) {
135
+ if (request.startsWith(".") || path.isAbsolute(request) || request.startsWith("node:")) {
136
+ return null;
137
+ }
138
+ const parts = request.split("/");
139
+ return request.startsWith("@") ? (parts.length > 1 ? `${parts[0]}/${parts[1]}` : null) : parts[0];
140
+ }
141
+
142
+ /**
143
+ * The file to use instead, when `error` is Node failing on a missing `react-native`
144
+ * export target for `request`, or null to let the error stand.
145
+ */
146
+ export function recoverMissingReactNativeTarget(
147
+ request,
148
+ error,
149
+ conditions,
150
+ fileExists = fs.existsSync,
151
+ ) {
152
+ if (error?.code !== "MODULE_NOT_FOUND" || typeof error.path !== "string") return null;
153
+ const name = packageName(request);
154
+ if (name === null) return null;
155
+ // Node reports the package directory on 22.22 and 24, but its package.json on 20.19
156
+ // and 22.13 (measured on each).
157
+ const packageDir =
158
+ path.basename(error.path) === "package.json" ? path.dirname(error.path) : error.path;
159
+ let manifest;
160
+ try {
161
+ manifest = JSON.parse(fs.readFileSync(path.join(packageDir, "package.json"), "utf8"));
162
+ } catch {
163
+ return null;
164
+ }
165
+ if (manifest.name !== name || manifest.exports === undefined) return null;
166
+ const subpath = `.${request.slice(name.length)}`;
167
+ // Only the failure this exists for: the target Node chose, with react-native in
168
+ // play, is not on disk.
169
+ const withRn = exportTarget(manifest.exports, subpath, [RN, ...conditions]);
170
+ if (withRn === null || fileExists(path.join(packageDir, withRn))) return null;
171
+ const without = exportTarget(manifest.exports, subpath, conditions);
172
+ if (without === null || without === withRn) return null;
173
+ const file = path.join(packageDir, without);
174
+ return fileExists(file) ? file : null;
175
+ }
176
+
177
+ const INSTALLED = Symbol.for("vitest-native.export-condition-recovery");
178
+
179
+ export function installExportConditionRecovery() {
180
+ // Marked on the process, not the function: later patches of _resolveFilename
181
+ // (native/hooks.mjs, module-reset.mjs) wrap this one.
182
+ if (globalThis[INSTALLED]) return;
183
+ globalThis[INSTALLED] = true;
184
+ const conditions = cjsConditionsWithout(RN);
185
+ const original = Module._resolveFilename;
186
+ Module._resolveFilename = function (request, parent, ...rest) {
187
+ try {
188
+ return original.call(this, request, parent, ...rest);
189
+ } catch (error) {
190
+ const file = recoverMissingReactNativeTarget(request, error, conditions);
191
+ if (file === null) throw error;
192
+ return file;
193
+ }
194
+ };
195
+ }