vitest-native 0.14.1 → 0.15.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 (89) hide show
  1. package/README.md +11 -10
  2. package/dist/cli.d.mts +9 -1
  3. package/dist/cli.mjs +2609 -361
  4. package/dist/context.d.mts +19 -0
  5. package/dist/context.mjs +47 -1
  6. package/dist/docs-url.d.mts +4 -0
  7. package/dist/docs-url.mjs +9 -0
  8. package/dist/errors.d.mts +21 -1
  9. package/dist/hang-watch-setup.mjs +55 -0
  10. package/dist/hang-watch.d.mts +56 -0
  11. package/dist/hang-watch.mjs +343 -0
  12. package/dist/helpers.cjs +24 -53
  13. package/dist/helpers.mjs +22 -1
  14. package/dist/host-D0r3P_T1.mjs +1985 -0
  15. package/dist/{index-aNBCTfA5.d.mts → index-JOR602XU.d.mts} +105 -2
  16. package/dist/index.d.mts +2 -1
  17. package/dist/index.mjs +723 -149
  18. package/dist/jest-compat/aliases.d.mts +1 -0
  19. package/dist/jest-compat/aliases.mjs +11 -0
  20. package/dist/jest-compat/interop.mjs +1 -1
  21. package/dist/jest-compat/jest-object.mjs +23 -5
  22. package/dist/jest-compat/node-registry.mjs +836 -68
  23. package/dist/jest-compat/setup.mjs +205 -12
  24. package/dist/jest-compat.cjs +383 -47
  25. package/dist/jest-compat.d.cts +19 -2
  26. package/dist/jest-compat.d.mts +19 -2
  27. package/dist/jest-compat.mjs +232 -47
  28. package/dist/matchers.d.cts +0 -1
  29. package/dist/matchers.d.mts +0 -1
  30. package/dist/native/assets.mjs +3 -1
  31. package/dist/native/babel-caller.d.mts +13 -0
  32. package/dist/native/babel-caller.mjs +24 -0
  33. package/dist/native/babel-toolchain.mjs +27 -3
  34. package/dist/native/boundary.mjs +45 -8
  35. package/dist/native/bounded-process.mjs +63 -5
  36. package/dist/native/bridge-client.mjs +133 -0
  37. package/dist/native/bridge-server.mjs +215 -0
  38. package/dist/native/bridge-thread.mjs +79 -0
  39. package/dist/native/bridge.mjs +512 -0
  40. package/dist/native/compile-error.mjs +120 -0
  41. package/dist/native/explain.mjs +3 -2
  42. package/dist/native/expo-module-mocks.mjs +2 -0
  43. package/dist/native/export-condition-recovery.mjs +20 -99
  44. package/dist/native/hooks.mjs +256 -133
  45. package/dist/native/jest-resolvers.mjs +94 -0
  46. package/dist/native/library-jest.mjs +352 -0
  47. package/dist/native/loader.mjs +167 -73
  48. package/dist/native/match.mjs +67 -7
  49. package/dist/native/module-reset.mjs +44 -49
  50. package/dist/native/ownership-ledger.d.mts +87 -0
  51. package/dist/native/ownership-ledger.mjs +524 -0
  52. package/dist/native/ownership.d.mts +20 -0
  53. package/dist/native/ownership.mjs +114 -0
  54. package/dist/native/registry-compiler.mjs +39 -5
  55. package/dist/native/registry-process.mjs +327 -28
  56. package/dist/native/registry.mjs +752 -200
  57. package/dist/native/resident-health.mjs +1 -0
  58. package/dist/native/resolve.d.mts +7 -0
  59. package/dist/native/resolve.mjs +119 -4
  60. package/dist/native/rntl-hooks.mjs +9 -5
  61. package/dist/native/rntl-text-host.mjs +5 -15
  62. package/dist/native/root-spelling.d.mts +6 -0
  63. package/dist/native/root-spelling.mjs +77 -0
  64. package/dist/native/runner.mjs +2 -19
  65. package/dist/native/setup.mjs +119 -38
  66. package/dist/native/shared-resolver.d.mts +141 -0
  67. package/dist/native/shared-resolver.mjs +719 -0
  68. package/dist/native/test-runner.mjs +26 -0
  69. package/dist/native/transform.mjs +18 -22
  70. package/dist/native/worker.mjs +9 -4
  71. package/dist/node-dispatch.mjs +293 -0
  72. package/dist/{preset-map-CogjYmSw.mjs → preset-map-DdAexIwz.mjs} +113 -2
  73. package/dist/{presets-CXDyg51l.mjs → presets-_EaSw29m.mjs} +710 -130
  74. package/dist/presets.d.mts +1 -1
  75. package/dist/presets.mjs +1 -1
  76. package/dist/rntl-matchers.d.ts +11 -15
  77. package/dist/rntl-support.mjs +28 -13
  78. package/dist/root-mocks-BNXeosbR.mjs +155 -0
  79. package/dist/serializer.cjs +7 -5
  80. package/dist/serializer.d.cts +7 -5
  81. package/dist/serializer.d.mts +7 -5
  82. package/dist/serializer.mjs +7 -5
  83. package/dist/setup.mjs +26 -27
  84. package/docs/migrating-from-jest.md +9 -232
  85. package/docs/migrating-from-vitest-react-native.md +4 -4
  86. package/docs/release-readiness.md +9 -11
  87. package/docs/versioning.md +38 -9
  88. package/package.json +59 -33
  89. package/dist/host-BAAAlSkO.mjs +0 -1028
@@ -0,0 +1,719 @@
1
+ // One resolver for every loading path, behind `experimental.ownershipModel: 'resolver'`
2
+ // (ADR-0004/0005; docs/ownership-model.md). Vite's resolveId, Node's CommonJS hook and
3
+ // its ESM loader each call `resolve` here, built from the same inputs (the project
4
+ // context's `resolverInputs`), so a package loaded by both module systems is one module.
5
+ // Bare requests only; others return null and the caller's own resolution runs. An
6
+ // `exports` target follows the context's conditions (`require` wins on both sides), a
7
+ // package without one takes its `react-native` field or the caller's `main`. Errors are
8
+ // counted as named fallbacks, never silent. A worker holds ONE resolver core for its
9
+ // CommonJS and ESM realms (workerSharedResolver): one answer memo, one package-directory
10
+ // and manifest cache; each realm gets a view that counts its own calls.
11
+ import crypto from "node:crypto";
12
+ import Module, { isBuiltin } from "node:module";
13
+ import fs from "node:fs";
14
+ import path from "node:path";
15
+ import { packageNameOf } from "./match.mjs";
16
+ import { resolvePlatformFile } from "./resolve.mjs";
17
+ import { VitestNativeError } from "../errors.mjs";
18
+
19
+ /** Requests another owner answers: the test runtime, and React Native's own graph. */
20
+ const OWNED_ELSEWHERE =
21
+ /^(?:vitest(?:\/|$)|@vitest\/|vite(?:\/|$)|chai$|react-native(?:\/|$)|@react-native\/)/;
22
+
23
+ /**
24
+ * Fallback reasons that are expected. `unresolved`: nothing on disk answers the
25
+ * request (an optional dependency probed with try/require). Anything else is a
26
+ * resolver error, which the native suite treats as a failure.
27
+ */
28
+ export const FALLBACK_ALLOWED = Object.freeze(["unresolved"]);
29
+ const UNRESOLVED_CODES = new Set(["MODULE_NOT_FOUND", "ERR_PACKAGE_PATH_NOT_EXPORTED", "ENOENT"]);
30
+
31
+ /**
32
+ * Per realm, the fallbacks counted outside FALLBACK_ALLOWED, with the errors named:
33
+ * empty when every realm resolved, or fell back only because nothing was installed.
34
+ * The native suite checks it in the workers (after each file) and in the main process
35
+ * (Vite's realm, after the run).
36
+ */
37
+ export function unexpectedFallbacks(realms = resolverCounters() ?? {}) {
38
+ const unexpected = {};
39
+ for (const [realm, counters] of Object.entries(realms)) {
40
+ for (const [reason, count] of Object.entries(counters.fallbacks)) {
41
+ if (!FALLBACK_ALLOWED.includes(reason)) (unexpected[realm] ??= {})[reason] = count;
42
+ }
43
+ if (unexpected[realm]) unexpected[realm].errors = counters.errors;
44
+ }
45
+ return unexpected;
46
+ }
47
+
48
+ /** The option's values: both resolve through the shared resolver. */
49
+ export const OWNERSHIP_MODEL_VALUES = Object.freeze(["resolver", "resolution"]);
50
+
51
+ /**
52
+ * The one key for comparing paths across realms: the native real path, the spelling Vite
53
+ * gives module ids (on-disk case, no Windows 8.3 short names, symlinks followed), or the
54
+ * resolved path when it does not exist. Answers keep Node's spelling (fs.realpathSync, its
55
+ * Module._cache key), so Node loads one module per file; anything that must decide
56
+ * whether a Vite id and a Node path are the same file, or two spellings of one directory
57
+ * are the same project, compares identityKey of each.
58
+ */
59
+ export function identityKey(file) {
60
+ try {
61
+ return fs.realpathSync.native(file);
62
+ } catch {
63
+ return path.resolve(file);
64
+ }
65
+ }
66
+
67
+ /** Per-realm counters, readable by tests and diagnostics. */
68
+ const COUNTERS = Symbol.for("vitest-native.sharedResolver");
69
+
70
+ export function resolverCounters() {
71
+ return globalThis[COUNTERS];
72
+ }
73
+
74
+ function canonicalInputs(inputs) {
75
+ return {
76
+ projectRoot: inputs.projectRoot,
77
+ platform: inputs.platform,
78
+ sourceExts: inputs.sourceExts ?? null,
79
+ preserveSymlinks: inputs.preserveSymlinks === true,
80
+ aliases: inputs.aliases ?? [],
81
+ conditions: [...(inputs.conditions ?? [])].sort(),
82
+ // It changes what the resolver answers, so every realm's copy must agree on it, and
83
+ // the caches keyed by this hash must tell it apart. Left out when empty, so the hash
84
+ // (and the registries cached under it) is unchanged for every other project.
85
+ ...(inputs.ownJestSupport?.length ? { ownJestSupport: [...inputs.ownJestSupport].sort() } : {}),
86
+ };
87
+ }
88
+
89
+ /** The hash every realm checks its copy of the inputs against. */
90
+ export function resolverInputsHash(inputs) {
91
+ return crypto
92
+ .createHash("sha256")
93
+ .update(JSON.stringify(canonicalInputs(inputs)))
94
+ .digest("hex")
95
+ .slice(0, 20);
96
+ }
97
+
98
+ // Node's resolvePackageTarget, for already-valid string targets: `undefined` means no
99
+ // condition matched (keep looking), `null` means the subpath is excluded. In a
100
+ // condition object the first matching key decides, even when its value is null; in an
101
+ // array a null entry falls through to the next.
102
+ function matchTarget(target, conditions) {
103
+ if (typeof target === "string") return target;
104
+ if (Array.isArray(target)) {
105
+ let excluded = false;
106
+ for (const entry of target) {
107
+ const match = matchTarget(entry, conditions);
108
+ if (typeof match === "string") return match;
109
+ if (match === null) excluded = true;
110
+ }
111
+ return excluded || target.length === 0 ? null : undefined;
112
+ }
113
+ if (target !== null && typeof target === "object") {
114
+ for (const [key, value] of Object.entries(target)) {
115
+ if (key === "default" || conditions.includes(key)) {
116
+ const match = matchTarget(value, conditions);
117
+ if (match !== undefined) return match;
118
+ }
119
+ }
120
+ return undefined;
121
+ }
122
+ return null;
123
+ }
124
+
125
+ // Node's patternKeyCompare: the longer base (up to and including `*`) wins, then the
126
+ // longer key. Negative when `a` ranks first.
127
+ function patternKeyCompare(a, b) {
128
+ const aStar = a.indexOf("*");
129
+ const bStar = b.indexOf("*");
130
+ const baseA = aStar === -1 ? a.length : aStar + 1;
131
+ const baseB = bStar === -1 ? b.length : bStar + 1;
132
+ if (baseA !== baseB) return baseB - baseA;
133
+ if (aStar === -1) return 1;
134
+ if (bStar === -1) return -1;
135
+ return b.length - a.length;
136
+ }
137
+
138
+ /**
139
+ * The relative target a package's `exports` gives `subpath` ("." or "./x") under
140
+ * `conditions`, or null when it gives none. Follows Node's PACKAGE_EXPORTS_RESOLVE:
141
+ * the sugar forms, exact subpaths, and single-`*` patterns ranked by patternKeyCompare.
142
+ */
143
+ export function exportTarget(exportsField, subpath, conditions) {
144
+ if (exportsField === undefined || exportsField === null) return null;
145
+ const map =
146
+ typeof exportsField === "string" ||
147
+ Array.isArray(exportsField) ||
148
+ !Object.keys(exportsField).some((key) => key.startsWith("."))
149
+ ? { ".": exportsField }
150
+ : exportsField;
151
+ if (Object.hasOwn(map, subpath) && !subpath.includes("*")) {
152
+ return matchTarget(map[subpath], conditions) ?? null;
153
+ }
154
+ let bestKey = "";
155
+ let bestMatch;
156
+ for (const key of Object.keys(map)) {
157
+ const star = key.indexOf("*");
158
+ if (star === -1 || key.lastIndexOf("*") !== star) continue;
159
+ const trailer = key.slice(star + 1);
160
+ if (
161
+ subpath.startsWith(key.slice(0, star)) &&
162
+ subpath.length >= key.length &&
163
+ subpath.endsWith(trailer) &&
164
+ patternKeyCompare(bestKey, key) > 0
165
+ ) {
166
+ bestKey = key;
167
+ bestMatch = subpath.slice(star, subpath.length - trailer.length);
168
+ }
169
+ }
170
+ if (bestMatch === undefined) return null;
171
+ const target = matchTarget(map[bestKey], conditions);
172
+ return typeof target === "string" ? target.replaceAll("*", bestMatch) : null;
173
+ }
174
+
175
+ /**
176
+ * A resolver for one realm: a view on a resolver core (createResolverCore) that counts
177
+ * this realm's calls. Each call builds its own core; a worker's realms share one through
178
+ * workerSharedResolver.
179
+ *
180
+ * @param {object} inputs the context's `resolverInputs`
181
+ * @param {object} [options]
182
+ * @param {string} [options.realm] name used in the counters
183
+ * @param {boolean} [options.memo] hold answers (default true)
184
+ * @param {boolean} [options.globalFolders] also look in NODE_PATH and the global
185
+ * folders, as Node's CommonJS resolution does (the require hooks, the registry walk);
186
+ * Node's ESM resolver and Vite do not
187
+ * @param {boolean} [options.viteAliasesApplied] the requests arrive with the project's
188
+ * string and RegExp aliases already applied: Vite's own alias plugin runs before any
189
+ * plugin's resolveId, so applying them again would expand `pkg` → `pkg/mock` twice.
190
+ * tsconfig `paths` (the `exact` and `prefix` entries) Vite applies only after, so they
191
+ * still apply.
192
+ */
193
+ /**
194
+ * A main field's file, completed the way Node completes `main`, with Metro's platform
195
+ * and source extensions. The resolver's choice, and what detection reads to decide
196
+ * whether that file needs compiling (ecosystem.ts).
197
+ *
198
+ * @param {string} target the field's value, resolved against the package directory
199
+ * @param {string} platform
200
+ * @param {readonly string[]} sourceExts
201
+ * @returns {string | null}
202
+ */
203
+ export function mainFieldFile(target, platform, sourceExts) {
204
+ if (fs.statSync(target, { throwIfNoEntry: false })?.isFile()) return target;
205
+ return (
206
+ resolvePlatformFile(target, platform, sourceExts) ??
207
+ resolvePlatformFile(path.join(target, "index"), platform, sourceExts)
208
+ );
209
+ }
210
+
211
+ export function createSharedResolver(
212
+ inputs,
213
+ {
214
+ realm = "unknown",
215
+ memo = true,
216
+ shadowFile = null,
217
+ viteAliasesApplied = false,
218
+ globalFolders = false,
219
+ } = {},
220
+ ) {
221
+ return createResolverCore(inputs, { viteAliasesApplied }).view(realm, {
222
+ memo,
223
+ shadowFile,
224
+ globalFolders,
225
+ });
226
+ }
227
+
228
+ const WORKER_CORES = Symbol.for("vitest-native.sharedResolverCores");
229
+
230
+ /**
231
+ * This worker's resolver for `realm`: every realm in a worker (the CommonJS hooks and the
232
+ * ESM loader, which run in-thread on the Node floor) shares one core, so an answer, a
233
+ * package directory or a manifest one realm found is the other's too. Kept on globalThis,
234
+ * by the inputs' hash, because the hot runtime can evaluate this module twice in a worker.
235
+ */
236
+ export function workerSharedResolver(
237
+ inputs,
238
+ realm,
239
+ { shadowFile = null, globalFolders = false } = {},
240
+ ) {
241
+ const cores = (globalThis[WORKER_CORES] ??= new Map());
242
+ const key = resolverInputsHash(inputs);
243
+ let core = cores.get(key);
244
+ if (core === undefined) cores.set(key, (core = createResolverCore(inputs)));
245
+ return core.view(realm, { memo: true, shadowFile, globalFolders });
246
+ }
247
+
248
+ function createResolverCore(inputs, { viteAliasesApplied = false } = {}) {
249
+ const { projectRoot, platform } = inputs;
250
+ const sourceExts = inputs.sourceExts ?? ["js", "jsx", "json", "ts", "tsx"];
251
+ const aliases = (inputs.aliases ?? []).filter(
252
+ ([find]) =>
253
+ !viteAliasesApplied ||
254
+ // tsconfig `paths` (the `exact` and `prefix` kinds) are not Vite aliases.
255
+ (typeof find === "object" && find !== null && ("prefix" in find || "exact" in find)),
256
+ );
257
+ const preserveSymlinks = inputs.preserveSymlinks === true;
258
+ const ownJestSupport = new Set(inputs.ownJestSupport ?? []);
259
+ // `react-native` first, as Metro and Jest's preset match it, then the realm-wide set.
260
+ const conditions = [
261
+ "react-native",
262
+ ...[...(inputs.conditions ?? [])].filter((c) => c !== "react-native").sort(),
263
+ ];
264
+ const memo = new Map();
265
+ // Package directories per (requesting directory, name), and manifests per package
266
+ // directory: a manifest is read once however many directories ask for it.
267
+ const dirs = new Map();
268
+ const manifests = new Map();
269
+ // Real paths, as Node's loader caches them (its realpath cache): see realPath.
270
+ const realDirs = new Map();
271
+ const realms = (globalThis[COUNTERS] ??= {});
272
+ let counters;
273
+
274
+ const fallback = (reason) => {
275
+ counters.fallbacks[reason] = (counters.fallbacks[reason] ?? 0) + 1;
276
+ return null;
277
+ };
278
+
279
+ // A path's real path, as fs.realpathSync spells it (Node's Module._cache key), built the
280
+ // way Node's realpath cache makes it cheap: one lstat per path segment not seen before,
281
+ // the parent's real path held. A symbolic link costs one readlink, its target resolved
282
+ // from the link's real directory; anything else is its parent's real path plus its name.
283
+ function realPath(file, hops = 0) {
284
+ let real = realDirs.get(file);
285
+ if (real !== undefined) return real;
286
+ const parent = path.dirname(file);
287
+ if (parent === file) return file;
288
+ const realParent = realPath(parent, hops);
289
+ if (fs.lstatSync(file).isSymbolicLink()) {
290
+ if (hops > 40) return fs.realpathSync(file); // a loop: let fs report ELOOP
291
+ real = realPath(path.resolve(realParent, fs.readlinkSync(file)), hops + 1);
292
+ } else {
293
+ real = path.join(realParent, path.basename(file));
294
+ }
295
+ realDirs.set(file, real);
296
+ return real;
297
+ }
298
+ const realDir = realPath;
299
+ // A file is one more segment; it is held too, as Node's cache holds every path it saw.
300
+ const realFile = realPath;
301
+
302
+ /**
303
+ * A package's directory as Node looks for it: the node_modules directories from the
304
+ * requester up (Module._nodeModulePaths), then, for a CommonJS realm only, NODE_PATH and
305
+ * the global folders (Module.globalPaths): the order of require.resolve.paths and of
306
+ * packageDirOf. Node's ESM resolver and Vite never read NODE_PATH. A package resolving
307
+ * its own name (self-reference) is left to the caller.
308
+ */
309
+ function packageDirFor(name, fromDir, globalFolders) {
310
+ const lookups = globalFolders
311
+ ? [...Module._nodeModulePaths(fromDir), ...Module.globalPaths]
312
+ : Module._nodeModulePaths(fromDir);
313
+ for (const lookup of lookups) {
314
+ const candidate = path.join(lookup, ...name.split("/"));
315
+ if (fs.existsSync(path.join(candidate, "package.json"))) {
316
+ // Under --preserve-symlinks Node keys modules by the link.
317
+ return preserveSymlinks ? candidate : realDir(candidate);
318
+ }
319
+ }
320
+ return null;
321
+ }
322
+
323
+ function packageAt(name, fromDir, globalFolders) {
324
+ const dirKey = `${globalFolders ? "g" : "-"}\0${fromDir}\0${name}`;
325
+ let dir = dirs.get(dirKey);
326
+ if (dir === undefined) {
327
+ dir = packageDirFor(name, fromDir, globalFolders);
328
+ dirs.set(dirKey, dir);
329
+ }
330
+ if (dir === null) return null;
331
+ let manifest = manifests.get(dir);
332
+ if (manifest === undefined) {
333
+ counters.manifestReads++;
334
+ manifest = JSON.parse(fs.readFileSync(path.join(dir, "package.json"), "utf8"));
335
+ manifests.set(dir, manifest);
336
+ }
337
+ return { dir, manifest };
338
+ }
339
+
340
+ const fieldFile = (target) => mainFieldFile(target, platform, sourceExts);
341
+
342
+ /**
343
+ * The real path of the file `request` from `parentFile` loads, or null to let the
344
+ * caller's own resolution decide.
345
+ *
346
+ * @param {string} request
347
+ * @param {string | undefined | null} parentFile absolute path of the requiring file
348
+ * @param {(id: string) => string} [nodeResolve] the caller's resolution, for a
349
+ * package without an `exports` target (Node's own `main`)
350
+ */
351
+ function resolveWith({ useMemo, globalFolders }, request, parentFile, nodeResolve) {
352
+ if (
353
+ typeof request !== "string" ||
354
+ request.length === 0 ||
355
+ isBuiltin(request) ||
356
+ request.startsWith("\0") ||
357
+ request.startsWith(".") ||
358
+ request.startsWith("file:") ||
359
+ path.isAbsolute(request) ||
360
+ OWNED_ELSEWHERE.test(request)
361
+ ) {
362
+ return null;
363
+ }
364
+ counters.calls++;
365
+ const fromDir =
366
+ parentFile && path.isAbsolute(parentFile) ? path.dirname(parentFile) : projectRoot;
367
+ const key = `${globalFolders ? "g" : "-"}\0${fromDir}\0${request}`;
368
+ if (useMemo) {
369
+ const held = memo.get(key);
370
+ // Another realm, or another key of the require hook's (its conditions), may have
371
+ // put it there: a file gone since (a nested copy uninstalled, a fixture a test
372
+ // deleted) is resolved again, at the cost of one stat per hit, as the hook's memo.
373
+ if (held !== undefined && fs.statSync(held, { throwIfNoEntry: false })?.isFile()) {
374
+ counters.hits++;
375
+ return held;
376
+ }
377
+ if (held !== undefined) memo.delete(key);
378
+ }
379
+ counters.misses++;
380
+ let result = null;
381
+ try {
382
+ const expanded = expandResolutionAlias(request, aliases);
383
+ if (path.isAbsolute(expanded)) {
384
+ result =
385
+ resolvePlatformFile(expanded, platform, sourceExts) ??
386
+ (fs.statSync(expanded, { throwIfNoEntry: false })?.isFile() ? expanded : null);
387
+ if (result === null) return fallback("unresolved");
388
+ } else if (OWNED_ELSEWHERE.test(expanded) || isBuiltin(expanded)) {
389
+ return null;
390
+ } else {
391
+ const name = packageNameOf(expanded);
392
+ const pkg = name ? packageAt(name, fromDir, globalFolders) : null;
393
+ if (pkg) {
394
+ const subpath = expanded === name ? "." : `.${expanded.slice(name.length)}`;
395
+ const target =
396
+ pkg.manifest.exports !== undefined && pkg.manifest.exports !== null
397
+ ? exportTarget(pkg.manifest.exports, subpath, conditions)
398
+ : undefined;
399
+ // A package that runs under its own Jest support resolves as Jest does: its
400
+ // `react-native` field is not read (decision (d), a7-readiness).
401
+ const field =
402
+ expanded === name && !ownJestSupport.has(name)
403
+ ? pkg.manifest["react-native"]
404
+ : undefined;
405
+ if (typeof target === "string" && target.startsWith("./")) {
406
+ result = path.resolve(pkg.dir, target);
407
+ } else if (target === undefined && typeof field === "string") {
408
+ // No `exports`: the `react-native` main field wins over `main`, as Metro and
409
+ // the Vite side resolve it (the field policy, ADR-0005). Node's own require
410
+ // would take `main`; under the flag it takes this, so the package is one
411
+ // module.
412
+ result = fieldFile(path.resolve(pkg.dir, field));
413
+ if (result === null) return fallback("unresolved");
414
+ } else if (nodeResolve) {
415
+ result = nodeResolve(expanded);
416
+ } else {
417
+ return null;
418
+ }
419
+ } else if (expanded !== request && nodeResolve) {
420
+ // An alias onto a package this directory cannot see: Node decides.
421
+ result = nodeResolve(expanded);
422
+ } else {
423
+ return null;
424
+ }
425
+ }
426
+ // Identity is the real file, whichever spelling reached it, unless the project
427
+ // runs with --preserve-symlinks, where Node keys modules by the link.
428
+ if (result && !preserveSymlinks) result = realFile(result);
429
+ } catch (error) {
430
+ // A package removed since its directory or manifest was held (a test deleting a
431
+ // fixture, an uninstall in watch mode): forget what was held for this request and
432
+ // let the caller's resolution answer, as it would have without the flag.
433
+ if (error?.code === "ENOENT") {
434
+ for (const dirKey of dirs.keys())
435
+ if (dirKey.slice(2).startsWith(`${fromDir}\0`)) dirs.delete(dirKey);
436
+ manifests.clear();
437
+ realDirs.clear();
438
+ }
439
+ // Node's own "no such module" answers, which the caller's resolution then gives.
440
+ const reason = UNRESOLVED_CODES.has(error?.code) ? "unresolved" : "error";
441
+ // The first few, named, so a failing gate says which request and why.
442
+ if (reason !== "unresolved" && counters.errors.length < 5) {
443
+ counters.errors.push(`${request} from ${fromDir}: ${error?.message ?? error}`);
444
+ }
445
+ return fallback(reason);
446
+ }
447
+ // Misses are not held: a file created later (a fixture, a watch edit) is found.
448
+ if (result && useMemo) memo.set(key, result);
449
+ return result;
450
+ }
451
+
452
+ /** Forget held answers: the Vite side does this when a watched file is added or removed. */
453
+ function clear() {
454
+ memo.clear();
455
+ dirs.clear();
456
+ manifests.clear();
457
+ realDirs.clear();
458
+ }
459
+
460
+ /**
461
+ * A realm's view: `resolve` and `shadow` count into that realm's counters, and share
462
+ * this core's memo and caches with every other view.
463
+ */
464
+ function view(realm, { memo: useMemo = true, shadowFile = null, globalFolders = false } = {}) {
465
+ const mode = { useMemo, globalFolders };
466
+ const own = (realms[realm] ??= {
467
+ calls: 0,
468
+ hits: 0,
469
+ misses: 0,
470
+ manifestReads: 0,
471
+ fallbacks: {},
472
+ errors: [],
473
+ // The resolution shadow: requests where the old resolution answers differently.
474
+ deltas: 0,
475
+ deltaSample: [],
476
+ });
477
+ const inRealm =
478
+ (fn) =>
479
+ (...args) => {
480
+ const outer = counters;
481
+ counters = own;
482
+ try {
483
+ return fn(...args);
484
+ } finally {
485
+ counters = outer;
486
+ }
487
+ };
488
+
489
+ /**
490
+ * Record a request where the resolution the flag replaces answers differently: the
491
+ * shadow ADR-0004 asks for, so every behaviour change on a real suite can be listed
492
+ * and explained. Each realm calls it once per distinct request it answered.
493
+ */
494
+ function shadow(request, fromFile, next, previous) {
495
+ if (previous === next || previous == null) return;
496
+ own.deltas++;
497
+ const delta = { request, from: fromFile ?? projectRoot, previous, next };
498
+ if (own.deltaSample.length < 50) own.deltaSample.push(delta);
499
+ // One JSON line per delta, every realm and worker into the one file the main
500
+ // process names (ownershipShadowFile).
501
+ if (shadowFile !== null) {
502
+ const line = `${JSON.stringify({ realm, ...delta })}\n`;
503
+ try {
504
+ fs.appendFileSync(shadowFile, line);
505
+ } catch (error) {
506
+ // The cache was cleared during a watch session: the main process recreates the
507
+ // context, not this directory.
508
+ if (error?.code !== "ENOENT") throw error;
509
+ fs.mkdirSync(path.dirname(shadowFile), { recursive: true });
510
+ fs.appendFileSync(shadowFile, line);
511
+ }
512
+ }
513
+ }
514
+
515
+ /**
516
+ * Forget the answer held for `request` from `parentFile`: the caller found the file
517
+ * gone (the require hook's stale check), so the next call resolves it afresh.
518
+ */
519
+ function forget(request, parentFile) {
520
+ const fromDir =
521
+ parentFile && path.isAbsolute(parentFile) ? path.dirname(parentFile) : projectRoot;
522
+ memo.delete(`${globalFolders ? "g" : "-"}\0${fromDir}\0${request}`);
523
+ dirs.clear();
524
+ manifests.clear();
525
+ realDirs.clear();
526
+ }
527
+
528
+ return {
529
+ resolve: inRealm((request, parentFile, nodeResolve) =>
530
+ resolveWith(mode, request, parentFile, nodeResolve),
531
+ ),
532
+ shadow,
533
+ forget,
534
+ clear,
535
+ counters: own,
536
+ conditions,
537
+ };
538
+ }
539
+
540
+ return { view };
541
+ }
542
+
543
+ /**
544
+ * The project's aliases in the resolver's format, preserving Vite's order and its
545
+ * matching rules: a string `find` matches the whole request or a prefix followed by
546
+ * `/`; a RegExp `find` matches as RegExp.test does and its replacement uses
547
+ * String.replace (capture groups included). Custom resolvers cannot cross into a
548
+ * worker and are listed as skipped.
549
+ *
550
+ * @param {unknown[]} alias `{ find, replacement }` entries, in Vite's order
551
+ * @param {string} root project root, for relative replacements
552
+ */
553
+ export function serializeResolutionAliases(alias, root) {
554
+ const entries = [];
555
+ const skipped = [];
556
+ for (const item of alias) {
557
+ const find = item?.find;
558
+ const replacement = item?.replacement;
559
+ if (
560
+ (typeof find !== "string" && !(find instanceof RegExp)) ||
561
+ typeof replacement !== "string" ||
562
+ item.customResolver
563
+ ) {
564
+ skipped.push(String(find));
565
+ continue;
566
+ }
567
+ entries.push([
568
+ find instanceof RegExp ? { source: find.source, flags: find.flags } : find,
569
+ replacement.startsWith(".") ? path.resolve(root, replacement) : replacement,
570
+ ]);
571
+ }
572
+ return { entries, skipped };
573
+ }
574
+
575
+ /** Vite's `resolve.alias` in either of its shapes, as a list. */
576
+ export function aliasList(value) {
577
+ if (Array.isArray(value)) return value;
578
+ if (value && typeof value === "object") {
579
+ return Object.entries(value).map(([find, replacement]) => ({ find, replacement }));
580
+ }
581
+ return [];
582
+ }
583
+
584
+ /**
585
+ * Apply the first matching alias, as Vite's alias plugin does. `{ exact }` entries are
586
+ * tsconfig `paths` without a wildcard, matched whole. `{ prefix }` entries
587
+ * are tsconfig `paths` wildcards (`#/*` → `src/*`), whose prefix match differs from a
588
+ * Vite string alias.
589
+ */
590
+ export function expandResolutionAlias(specifier, entries) {
591
+ for (const [find, replacement] of entries) {
592
+ if (typeof find === "object" && find !== null && "exact" in find) {
593
+ if (specifier === find.exact) return replacement;
594
+ } else if (typeof find === "object" && find !== null && "prefix" in find) {
595
+ if (specifier.startsWith(find.prefix)) {
596
+ return `${replacement.replace(/\/$/, "")}/${specifier.slice(find.prefix.length)}`;
597
+ }
598
+ } else if (typeof find === "object" && find !== null) {
599
+ const re = new RegExp(find.source, find.flags);
600
+ if (re.test(specifier)) {
601
+ return specifier.replace(new RegExp(find.source, find.flags), replacement);
602
+ }
603
+ } else if (
604
+ typeof find === "string" &&
605
+ specifier.startsWith(find) &&
606
+ (specifier.length === find.length || specifier[find.length] === "/")
607
+ ) {
608
+ return replacement + specifier.slice(find.length);
609
+ }
610
+ }
611
+ return specifier;
612
+ }
613
+
614
+ /** The `--conditions` / `-C` values in a list of Node options. */
615
+ export function conditionsIn(options) {
616
+ const out = [];
617
+ for (let i = 0; i < options.length; i++) {
618
+ const option = options[i];
619
+ let value;
620
+ if (option === "--conditions" || option === "-C") value = options[++i];
621
+ else if (option.startsWith("--conditions=")) value = option.slice("--conditions=".length);
622
+ else if (option.startsWith("-C=")) value = option.slice(3);
623
+ if (value) out.push(value);
624
+ }
625
+ return out;
626
+ }
627
+
628
+ /** Split a NODE_OPTIONS string as Node does for unquoted values. */
629
+ export function nodeOptionsList(value) {
630
+ return typeof value === "string" ? value.split(/\s+/).filter(Boolean) : [];
631
+ }
632
+
633
+ /**
634
+ * Fail by name when a realm's copy of the inputs, or the conditions Node itself
635
+ * applies in it, differ from the record the plugin wrote. Conditions compare as sets:
636
+ * Node treats them as one.
637
+ *
638
+ * @param {object} inputs the context's `resolverInputs`
639
+ * @param {string} hash the context's `resolverInputsHash`
640
+ * @param {string} realm
641
+ * @param {{ nodeConditions?: string[] }} [view] this realm's Node conditions, or
642
+ * none for the Vite realm, which resolves through the record only
643
+ */
644
+ export function checkResolverInputs(inputs, hash, realm, view = {}) {
645
+ const actual = resolverInputsHash(inputs);
646
+ if (actual !== hash) {
647
+ throw mismatch(realm, "hash", `its copy hashes to ${actual}, the context says ${hash}`);
648
+ }
649
+ if (view.nodeConditions) {
650
+ const expected = new Set(inputs.conditions);
651
+ const seen = new Set(view.nodeConditions.filter((c) => c !== "react-native"));
652
+ const missing = [...expected].filter((c) => !seen.has(c)).sort();
653
+ const extra = [...seen].filter((c) => !expected.has(c)).sort();
654
+ if (missing.length > 0 || extra.length > 0) {
655
+ throw mismatch(
656
+ realm,
657
+ "conditions",
658
+ `Node applies ${JSON.stringify([...seen].sort())} here, the context records ` +
659
+ `${JSON.stringify([...expected].sort())}` +
660
+ (extra.length ? `; only here: ${extra.join(", ")}` : "") +
661
+ (missing.length ? `; missing here: ${missing.join(", ")}` : ""),
662
+ );
663
+ }
664
+ }
665
+ }
666
+
667
+ /**
668
+ * Under `diagnostics`, where every realm writes the resolution shadow: a JSON-lines file
669
+ * in the cache directory that holds the project context, named by the resolver inputs'
670
+ * hash, so each project and configuration has its own and the main process can name it
671
+ * before the context is final. `contextRef` is the CONTEXT_ENV value ("<file>#<key>").
672
+ */
673
+ export function ownershipShadowFile(contextRef, inputsHash) {
674
+ const contextsDir = path.dirname(contextRef.slice(0, contextRef.lastIndexOf("#")));
675
+ return path.join(path.dirname(contextsDir), "ownership-shadow", `${inputsHash}.jsonl`);
676
+ }
677
+
678
+ /**
679
+ * The resolver inputs a realm builds its resolver from: null with the flag off, and the
680
+ * context's record, checked against the conditions Node applies in this worker, with it
681
+ * on. With the flag on and no record, the realm would resolve as if the flag were off
682
+ * while Vite resolves with it, so that fails by name instead.
683
+ */
684
+ export function ownershipResolverInputs(context, realm, nodeConditions) {
685
+ if (!OWNERSHIP_MODEL_VALUES.includes(context?.ownershipModel)) return null;
686
+ if (!context.resolverInputs) {
687
+ throw new VitestNativeError(
688
+ "RESOLVER_INPUTS_MISSING",
689
+ `experimental.ownershipModel: the ${realm} realm runs with the flag on, but the ` +
690
+ `project context has no resolver inputs, so it would resolve as if the flag were ` +
691
+ `off while Vite resolves with it. The plugin records them before any worker ` +
692
+ `starts; a worker reaching this ran without the plugin's configureVitest step. ` +
693
+ `Report this, with the Vitest config, as a vitest-native bug.`,
694
+ );
695
+ }
696
+ checkResolverInputs(context.resolverInputs, context.resolverInputsHash, realm, {
697
+ nodeConditions,
698
+ });
699
+ return context.resolverInputs;
700
+ }
701
+
702
+ function mismatch(realm, field, detail) {
703
+ return new VitestNativeError(
704
+ "RESOLVER_INPUT_MISMATCH",
705
+ `experimental.ownershipModel: the ${realm} realm resolves with different '${field}' ` +
706
+ `than the project context (${detail}). Every realm must resolve from the same ` +
707
+ `inputs, or a package can load twice. Set --conditions in one place ` +
708
+ `(test.execArgv, or NODE_OPTIONS for the whole run), or report this, with the ` +
709
+ `Vitest config, as a vitest-native bug.`,
710
+ );
711
+ }
712
+
713
+ /**
714
+ * Node's own CommonJS conditions for a process with these features: `require`,
715
+ * `node`, `node-addons`, and `module-sync` where require(esm) is enabled.
716
+ */
717
+ export function nodeDefaultConditions(features = process.features) {
718
+ return ["require", "node", "node-addons", ...(features?.require_module ? ["module-sync"] : [])];
719
+ }