vitest-native 0.13.0 → 0.14.0-rc.1

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 +298 -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 +435 -95
  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 +14 -3
  49. package/dist/native/resolve.mjs +10 -10
  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 +21 -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
@@ -1,3 +1,5 @@
1
+ import { createRequire } from "node:module";
2
+ import path from "node:path";
1
3
  // Globals React Native core expects at runtime, ported from react-native/jest/setup.js.
2
4
  export function installGlobals() {
3
5
  const g = globalThis;
@@ -35,6 +37,10 @@ export function installGlobals() {
35
37
  function installExpoGlobal(g) {
36
38
  if (g.expo && g.expo.EventEmitter) return;
37
39
 
40
+ // Listener and module mutations are attributed later by reset.mjs at the
41
+ // import/test boundary. Keeping the stack here lets resident dependency init
42
+ // survive while file-owned state is removed before the next file.
43
+ const listenerRecords = new Set();
38
44
  class EventEmitter {
39
45
  constructor() {
40
46
  this._listeners = new Map();
@@ -42,15 +48,37 @@ function installExpoGlobal(g) {
42
48
  addListener(eventName, listener) {
43
49
  let set = this._listeners.get(eventName);
44
50
  if (!set) this._listeners.set(eventName, (set = new Set()));
45
- set.add(listener);
51
+ if (!set.has(listener)) {
52
+ set.add(listener);
53
+ listenerRecords.add({
54
+ emitter: this,
55
+ eventName,
56
+ listener,
57
+ stack: new Error().stack || "",
58
+ });
59
+ }
46
60
  return { remove: () => this.removeListener(eventName, listener) };
47
61
  }
48
62
  removeListener(eventName, listener) {
49
63
  this._listeners.get(eventName)?.delete(listener);
64
+ for (const record of listenerRecords) {
65
+ if (
66
+ record.emitter === this &&
67
+ record.eventName === eventName &&
68
+ record.listener === listener
69
+ ) {
70
+ listenerRecords.delete(record);
71
+ }
72
+ }
50
73
  }
51
74
  removeAllListeners(eventName) {
52
75
  if (eventName == null) this._listeners.clear();
53
76
  else this._listeners.delete(eventName);
77
+ for (const record of listenerRecords) {
78
+ if (record.emitter === this && (eventName == null || record.eventName === eventName)) {
79
+ listenerRecords.delete(record);
80
+ }
81
+ }
54
82
  }
55
83
  emit(eventName, ...args) {
56
84
  this._listeners.get(eventName)?.forEach((l) => l(...args));
@@ -82,22 +110,67 @@ function installExpoGlobal(g) {
82
110
  // so they are memoized classes on SharedObject's prototype chain.
83
111
  // Explicitly-set properties (spies, overrides) always win.
84
112
  const __moduleCache = new Map();
113
+ const moduleResets = new Set();
85
114
  const makeModuleStub = () => {
86
115
  const fabricatedClasses = new Map();
87
- return new Proxy(new NativeModule(), {
88
- get(target, prop) {
89
- if (prop in target) return target[prop];
116
+ const fabricatedRecords = new Map();
117
+ const directMutations = new Map();
118
+ const target = new NativeModule();
119
+ const trackDirectMutation = (prop) => {
120
+ if (directMutations.has(prop)) return;
121
+ directMutations.set(prop, {
122
+ descriptor: Object.getOwnPropertyDescriptor(target, prop),
123
+ stack: new Error().stack || "",
124
+ });
125
+ };
126
+ const stub = new Proxy(target, {
127
+ get(object, prop) {
128
+ if (prop in object) return object[prop];
90
129
  if (typeof prop === "symbol") return undefined;
91
130
  if (prop.endsWith("Async")) return () => Promise.resolve(undefined);
92
131
  if (/^[A-Z]/.test(prop)) {
93
132
  if (!fabricatedClasses.has(prop)) {
94
133
  fabricatedClasses.set(prop, class extends SharedObject {});
134
+ fabricatedRecords.set(prop, { stack: new Error().stack || "" });
95
135
  }
96
136
  return fabricatedClasses.get(prop);
97
137
  }
98
138
  return () => undefined;
99
139
  },
140
+ set(object, prop, value) {
141
+ trackDirectMutation(prop);
142
+ return Reflect.set(object, prop, value, object);
143
+ },
144
+ defineProperty(object, prop, descriptor) {
145
+ trackDirectMutation(prop);
146
+ return Reflect.defineProperty(object, prop, descriptor);
147
+ },
148
+ deleteProperty(object, prop) {
149
+ trackDirectMutation(prop);
150
+ return Reflect.deleteProperty(object, prop);
151
+ },
152
+ });
153
+ moduleResets.add({
154
+ reset: () => {
155
+ for (const [prop, record] of directMutations) {
156
+ if (record.descriptor) Object.defineProperty(target, prop, record.descriptor);
157
+ else Reflect.deleteProperty(target, prop);
158
+ }
159
+ directMutations.clear();
160
+ for (const prop of fabricatedRecords.keys()) fabricatedClasses.delete(prop);
161
+ fabricatedRecords.clear();
162
+ },
163
+ bless: (isResidentImport) => {
164
+ for (const [prop, record] of directMutations) {
165
+ if (isResidentImport(record.stack)) directMutations.delete(prop);
166
+ }
167
+ for (const [prop, record] of fabricatedRecords) {
168
+ if (isResidentImport(record.stack)) fabricatedRecords.delete(prop);
169
+ }
170
+ },
171
+ verify: () => directMutations.size === 0 && fabricatedRecords.size === 0,
100
172
  });
173
+ return stub;
101
174
  };
102
175
  const modules = new Proxy(
103
176
  {},
@@ -112,7 +185,7 @@ function installExpoGlobal(g) {
112
185
  );
113
186
 
114
187
  let __uuid = 0;
115
- g.expo = {
188
+ const expoRuntime = {
116
189
  EventEmitter,
117
190
  NativeModule,
118
191
  SharedObject,
@@ -129,4 +202,59 @@ function installExpoGlobal(g) {
129
202
  getViewConfig: () => null,
130
203
  reloadAppAsync: () => Promise.resolve(),
131
204
  };
205
+ const resetRuntime = () => {
206
+ while (listenerRecords.size > 0) {
207
+ const record = listenerRecords.values().next().value;
208
+ record.emitter.removeListener(record.eventName, record.listener);
209
+ }
210
+ for (const reset of moduleResets) reset.reset();
211
+ __uuid = 0;
212
+ };
213
+ resetRuntime.bless = (isResidentImport) => {
214
+ for (const record of listenerRecords) {
215
+ if (isResidentImport(record.stack)) listenerRecords.delete(record);
216
+ }
217
+ for (const reset of moduleResets) reset.bless(isResidentImport);
218
+ };
219
+ resetRuntime.verify = () =>
220
+ __uuid === 0 &&
221
+ listenerRecords.size === 0 &&
222
+ [...moduleResets].every((reset) => reset.verify());
223
+ Object.defineProperty(expoRuntime, Symbol.for("vitest-native.expo.reset"), {
224
+ configurable: false,
225
+ enumerable: false,
226
+ value: resetRuntime,
227
+ writable: false,
228
+ });
229
+ g.expo = expoRuntime;
230
+ }
231
+
232
+ /**
233
+ * `global.ErrorUtils` — React Native's error-guard polyfill (installed on device by
234
+ * InitializeCore via @react-native/js-polyfills, and by Jest's RN preset as a setup
235
+ * polyfill). The native engine deliberately does not run InitializeCore, and this
236
+ * global was the one piece of it that library code reads at MODULE SCOPE: Expo's
237
+ * `Expo.fx` calls `ErrorUtils.getGlobalHandler()` while loading, so any Expo import
238
+ * under the native engine failed with "ErrorUtils is not defined".
239
+ *
240
+ * The real polyfill is used, not a hand mock: it is Flow-typed, so this must run
241
+ * AFTER the require hooks are installed (they compile it like the rest of the
242
+ * @react-native/* sources), and it is resolved from the project so the version
243
+ * matches the installed React Native. Idempotent per realm. Silent when the
244
+ * polyfill package is absent (a partial install) — nothing else here depends on it.
245
+ */
246
+ export function installErrorUtils(projectRoot) {
247
+ const g = globalThis;
248
+ if (g.ErrorUtils) return;
249
+ try {
250
+ const req = createRequire(path.join(projectRoot, "package.json"));
251
+ // Resolved via react-native's own dependency, the way InitializeCore reaches it.
252
+ const rnDir = path.dirname(req.resolve("react-native/package.json"));
253
+ const errorGuard = createRequire(path.join(rnDir, "package.json")).resolve(
254
+ "@react-native/js-polyfills/error-guard",
255
+ );
256
+ req(errorGuard);
257
+ } catch {
258
+ // Not installed; leave the global undefined rather than shipping a lookalike.
259
+ }
132
260
  }
@@ -6,14 +6,12 @@ import fs from "node:fs";
6
6
  import { transformRN, isFlow, needsTransform } from "./transform.mjs";
7
7
  import { boundarySourceFor } from "./boundary.mjs";
8
8
  import { resolvePlatformFile, resolveDeepPackageFile } from "./resolve.mjs";
9
+ import { NODE_MODULES_PATH, isUtilitySubpath, packageNameOf, subpathLeafOf } from "./match.mjs";
9
10
  import {
10
- NODE_MODULES_PATH,
11
- REACT_NATIVE_PATH,
12
- buildPkgMatcher,
13
- isUtilitySubpath,
14
- packageNameOf,
15
- subpathLeafOf,
16
- } from "./match.mjs";
11
+ createNativeOwnershipPolicy,
12
+ findNativeOwnershipConflict,
13
+ parseNativeOwnershipManifest,
14
+ } from "./ownership.mjs";
17
15
  import { explainUntransformedSyntaxError } from "./explain.mjs";
18
16
 
19
17
  // Guarded via globalThis, not module scope: under the hot runtime this module
@@ -21,9 +19,9 @@ import { explainUntransformedSyntaxError } from "./explain.mjs";
21
19
  // loader, once through Vitest's module runner when the setup file is inlined),
22
20
  // and the hooks must still install exactly once per worker.
23
21
  /**
24
- * Packages Vite executes itself (see ecosystem.ts). If Node also resolves one of
25
- * these, the module exists TWICE in the process — once in Vite's graph, once in
26
- * Node's — and module-level state does not cross between them.
22
+ * Packages whose legacy entry fields make Vite and Node select different files. If
23
+ * both graphs resolve one, the module exists TWICE in the process and module-level
24
+ * state does not cross between them.
27
25
  *
28
26
  * This is silent by construction: nothing fails, nothing is logged, the second
29
27
  * copy simply starts empty. A store configured through one copy reads back
@@ -37,12 +35,12 @@ import { explainUntransformedSyntaxError } from "./explain.mjs";
37
35
  const VITE_MAIN_FIELDS = ["react-native", "module", "jsnext:main", "jsnext"];
38
36
 
39
37
  const reportedDuplicates = new Set();
40
- const reportedProjectLoads = new Set();
38
+ const reportedProjectResolutions = new Set();
41
39
 
42
40
  /** Test seam: the warning is once per package for the life of the worker. */
43
41
  export function _resetDuplicateReports() {
44
42
  reportedDuplicates.clear();
45
- reportedProjectLoads.clear();
43
+ reportedProjectResolutions.clear();
46
44
  cachedProjectDirs = undefined;
47
45
  }
48
46
 
@@ -58,9 +56,10 @@ let cachedProjectDirs;
58
56
  function projectDirs() {
59
57
  if (cachedProjectDirs) return cachedProjectDirs;
60
58
  try {
61
- cachedProjectDirs = JSON.parse(process.env.VITEST_NATIVE_PROJECT_DIRS || "[]").map(
62
- (dir) => dir.replace(/\\/g, "/").replace(/\/+$/, "") + "/",
63
- );
59
+ const ownership = parseNativeOwnershipManifest(process.env.VITEST_NATIVE_OWNERSHIP);
60
+ const dirs =
61
+ ownership?.projectDirs ?? JSON.parse(process.env.VITEST_NATIVE_PROJECT_DIRS || "[]");
62
+ cachedProjectDirs = dirs.map((dir) => dir.replace(/\\/g, "/").replace(/\/+$/, "") + "/");
64
63
  } catch {
65
64
  cachedProjectDirs = [];
66
65
  }
@@ -68,40 +67,51 @@ function projectDirs() {
68
67
  }
69
68
 
70
69
  /**
71
- * Say so when Node loads the project's own source.
70
+ * Report Node resolution of project source assigned to Vite.
72
71
  *
73
- * The package under test is Vite's (see the ownership rule in apply.ts). If an
74
- * installed package requires it as well, it exists twice — once in each graph — and
75
- * the symptom is silence: a store configured through the test's copy reads back unset
76
- * through the copy the library sees, so an assertion compares "" against the expected
77
- * text with nothing pointing at the cause. It is the same failure the
78
- * duplicate-instance warning above covers, arrived at from the other direction: there
79
- * the two graphs disagree about which FILE the package is, here they agree on the file
80
- * and still hold separate instances of it.
72
+ * This runs in `_resolveFilename`, including for `require.resolve()`. Resolution
73
+ * does not prove execution, much less two live instances. If both graphs evaluate
74
+ * the file, their independent stores can silently return different values. Keep
75
+ * this a conditional risk warning, not a fatal duplicate-instance assertion.
81
76
  *
82
77
  * Only reported when the requirer is an installed package. A test reaching into its
83
78
  * own source deliberately — `jest.requireActual('./src/thing')` — is Node loading
84
79
  * project files on purpose, and is not this.
85
80
  */
86
- export function checkProjectSourceLoadedByNode(resolved, parent, dirs = projectDirs()) {
87
- if (dirs.length === 0 || typeof resolved !== "string") return;
81
+ export function checkProjectSourceResolvedByNode(resolved, parent, dirs = projectDirs(), policy) {
82
+ if (typeof resolved !== "string" || (!policy && dirs.length === 0)) return;
83
+ // `_resolveFilename` returns bare names for built-ins (`fs`, `node:fs`, `module`).
84
+ // Resolving that string as a filesystem path makes it look like a relative file
85
+ // inside the project, which produced a page of false twin warnings from Babel's
86
+ // ordinary built-in imports in packed Expo apps.
87
+ if (Module.isBuiltin(resolved)) return;
88
88
  const file = resolved.replace(/\\/g, "/");
89
89
  // Project source never lives under node_modules, and the project directory
90
90
  // contains its own node_modules — so this has to be excluded explicitly.
91
91
  if (file.includes("/node_modules/")) return;
92
- if (!dirs.some((dir) => file.startsWith(dir))) return;
92
+ if (policy) {
93
+ // An authoritative policy may assign vendored RN to Node, delegate ownership,
94
+ // or disable enforcement. Never undo that decision with a path heuristic.
95
+ if (findNativeOwnershipConflict(policy, file, "node")?.decision.reason !== "project-source") {
96
+ return;
97
+ }
98
+ } else if (
99
+ !dirs.some((dir) => file.startsWith(dir.replace(/\\/g, "/").replace(/\/+$/, "") + "/"))
100
+ ) {
101
+ return;
102
+ }
93
103
  const from = parent && parent.filename ? parent.filename.replace(/\\/g, "/") : "";
94
104
  if (!NODE_MODULES_PATH.test(from) || from.includes("/vitest-native/dist/")) return;
95
- if (reportedProjectLoads.has(file)) return;
96
- reportedProjectLoads.add(file);
105
+ if (reportedProjectResolutions.has(file)) return;
106
+ reportedProjectResolutions.add(file);
97
107
  console.warn(
98
- `[vitest-native] Node loaded a file from the package under test.\n` +
108
+ `[vitest-native] Node resolved a file from the package under test.\n` +
99
109
  ` file -> ${resolved}\n` +
100
- ` required by -> ${parent.filename}\n` +
101
- " The package under test belongs to Vite's graph, so it now exists twice — once\n" +
102
- " in each module system — and module-level state is not shared between the copies.\n" +
103
- " Nothing throws: writes through one are invisible to the other, so values read back\n" +
104
- " unset. This happens when an installed React Native package depends on the very\n" +
110
+ ` requested by -> ${parent.filename}\n` +
111
+ " resolution observed -> Node; policy owner -> Vite (project-source)\n" +
112
+ " Resolution alone does not prove execution or duplicate instances. If both Node\n" +
113
+ " and Vite evaluate this file, their module-level state is not shared.\n" +
114
+ " This risk occurs when an installed React Native package depends on the very\n" +
105
115
  " package whose tests are running. Import it from one side only, or test it from a\n" +
106
116
  " package that does not sit underneath the dependency.",
107
117
  );
@@ -115,16 +125,22 @@ function reportDuplicateInstance(pkg, nodeFile, viteFile, field) {
115
125
  " If both module systems load it, the package exists twice and module-level state —\n" +
116
126
  " stores, React contexts, event emitters, registries — is not shared between the copies.\n" +
117
127
  " Nothing throws: writes through one are simply invisible to the other, so values read\n" +
118
- " back unset. Set `resolve.mainFields` so both resolvers agree, or import the package\n" +
119
- " from one side only.",
128
+ " back unset. Only a risk: this compares Node's resolution against Vite's default\n" +
129
+ " main fields, and cannot see whether Vite loaded the package at all. Align the two\n" +
130
+ " (`resolve.mainFields`, matching the fields above), or import the package from one\n" +
131
+ " side only.",
120
132
  );
121
133
  }
122
134
 
123
135
  /**
124
136
  * Compare what Node just resolved against what Vite's field order would pick for
125
- * the same package. A difference means the two module systems have different
126
- * files for one package id, so anything importing it from both sides gets two
127
- * copies with separate state.
137
+ * the same package. A difference means the two module systems WOULD hold different
138
+ * files for one package id, so anything importing it from both sides gets two copies
139
+ * with separate state.
140
+ *
141
+ * Only a risk, never proof: Vite's graph is not visible from here, so a package Node
142
+ * alone ever requires looks the same as one both graphs load. That is why the caller
143
+ * runs this under `diagnostics` rather than by default.
128
144
  */
129
145
  export function checkResolverAgreement(request, resolved) {
130
146
  const pkg = packageOf(request);
@@ -162,6 +178,7 @@ export function installRequireHooks(
162
178
  platform = "ios",
163
179
  reactNativeVersion = "0.0.0",
164
180
  assetExts = [],
181
+ sourceExts = ["js", "jsx", "json", "ts", "tsx"],
165
182
  ) {
166
183
  if (globalThis.__vitest_native_require_hooks_installed) {
167
184
  // Install once per worker — but not with a frozen transform list. The hot
@@ -171,7 +188,11 @@ export function installRequireHooks(
171
188
  // pin the boot-time env list forever, and the divergence is hot-only because
172
189
  // under stock the setup file IS the first caller. Rebuild the matcher when
173
190
  // a later caller brings a different list; hook layers are never stacked.
174
- globalThis.__vitest_native_require_hooks_update?.(transformPkgs);
191
+ globalThis.__vitest_native_require_hooks_update?.({
192
+ transformPkgs,
193
+ assetExts,
194
+ sourceExts,
195
+ });
175
196
  return;
176
197
  }
177
198
  globalThis.__vitest_native_require_hooks_installed = true;
@@ -185,26 +206,46 @@ export function installRequireHooks(
185
206
  // @react-native-vector-icons are shadowed by their preset, so they never inspect
186
207
  // the stubbed font require.)
187
208
  const NON_ASSET = new Set([".js", ".cjs", ".mjs", ".ts", ".tsx", ".json", ".node"]);
188
- const assetExtSet = new Set(assetExts.map((e) => String(e).replace(/^\./, "").toLowerCase()));
189
- for (const raw of assetExts) {
190
- const ext = "." + String(raw).replace(/^\./, "");
191
- if (NON_ASSET.has(ext) || Module._extensions[ext]) continue;
192
- Module._extensions[ext] = function (mod, filename) {
193
- const basename = filename.replace(/\\/g, "/").split("/").pop() || filename;
194
- mod.exports = basename;
195
- };
196
- }
209
+ let assetExtSet = new Set(assetExts.map((e) => String(e).replace(/^\./, "").toLowerCase()));
210
+ let activeSourceExts = sourceExts;
211
+ const installAssetExtensions = (extensions) => {
212
+ for (const raw of extensions) {
213
+ const ext = "." + String(raw).replace(/^\./, "");
214
+ if (NON_ASSET.has(ext) || Module._extensions[ext]) continue;
215
+ Module._extensions[ext] = function (mod, filename) {
216
+ const basename = filename.replace(/\\/g, "/").split("/").pop() || filename;
217
+ mod.exports = basename;
218
+ };
219
+ }
220
+ };
221
+ installAssetExtensions(assetExts);
197
222
 
198
223
  // Configured third-party packages to also transform (Flow/TS/JSX stripped).
199
224
  // `let` + the updater below: the hot worker installs the hooks at boot with the
200
225
  // raw env list, and the setup file re-calls with the preset-extended one.
201
- let isExtra = buildPkgMatcher(transformPkgs, projectRoot);
226
+ const configuredOwnership = parseNativeOwnershipManifest(process.env.VITEST_NATIVE_OWNERSHIP);
227
+ const ownershipBase = {
228
+ projectRoot,
229
+ projectDirs: configuredOwnership?.projectDirs ?? [],
230
+ reactNativeRoots: configuredOwnership?.reactNativeRoots ?? [],
231
+ serverDepsInlineAll: configuredOwnership?.enforcement === "overridden-by-inline-all",
232
+ };
233
+ let ownership = createNativeOwnershipPolicy({
234
+ ...ownershipBase,
235
+ runtimeTransforms: transformPkgs,
236
+ });
237
+ let isExtra = ownership.matchesNodeTransformedFile;
202
238
  let isExtraKey = JSON.stringify(transformPkgs);
203
- globalThis.__vitest_native_require_hooks_update = (pkgs) => {
239
+ globalThis.__vitest_native_require_hooks_update = (next) => {
240
+ const pkgs = next.transformPkgs;
241
+ activeSourceExts = next.sourceExts;
242
+ assetExtSet = new Set(next.assetExts.map((e) => String(e).replace(/^\./, "").toLowerCase()));
243
+ installAssetExtensions(next.assetExts);
204
244
  const key = JSON.stringify(pkgs);
205
245
  if (key === isExtraKey) return;
206
246
  isExtraKey = key;
207
- isExtra = buildPkgMatcher(pkgs, projectRoot);
247
+ ownership = createNativeOwnershipPolicy({ ...ownershipBase, runtimeTransforms: pkgs });
248
+ isExtra = ownership.matchesNodeTransformedFile;
208
249
  };
209
250
 
210
251
  // Preset redirect (CJS): when an externalized third-party module require()s a
@@ -277,44 +318,63 @@ export function installRequireHooks(
277
318
 
278
319
  const origResolve = Module._resolveFilename;
279
320
  Module._resolveFilename = function (request, parent, ...rest) {
321
+ let resolved;
280
322
  if (
281
323
  parent &&
282
324
  parent.filename &&
283
325
  (NODE_MODULES_PATH.test(parent.filename) ||
284
- REACT_NATIVE_PATH.test(parent.filename) ||
326
+ ownership.isReactNativeFile(parent.filename) ||
285
327
  isExtra(parent.filename)) &&
286
328
  request.startsWith(".") &&
287
329
  !path.extname(request)
288
330
  ) {
289
- const hit = resolvePlatformFile(
331
+ resolved = resolvePlatformFile(
290
332
  path.resolve(path.dirname(parent.filename), request),
291
333
  platform,
334
+ activeSourceExts,
292
335
  );
293
- if (hit) return hit;
294
336
  }
295
- let resolved;
296
- try {
297
- resolved = origResolve.call(this, request, parent, ...rest);
298
- } catch (err) {
299
- // RN 0.87's exports map rejects the deep self-references its own Babel
300
- // preset emits (`react-native/src/private/…`); Metro resolves them via the
301
- // `react-native-legacy-deep-imports` condition. Mirror Metro by path.
302
- const fromDir = parent?.filename ? path.dirname(parent.filename) : projectRoot;
303
- const deep = resolveDeepPackageFile(request, fromDir, platform);
304
- if (deep === null) throw err;
305
- resolved = deep;
337
+ if (!resolved) {
338
+ try {
339
+ resolved = origResolve.call(this, request, parent, ...rest);
340
+ } catch (err) {
341
+ // RN 0.87's exports map rejects the deep self-references its own Babel
342
+ // preset emits (`react-native/src/private/…`); Metro resolves them via the
343
+ // `react-native-legacy-deep-imports` condition. Mirror Metro by path.
344
+ // From the requiring file first, as Metro does; then from the project, for a
345
+ // parent outside the project's tree — the precompiled registry's cache file
346
+ // when the cache had to fall back to tmpdir.
347
+ const fromDir = parent?.filename ? path.dirname(parent.filename) : projectRoot;
348
+ const deep =
349
+ resolveDeepPackageFile(request, fromDir, platform, activeSourceExts) ??
350
+ (fromDir === projectRoot
351
+ ? null
352
+ : resolveDeepPackageFile(request, projectRoot, platform, activeSourceExts));
353
+ if (deep === null) throw err;
354
+ resolved = deep;
355
+ }
356
+ }
357
+ // Diagnostics only. The comparison sees Node's resolution and the package
358
+ // manifest, never Vite's module graph, so it cannot tell a package both graphs
359
+ // load from one only Node ever requires — and the ecosystem is full of the
360
+ // latter (Babel's source-map packages, RNTL's own test-renderer). Reported as
361
+ // noise on every test file (#201); kept as an opt-in diagnostic for the silent
362
+ // duplicate-instance failure it was written to surface.
363
+ if (process.env.VITEST_NATIVE_DIAGNOSTICS === "true") {
364
+ checkResolverAgreement(request, resolved);
306
365
  }
307
- checkResolverAgreement(request, resolved);
308
- checkProjectSourceLoadedByNode(resolved, parent);
366
+ // Every successful resolution (including platform hits) crosses this boundary.
367
+ checkProjectSourceResolvedByNode(resolved, parent, projectDirs(), ownership);
309
368
  return resolved;
310
369
  };
311
370
 
312
371
  const origJs = Module._extensions[".js"];
313
372
  Module._extensions[".js"] = function (mod, filename) {
314
373
  const norm = filename.replace(/\\/g, "/");
315
- const boundary = boundarySourceFor(norm, platform, reactNativeVersion);
374
+ const rnPath = ownership.reactNativePathFor(filename);
375
+ const boundary = boundarySourceFor(rnPath ?? norm, platform, reactNativeVersion);
316
376
  if (boundary != null) return mod._compile(boundary, filename);
317
- if (REACT_NATIVE_PATH.test(norm)) {
377
+ if (rnPath !== null) {
318
378
  const src = fs.readFileSync(filename, "utf8");
319
379
  if (isFlow(src))
320
380
  return mod._compile(transformRN(filename, src, projectRoot, platform), filename);