vitest-native 0.14.0-rc.9 → 0.14.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 (97) hide show
  1. package/README.md +76 -60
  2. package/dist/cli.d.mts +1 -3
  3. package/dist/cli.mjs +175 -63
  4. package/dist/context.d.mts +45 -0
  5. package/dist/context.mjs +243 -0
  6. package/dist/errors.d.mts +3 -0
  7. package/dist/helpers.cjs +53 -4
  8. package/dist/helpers.d.cts +1 -3
  9. package/dist/helpers.d.mts +1 -3
  10. package/dist/helpers.mjs +2 -3
  11. package/dist/host-5o48Ujzs.mjs +939 -0
  12. package/dist/{index-CzQazgp9.d.cts → index-DqU4YO3D.d.mts} +27 -49
  13. package/dist/index.d.mts +1 -3
  14. package/dist/index.mjs +463 -595
  15. package/dist/jest-compat/error-equality.mjs +127 -0
  16. package/dist/jest-compat/jest-object.mjs +149 -4
  17. package/dist/jest-compat/node-registry.mjs +233 -58
  18. package/dist/jest-compat/setup.mjs +28 -4
  19. package/dist/jest-compat.cjs +227 -52
  20. package/dist/jest-compat.d.cts +5 -6
  21. package/dist/jest-compat.d.mts +5 -6
  22. package/dist/jest-compat.mjs +204 -52
  23. package/dist/matchers.cjs +1 -2
  24. package/dist/matchers.d.cts +0 -2
  25. package/dist/matchers.d.mts +0 -2
  26. package/dist/matchers.mjs +1 -2
  27. package/dist/{memory-FYbP0_gg.mjs → memory-Couw0Esx.mjs} +31 -6
  28. package/dist/native/assets.d.mts +2 -0
  29. package/dist/native/assets.mjs +34 -0
  30. package/dist/native/babel-toolchain.mjs +190 -0
  31. package/dist/native/babel-worker.mjs +47 -0
  32. package/dist/native/boundary.mjs +23 -8
  33. package/dist/native/compile-cache.mjs +21 -9
  34. package/dist/native/coverage-v8.mjs +287 -0
  35. package/dist/native/esm-interop.mjs +216 -0
  36. package/dist/native/expo-native-modules.mjs +7 -1
  37. package/dist/native/globals.mjs +104 -6
  38. package/dist/native/hooks.mjs +271 -60
  39. package/dist/native/loader.mjs +378 -20
  40. package/dist/native/match.d.mts +24 -2
  41. package/dist/native/match.mjs +117 -12
  42. package/dist/native/metro-profile-compiler.mjs +2 -31
  43. package/dist/native/module-reset.mjs +37 -5
  44. package/dist/native/native-modules.d.mts +2 -3
  45. package/dist/native/native-modules.mjs +22 -21
  46. package/dist/native/ownership.d.mts +10 -0
  47. package/dist/native/ownership.mjs +96 -9
  48. package/dist/native/registry-compiler.mjs +6 -0
  49. package/dist/native/registry.mjs +138 -119
  50. package/dist/native/resident-health.mjs +133 -0
  51. package/dist/native/resolve.d.mts +6 -0
  52. package/dist/native/resolve.mjs +100 -9
  53. package/dist/native/rntl-hooks.mjs +157 -6
  54. package/dist/native/rntl-text-host.mjs +64 -0
  55. package/dist/native/runner.mjs +73 -0
  56. package/dist/native/setup.mjs +96 -70
  57. package/dist/native/state-manifest.mjs +14 -8
  58. package/dist/native/transform.d.mts +2 -0
  59. package/dist/native/transform.mjs +476 -59
  60. package/dist/native/worker.mjs +65 -36
  61. package/dist/{pool-DjpOjOf3.mjs → pool-CFSpNfyw.mjs} +37 -11
  62. package/dist/{preset-map-BlBriTA0.mjs → preset-map-CogjYmSw.mjs} +4 -19
  63. package/dist/preset-modules.mjs +2 -11
  64. package/dist/{presets--zrEWQC2.mjs → presets-CXDyg51l.mjs} +65 -82
  65. package/dist/presets.d.mts +1 -1
  66. package/dist/presets.mjs +1 -1
  67. package/dist/report-error.d.mts +20 -0
  68. package/dist/report-error.mjs +145 -0
  69. package/dist/rntl-support.d.mts +12 -0
  70. package/dist/rntl-support.mjs +189 -0
  71. package/dist/{rolldown-runtime-BhDjJH2R.mjs → rolldown-runtime-D70C1uOS.mjs} +1 -2
  72. package/dist/serializer.cjs +1 -2
  73. package/dist/serializer.d.cts +1 -3
  74. package/dist/serializer.d.mts +1 -3
  75. package/dist/serializer.mjs +1 -2
  76. package/dist/setup.mjs +95 -156
  77. package/dist/{worker-vitest-BGPo0ek6.mjs → worker-vitest-CILPFeRX.mjs} +2 -3
  78. package/docs/migrating-from-jest.md +76 -12
  79. package/docs/release-readiness.md +1 -1
  80. package/package.json +119 -102
  81. package/CHANGELOG.md +0 -2491
  82. package/dist/cli.cjs +0 -1951
  83. package/dist/cli.d.cts +0 -3
  84. package/dist/ecosystem-D6e1OVOg.mjs +0 -1019
  85. package/dist/ecosystem-MFwkbnaC.cjs +0 -1099
  86. package/dist/errors-B3lJK46O.cjs +0 -75
  87. package/dist/errors-CxoBUfVJ.mjs +0 -64
  88. package/dist/index-xw43lBlv.d.mts +0 -481
  89. package/dist/memory-6EPHrJA1.cjs +0 -144
  90. package/dist/pool-B4yesGhI.cjs +0 -121
  91. package/dist/preset-map-jSFsNy1Q.cjs +0 -241
  92. package/dist/preset-modules-BoLkaeEN.cjs +0 -53
  93. package/dist/preset-modules-CG8-G82P.mjs +0 -36
  94. package/dist/presets-9f83H0WW.cjs +0 -3939
  95. package/dist/rolldown-runtime-C0BPl7ul.cjs +0 -43
  96. package/dist/worker-vitest-BfiQB8ND.cjs +0 -62
  97. package/docs/hot-default-design.md +0 -216
@@ -17,6 +17,7 @@ import { expandAlias } from "./aliases.mjs";
17
17
  import { resolvePlatformFile, resolveRelativePlatformFile } from "../native/resolve.mjs";
18
18
  import { resetEvaluatedModules, restoreEvaluatedModules } from "../native/module-reset.mjs";
19
19
  import { VitestNativeError } from "../errors.mjs";
20
+ import { projectContext } from "../context.mjs";
20
21
 
21
22
  const STATE = "__vitest_native_jest_registry";
22
23
  /** The manifest id under which the hot runtime clears the registry per file. */
@@ -30,25 +31,18 @@ const UNRESETTABLE = /\.node$/;
30
31
  const SOURCE_FILE = /\.[cm]?[jt]sx?$/;
31
32
  const NONE = Symbol("vitest-native.jest-registry.none");
32
33
 
33
- function envList(name) {
34
- try {
35
- const value = JSON.parse(process.env[name] || "[]");
36
- return Array.isArray(value) ? value : [];
37
- } catch {
38
- return [];
39
- }
40
- }
34
+ const context = projectContext();
41
35
 
42
36
  /** Configuration the plugin hands the worker, shared with the compat setup. */
43
37
  export const config = {
44
- projectRoot: process.env.VITEST_NATIVE_PROJECT_ROOT || process.cwd(),
45
- platform: process.env.VITEST_NATIVE_PLATFORM === "android" ? "android" : "ios",
38
+ projectRoot: context?.projectRoot ?? process.cwd(),
39
+ platform: context?.platform === "android" ? "android" : "ios",
46
40
  // The project's string-to-string `resolve.alias` entries (and tsconfig `paths` when
47
41
  // Vite resolves them), which Node knows nothing of.
48
- aliases: envList("VITEST_NATIVE_REQUIRE_ALIASES"),
49
- skippedAliases: envList("VITEST_NATIVE_REQUIRE_ALIASES_SKIPPED"),
42
+ aliases: context?.requireAliases ?? [],
43
+ skippedAliases: context?.requireAliasesSkipped ?? [],
50
44
  };
51
- const sourceExts = envList("VITEST_NATIVE_SOURCE_EXTS");
45
+ const sourceExts = context?.sourceExts ?? [];
52
46
 
53
47
  const realpathCache = new Map();
54
48
  /** Node keys its cache by real path; a platform-variant scan does not resolve links. */
@@ -79,7 +73,7 @@ const worker = () => globalThis.__vitest_worker__;
79
73
  function createState() {
80
74
  const rootFile = path.join(config.projectRoot, "package.json");
81
75
  const rootParent = parentModuleFor(rootFile);
82
- const registryFile = process.env.VITEST_NATIVE_RN_REGISTRY;
76
+ const registryFile = context?.registry;
83
77
  const realRegistryFile = registryFile ? canonical(registryFile) : null;
84
78
  const exts = sourceExts.length > 0 ? sourceExts : undefined;
85
79
  const platformFile = (base) => {
@@ -102,8 +96,13 @@ function createState() {
102
96
  bypass: null,
103
97
  /** The open isolateModules block, if any. */
104
98
  isolation: null,
105
- /** Module._cache keys present when the registry was installed: never reset. */
99
+ /**
100
+ * Module._cache keys a reset never drops. Taken when the registry is created, then
101
+ * once more where the native setup installs the sharing (`shareProjectModules`), so a
102
+ * library's Jest setup or a preset that creates the registry earlier cannot shrink it.
103
+ */
106
104
  baseline: new Set(Object.keys(Module._cache)),
105
+ baselineFixed: false,
107
106
  };
108
107
 
109
108
  // Resolve as the require hooks will, so registration and lookup share one key:
@@ -136,13 +135,21 @@ function createState() {
136
135
  }
137
136
  }
138
137
 
138
+ /**
139
+ * How often the load hook asked `state.resolve`, how often that resolved afresh rather
140
+ * than from its cache, and how often a request went to Node without either.
141
+ */
142
+ state.stats = { resolves: 0, uncached: 0, toNode: 0 };
143
+
139
144
  /** Cached: resolution does not change within a worker, whatever is mocked. */
140
145
  state.resolve = (request, parent) => {
141
146
  if (typeof request !== "string" || Module.isBuiltin(request)) return null;
147
+ state.stats.resolves++;
142
148
  parent ??= rootParent;
143
149
  const key = `${parent.filename}\0${request}`;
144
150
  let filename = state.resolutions.get(key);
145
151
  if (filename === undefined) {
152
+ state.stats.uncached++;
146
153
  filename = resolveUncached(request, parent);
147
154
  state.resolutions.set(key, filename);
148
155
  }
@@ -156,24 +163,81 @@ function createState() {
156
163
  };
157
164
 
158
165
  // The memoized mock: `requireMock` caches the factory's result in `_mockRegistry`.
166
+ //
167
+ // A factory jestMockTransform made async (its `jest.requireActual` of project source
168
+ // now loads through Vite: see transform.ts) yields a promise, as does one the author
169
+ // wrote async. What is memoized is the SETTLED value, so every load gets the same
170
+ // object, never the promise: Vite's import awaits it (`valueForImport`), and Vite
171
+ // runs the factory while it evaluates the test file's imports, so a `require()` or
172
+ // `jest.requireMock` in the test body finds it settled. A Node-side load that comes
173
+ // first runs the synchronous original instead, which is what it did before the
174
+ // rewrite, and Vite's import then gets that value. One that comes while the promise
175
+ // is pending — Node requiring the module from inside its own factory's import graph,
176
+ // a cycle — cannot wait, so it throws, as the synchronous cycle does.
177
+ const settle = (entry, factory) => {
178
+ entry.evaluating = true;
179
+ let result;
180
+ try {
181
+ result = factory();
182
+ } finally {
183
+ entry.evaluating = false;
184
+ }
185
+ // By tag, not by a `then` method: see jestMockInterop in interop.mjs.
186
+ if (Object.prototype.toString.call(result) !== "[object Promise]") {
187
+ entry.value = result;
188
+ entry.has = true;
189
+ return result;
190
+ }
191
+ const pending = result.then(
192
+ (value) => {
193
+ if (entry.pending === pending) {
194
+ entry.pending = null;
195
+ entry.value = value;
196
+ entry.has = true;
197
+ }
198
+ return value;
199
+ },
200
+ (error) => {
201
+ if (entry.pending === pending) entry.pending = null;
202
+ throw error;
203
+ },
204
+ );
205
+ entry.pending = pending;
206
+ return pending;
207
+ };
208
+ const cycle = (entry) =>
209
+ // Jest would re-enter the factory here until the stack overflowed.
210
+ new VitestNativeError(
211
+ "JEST_MOCK_FACTORY_CYCLE",
212
+ `the jest.mock factory for '${entry.spec}' requires the module it mocks. ` +
213
+ "Use jest.requireActual() inside the factory for the real module.",
214
+ );
215
+
216
+ /** The mock for a Node-side load, which cannot wait for a promise. */
159
217
  state.valueOf = (entry) => {
160
218
  if (entry.has) return entry.value;
161
- if (entry.evaluating) {
162
- // Jest would re-enter the factory here until the stack overflowed.
219
+ if (entry.evaluating) throw cycle(entry);
220
+ if (entry.pending) {
221
+ // An author's own async factory has always handed Node its promise.
222
+ if (!entry.asyncFactory) return entry.pending;
163
223
  throw new VitestNativeError(
164
224
  "JEST_MOCK_FACTORY_CYCLE",
165
- `the jest.mock factory for '${entry.spec}' requires the module it mocks. ` +
166
- "Use jest.requireActual() inside the factory for the real module.",
225
+ `'${entry.spec}' was required while its jest.mock factory was still loading the ` +
226
+ "real module, which require() cannot wait for. Something that factory loads " +
227
+ "requires the mocked module back; break the cycle, or import the module instead.",
167
228
  );
168
229
  }
169
- entry.evaluating = true;
170
- try {
171
- entry.value = entry.factory();
172
- entry.has = true;
173
- } finally {
174
- entry.evaluating = false;
175
- }
176
- return entry.value;
230
+ // An async factory the author wrote has no synchronous original, so this load gets
231
+ // its promise, as it always has; later loads get the settled value.
232
+ return settle(entry, entry.factory);
233
+ };
234
+
235
+ /** The mock for Vite's import: the settled value, or a promise of it. */
236
+ state.valueForImport = (entry) => {
237
+ if (entry.has) return entry.value;
238
+ if (entry.pending) return entry.pending;
239
+ if (entry.evaluating) throw cycle(entry);
240
+ return settle(entry, entry.asyncFactory ?? entry.factory);
177
241
  };
178
242
 
179
243
  /** The entry a load of `request` (resolved to `filename`) is served, if any. */
@@ -188,9 +252,18 @@ function createState() {
188
252
  return filename !== null ? state.entries.get(filename) : state.unresolved.get(request);
189
253
  };
190
254
 
191
- state.register = (from, spec, factory) => {
255
+ // `asyncFactory` is jestMockTransform's async variant of `factory`, when it made one.
256
+ state.register = (from, spec, factory, asyncFactory) => {
192
257
  const filename = state.resolveFrom(spec, from);
193
- const entry = { spec, factory, has: false, value: undefined, evaluating: false };
258
+ const entry = {
259
+ spec,
260
+ factory,
261
+ asyncFactory,
262
+ has: false,
263
+ value: undefined,
264
+ pending: null,
265
+ evaluating: false,
266
+ };
194
267
  if (filename !== null) state.entries.set(filename, entry);
195
268
  else state.unresolved.set(spec, entry);
196
269
  // The hoisted `vi.mock` factory looks its entry up by where it was written.
@@ -258,6 +331,7 @@ function createState() {
258
331
  const forget = (entry) => {
259
332
  entry.has = false;
260
333
  entry.value = undefined;
334
+ entry.pending = null;
261
335
  };
262
336
 
263
337
  /**
@@ -271,12 +345,12 @@ function createState() {
271
345
  * reachable, for the caller to fall back to `vi.resetModules()`.
272
346
  */
273
347
  state.resetModules = () => {
274
- const map = worker()?.evaluatedModules?.idToModuleMap;
275
- if (map) resetEvaluatedModules(map);
348
+ const modules = worker()?.evaluatedModules;
349
+ if (modules) resetEvaluatedModules(modules);
276
350
  state.isolation = null;
277
351
  state.dropProjectModules();
278
352
  allEntries().forEach(forget);
279
- return Boolean(map);
353
+ return Boolean(modules);
280
354
  };
281
355
 
282
356
  /**
@@ -294,13 +368,13 @@ function createState() {
294
368
  // name and own properties included, so only this matches a suite written for Jest.
295
369
  throw new Error(`${name} cannot be nested inside another ${name} or ${other}.`);
296
370
  }
297
- const map = worker()?.evaluatedModules?.idToModuleMap;
371
+ const modules = worker()?.evaluatedModules;
298
372
  const isolation = {
299
373
  modules: state.dropProjectModules(),
300
374
  had: new Set(allEntries().filter((entry) => entry.has)),
301
- vite: map ? new Map() : null,
375
+ vite: modules ? new Map() : null,
302
376
  };
303
- if (map) resetEvaluatedModules(map, isolation.vite);
377
+ if (modules) resetEvaluatedModules(modules, isolation.vite);
304
378
  state.isolation = isolation;
305
379
  return () => {
306
380
  // `resetModules` inside the block ended it, as in Jest, where it nulls the
@@ -312,7 +386,7 @@ function createState() {
312
386
  allEntries()
313
387
  .filter((entry) => !isolation.had.has(entry))
314
388
  .forEach(forget);
315
- if (map) restoreEvaluatedModules(map, isolation.vite);
389
+ if (modules) restoreEvaluatedModules(modules, isolation.vite);
316
390
  };
317
391
  };
318
392
 
@@ -338,14 +412,28 @@ export function nodeRegistry() {
338
412
  installLoadHook(state);
339
413
  if (typeof worker()?.evaluatedModules?.getModulesByFile !== "function") {
340
414
  console.warn(
341
- "[vitest-native] jest-compat cannot reach Vitest's module graph in this worker, so " +
342
- "require() may load a second copy of a module the test imported, and " +
415
+ "[vitest-native] cannot reach Vitest's module graph in this worker, so require() " +
416
+ "may load a second copy of a project module the test imported, and " +
343
417
  "jest.isolateModulesAsync() does not isolate import().",
344
418
  );
345
419
  }
346
420
  return state;
347
421
  }
348
422
 
423
+ /**
424
+ * Installed by the native engine's setup in every worker, so a project file that a test
425
+ * imports and that Node later `require`s is one module (`viteInstanceOf`). It is the same
426
+ * registry jest-compat uses; before this, only jest-compat or a library's Jest setup
427
+ * created it, so whether a project file loaded once or twice depended on those. Its call
428
+ * is also the fixed point the registry's baseline is taken at, once per worker.
429
+ */
430
+ export function shareProjectModules() {
431
+ const state = nodeRegistry();
432
+ if (state.baselineFixed) return;
433
+ state.baseline = new Set(Object.keys(Module._cache));
434
+ state.baselineFixed = true;
435
+ }
436
+
349
437
  /**
350
438
  * Vite's instance of a project module this file already evaluated, for a CommonJS
351
439
  * consumer, or NONE — so `require('./store')` after `import './store'` is one module,
@@ -363,30 +451,105 @@ function viteInstanceOf(filename) {
363
451
  for (const node of nodes ?? []) {
364
452
  if (node.id?.startsWith("mock:") || !node.evaluated || node.exports == null) continue;
365
453
  const ns = node.exports;
366
- if ("value" in (Object.getOwnPropertyDescriptor(ns, "default") ?? {})) return NONE;
367
- let facade = viteFacades.get(ns);
368
- if (!facade) {
369
- facade = new Proxy(ns, {
370
- get: (target, key, receiver) =>
371
- key === "__esModule" && !Reflect.has(target, key)
372
- ? true
373
- : Reflect.get(target, key, receiver),
374
- has: (target, key) => key === "__esModule" || Reflect.has(target, key),
375
- set: (target, key, value) =>
376
- Reflect.defineProperty(target, key, {
377
- value,
378
- writable: true,
379
- enumerable: true,
380
- configurable: true,
381
- }),
382
- });
383
- viteFacades.set(ns, facade);
384
- }
385
- return facade;
454
+ if (isCommonJsNamespace(ns)) return NONE;
455
+ return requireFacade(ns);
386
456
  }
387
457
  return NONE;
388
458
  }
389
459
 
460
+ /**
461
+ * A bare specifier (a package name). Aliases need no check here: the require hooks
462
+ * apply them only after Node fails, so Node's answer for an aliased name is already the
463
+ * one `state.resolve` would reach.
464
+ */
465
+ function isBare(request) {
466
+ return !(request.startsWith(".") || path.isAbsolute(request) || request.startsWith("file:"));
467
+ }
468
+
469
+ /**
470
+ * Node's real path for `request` from `parent` (the require hooks' resolver included), the
471
+ * same call `state.resolve` makes, or null when Node cannot resolve it.
472
+ */
473
+ function nodeResolution(request, parent) {
474
+ try {
475
+ const resolved = Module._resolveFilename(request, parent, false);
476
+ return Module.isBuiltin(resolved) ? null : canonical(resolved);
477
+ } catch {
478
+ return null;
479
+ }
480
+ }
481
+
482
+ /** Vite's namespace for CommonJS: `module.exports` as a plain `default` data property. */
483
+ const isCommonJsNamespace = (ns) =>
484
+ "value" in (Object.getOwnPropertyDescriptor(ns, "default") ?? {});
485
+
486
+ /**
487
+ * What `jest.requireActual` returns for a module `vi.importActual` loaded, for a factory
488
+ * jestMockTransform made async (transform.ts): `module.exports` for CommonJS, so
489
+ * `jest.requireActual('./legacy')()` still calls the function a CommonJS file exports.
490
+ *
491
+ * For an ES module, an object as babel-jest's `require()` gives one: `__esModule`, and
492
+ * a member per export that reads the module live. Vite seals a module's namespace, so
493
+ * the namespace itself (or a Proxy over it) cannot take the writes a Jest factory makes
494
+ * to the actual module (`actual.other = jest.fn(); return actual`); here a write
495
+ * replaces that member, and a new key is added, on this object only. One object per
496
+ * module, so every `requireActual` of it in a file is the same object, as under Jest.
497
+ */
498
+ const actualObjects = new WeakMap();
499
+ export function actualExports(ns) {
500
+ if (ns == null || typeof ns !== "object") return ns;
501
+ if (isCommonJsNamespace(ns)) return ns.default;
502
+ let actual = actualObjects.get(ns);
503
+ if (actual) return actual;
504
+ actual = {};
505
+ for (const key of Object.keys(ns)) {
506
+ Object.defineProperty(actual, key, {
507
+ enumerable: true,
508
+ configurable: true,
509
+ get: () => ns[key],
510
+ set: (value) => {
511
+ Object.defineProperty(actual, key, {
512
+ value,
513
+ writable: true,
514
+ enumerable: true,
515
+ configurable: true,
516
+ });
517
+ },
518
+ });
519
+ }
520
+ if (!("__esModule" in actual)) {
521
+ Object.defineProperty(actual, "__esModule", {
522
+ value: true,
523
+ configurable: true,
524
+ writable: true,
525
+ });
526
+ }
527
+ actualObjects.set(ns, actual);
528
+ return actual;
529
+ }
530
+
531
+ function requireFacade(ns) {
532
+ let facade = viteFacades.get(ns);
533
+ if (!facade) {
534
+ facade = new Proxy(ns, {
535
+ get: (target, key, receiver) =>
536
+ key === "__esModule" && !Reflect.has(target, key)
537
+ ? true
538
+ : Reflect.get(target, key, receiver),
539
+ has: (target, key) => key === "__esModule" || Reflect.has(target, key),
540
+ set: (target, key, value) =>
541
+ Reflect.defineProperty(target, key, {
542
+ value,
543
+ writable: true,
544
+ enumerable: true,
545
+ configurable: true,
546
+ }),
547
+ });
548
+ viteFacades.set(ns, facade);
549
+ }
550
+ return facade;
551
+ }
552
+
390
553
  function installLoadHook(state) {
391
554
  const origLoad = Module._load;
392
555
  Module._load = function (request, parent, ...rest) {
@@ -400,6 +563,18 @@ function installLoadHook(state) {
400
563
  if ((!fromProject && state.isEmpty()) || Module.isBuiltin(request)) {
401
564
  return origLoad.call(this, request, parent, ...rest);
402
565
  }
566
+ // With no mocks, only a project file can be served from Vite. For a bare specifier,
567
+ // Node's own answer decides: a file under node_modules goes to Node's loader as is;
568
+ // anything else (a workspace link to source, a package's self-reference, an alias the
569
+ // hooks apply) is resolved as below, reusing that answer.
570
+ if (state.isEmpty() && isBare(request)) {
571
+ const resolved = nodeResolution(request, parent);
572
+ if (resolved !== null && NODE_MODULES.test(resolved)) {
573
+ state.stats.toNode++;
574
+ return origLoad.call(this, request, parent, ...rest);
575
+ }
576
+ if (resolved !== null) state.resolutions.set(`${parent.filename}\0${request}`, resolved);
577
+ }
403
578
  const filename = state.resolve(request, parent);
404
579
  const entry = state.lookup(filename, request);
405
580
  if (entry !== undefined) return state.valueOf(entry);
@@ -11,14 +11,15 @@
11
11
  // this entry) to rewrite top-level jest.mock/unmock/doMock to the hoisted vi.*
12
12
  // form at transform time. `jest.fn`, `jest.spyOn`, `jest.requireActual`,
13
13
  // `jest.useFakeTimers` work at runtime via the `jest` global installed here.
14
- import { vi } from "vitest";
14
+ import { expect, vi } from "vitest";
15
15
  import { createRequire } from "node:module";
16
16
  import path from "node:path";
17
17
  import { jestMockInterop } from "./interop.mjs";
18
18
  import { installJestObject } from "./jest-object.mjs";
19
19
  import { callerFile } from "./caller.mjs";
20
+ import { errorsWithMethodsEquality } from "./error-equality.mjs";
20
21
  import { VitestNativeError } from "../errors.mjs";
21
- import { NODE_MOCKS_STATE_ID, config, nodeRegistry } from "./node-registry.mjs";
22
+ import { NODE_MOCKS_STATE_ID, actualExports, config, nodeRegistry } from "./node-registry.mjs";
22
23
 
23
24
  // The global `require` below resolves from the consumer project root.
24
25
  const require = createRequire(path.join(config.projectRoot, "package.json"));
@@ -206,6 +207,25 @@ if (typeof vi.retryTimes !== "function") {
206
207
  // keeps Vitest's meaning, and Vitest has no isolateModules to extend.
207
208
  globalThis.jest = installJestObject(vi, { resetModules, isolateModules, isolateModulesAsync });
208
209
 
210
+ // Two identical errors whose class assigns methods as instance fields (zod 3's
211
+ // ZodError) are never equal under Vitest, which compares an error's own properties and
212
+ // so its per-instance closures; Jest compares errors by message. See error-equality.mjs
213
+ // for why the tester ignores only those methods rather than adopting Jest's rule.
214
+ //
215
+ // The testers live in Vitest's expect state, which outlives this file under the hot
216
+ // runtime, and each evaluation of this file brings a new function. Look for a tester
217
+ // carrying the marker in the list itself (`globalThis[Symbol.for('$$jest-matchers-
218
+ // object')]` is where `expect.addEqualityTesters` pushes, in Jest and Vitest alike), so
219
+ // it is registered once however many files the worker runs.
220
+ const ERROR_METHODS_EQUALITY = Symbol.for("vitest-native.jest-compat.error-methods-equality");
221
+ {
222
+ const registered = globalThis[Symbol.for("$$jest-matchers-object")]?.customEqualityTesters;
223
+ if (!registered?.some((tester) => tester?.[ERROR_METHODS_EQUALITY])) {
224
+ errorsWithMethodsEquality[ERROR_METHODS_EQUALITY] = true;
225
+ expect.addEqualityTesters([errorsWithMethodsEquality]);
226
+ }
227
+ }
228
+
209
229
  // Jest sets `JEST_WORKER_ID` in every worker (jest-worker: `JEST_WORKER_ID:
210
230
  // String(workerId + 1)`; jest-runner sets "1" when running in band), and code written for Jest tests
211
231
  // for it to detect a test run — e.g. picking a local or production endpoint with
@@ -227,7 +247,8 @@ if (typeof globalThis.__vnInteropMock !== "function") globalThis.__vnInteropMock
227
247
  // the memoized value through the CJS interop; Node's `require` gets the raw value.
228
248
  {
229
249
  const registry = nodeRegistry();
230
- globalThis.__vnJestMock = (from, spec, factory) => void registry.register(from, spec, factory);
250
+ globalThis.__vnJestMock = (from, spec, factory, asyncFactory) =>
251
+ void registry.register(from, spec, factory, asyncFactory);
231
252
  globalThis.__vnJestMocked = (from, spec) => {
232
253
  const entry = registry.byCall.get(`${from}\0${spec}`);
233
254
  if (entry === undefined) {
@@ -236,8 +257,11 @@ if (typeof globalThis.__vnInteropMock !== "function") globalThis.__vnInteropMock
236
257
  `the jest.mock('${spec}') factory was not registered in this test file.`,
237
258
  );
238
259
  }
239
- return jestMockInterop(registry.valueOf(entry));
260
+ return jestMockInterop(registry.valueForImport(entry));
240
261
  };
262
+ // A factory's `jest.requireActual` of project source that jestMockTransform moved to
263
+ // `vi.importActual` (transform.ts) gets its result in the shape requireActual gives.
264
+ globalThis.__vnActualExports = actualExports;
241
265
  globalThis.__vnJestUnmock = (from, spec) => registry.unregister(from, spec);
242
266
  // Registrations are per test file, as in Jest. This file evaluates before each test
243
267
  // file, so a worker reused without the hot runtime (`isolate: false`, or a watch