vitest-native 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/CHANGELOG.md +921 -0
  2. package/README.md +33 -1
  3. package/dist/cli.cjs +185 -31
  4. package/dist/cli.mjs +182 -28
  5. package/dist/ecosystem-BJzJU3Cf.cjs +568 -0
  6. package/dist/ecosystem-C4qT_vl3.mjs +506 -0
  7. package/dist/errors-B3lJK46O.cjs +75 -0
  8. package/dist/errors-CxoBUfVJ.mjs +64 -0
  9. package/dist/errors.d.mts +46 -0
  10. package/dist/errors.mjs +78 -0
  11. package/dist/helpers.cjs +6 -23
  12. package/dist/helpers.d.cts +0 -6
  13. package/dist/helpers.d.mts +0 -6
  14. package/dist/helpers.mjs +6 -23
  15. package/dist/{index-CEgRDdhd.d.cts → index-CrMeE8rd.d.mts} +14 -9
  16. package/dist/{index-j-0tueBr.d.mts → index-DIMbjH8R.d.cts} +15 -7
  17. package/dist/index.d.mts +8 -7
  18. package/dist/index.mjs +307 -91
  19. package/dist/jest-compat/interop.mjs +15 -0
  20. package/dist/jest-compat/setup.mjs +102 -7
  21. package/dist/jest-compat.cjs +4 -4
  22. package/dist/jest-compat.d.cts +0 -1
  23. package/dist/jest-compat.d.mts +0 -1
  24. package/dist/jest-compat.mjs +2 -2
  25. package/dist/matchers.cjs +16 -7
  26. package/dist/matchers.mjs +16 -7
  27. package/dist/native/hooks.mjs +152 -13
  28. package/dist/native/loader.mjs +36 -11
  29. package/dist/native/match.d.mts +33 -0
  30. package/dist/native/match.mjs +94 -22
  31. package/dist/native/module-reset.mjs +63 -0
  32. package/dist/native/registry.mjs +110 -13
  33. package/dist/native/resolve.d.mts +22 -0
  34. package/dist/native/resolve.mjs +21 -13
  35. package/dist/native/runner.mjs +21 -0
  36. package/dist/native/setup.mjs +4 -2
  37. package/dist/native/transform.mjs +108 -3
  38. package/dist/native/worker.mjs +59 -16
  39. package/dist/{pool-DzsEo9vv.cjs → pool-BU-1ecIF.cjs} +7 -6
  40. package/dist/{pool-CJmjRgsB.mjs → pool-Bcxn9a3I.mjs} +4 -3
  41. package/dist/{preset-map-CG4FMtsl.cjs → preset-map-BoG19dLa.cjs} +1 -1
  42. package/dist/{preset-map-CNsZKfvu.mjs → preset-map-DuX0ocdn.mjs} +1 -1
  43. package/dist/{presets-C4faM3ds.cjs → presets-CwO_c4aL.cjs} +224 -55
  44. package/dist/{presets-CuDrNA_W.mjs → presets-IStcJEOa.mjs} +216 -53
  45. package/dist/presets.d.mts +2 -2
  46. package/dist/presets.mjs +2 -2
  47. package/dist/rntl-matchers.d.ts +35 -0
  48. package/dist/{chunk-CjcI7cDX.mjs → rolldown-runtime-BhDjJH2R.mjs} +1 -1
  49. package/dist/{chunk-CZWwpsFl.cjs → rolldown-runtime-C0BPl7ul.cjs} +1 -1
  50. package/dist/serializer.cjs +34 -4
  51. package/dist/serializer.mjs +34 -4
  52. package/dist/setup.d.mts +1 -1
  53. package/dist/setup.mjs +237 -74
  54. package/docs/release-readiness.md +22 -5
  55. package/docs/versioning.md +133 -0
  56. package/package.json +38 -46
  57. package/dist/ecosystem-BIWaVwYL.cjs +0 -294
  58. package/dist/ecosystem-EFtHnKS9.mjs +0 -256
  59. package/dist/index.cjs +0 -788
  60. package/dist/index.d.cts +0 -14
  61. package/dist/presets.cjs +0 -18
  62. package/dist/presets.d.cts +0 -2
  63. package/dist/setup.cjs +0 -2702
  64. package/dist/setup.d.cts +0 -1
@@ -0,0 +1,506 @@
1
+ import { n as VitestNativeTypeError } from "./errors-CxoBUfVJ.mjs";
2
+ import { t as AUTO_DETECT_PRESETS } from "./preset-map-DuX0ocdn.mjs";
3
+ import { createRequire } from "node:module";
4
+ import fs from "node:fs";
5
+ import path from "node:path";
6
+ //#region src/validate.ts
7
+ const KNOWN_OPTIONS = [
8
+ "platform",
9
+ "presets",
10
+ "mocks",
11
+ "diagnostics",
12
+ "assetExts",
13
+ "engine",
14
+ "transform",
15
+ "hotRuntime"
16
+ ];
17
+ const KNOWN_HOT_RUNTIME_OPTIONS = [
18
+ "recycleAfterFiles",
19
+ "memoryLimit",
20
+ "preserveGlobals"
21
+ ];
22
+ function assertStringArray(value, option) {
23
+ if (!Array.isArray(value) || value.some((entry) => typeof entry !== "string" || entry.length === 0)) throw new VitestNativeTypeError("INVALID_OPTION", `"${option}" must be an array of non-empty strings.`);
24
+ }
25
+ function assertNonNegativeInteger(value, option) {
26
+ if (typeof value !== "number" || !Number.isSafeInteger(value) || value < 0) throw new VitestNativeTypeError("INVALID_OPTION", `"${option}" must be a non-negative safe integer.`);
27
+ }
28
+ function validateOptions(options) {
29
+ if (options.engine !== void 0 && options.engine !== "auto" && options.engine !== "mock" && options.engine !== "native") throw new VitestNativeTypeError("INVALID_OPTION", `"engine" must be "auto", "mock", or "native".`);
30
+ if (options.platform !== void 0 && options.platform !== "ios" && options.platform !== "android") throw new VitestNativeTypeError("INVALID_OPTION", `"platform" must be "ios" or "android".`);
31
+ if (options.diagnostics !== void 0 && typeof options.diagnostics !== "boolean") throw new VitestNativeTypeError("INVALID_OPTION", `"diagnostics" must be a boolean.`);
32
+ if (options.assetExts !== void 0) assertStringArray(options.assetExts, "assetExts");
33
+ if (options.transform !== void 0) assertStringArray(options.transform, "transform");
34
+ if (options.presets !== void 0 && !Array.isArray(options.presets)) {
35
+ if (!(options.presets !== null && typeof options.presets === "object" && Object.values(options.presets).every((v) => typeof v === "boolean"))) throw new VitestNativeTypeError("INVALID_OPTION", "\"presets\" must be an array of presets, or an object of booleans to switch auto-detected presets off (for example { navigation: false }).");
36
+ }
37
+ if (options.mocks !== void 0 && (options.mocks === null || Array.isArray(options.mocks) || typeof options.mocks !== "object")) throw new VitestNativeTypeError("INVALID_OPTION", `"mocks" must be a plain object.`);
38
+ const hotRuntime = options.hotRuntime;
39
+ if (hotRuntime === void 0 || typeof hotRuntime === "boolean") return;
40
+ if (hotRuntime === null || Array.isArray(hotRuntime) || typeof hotRuntime !== "object") throw new VitestNativeTypeError("INVALID_OPTION", `"hotRuntime" must be a boolean or an options object.`);
41
+ const hotOptions = hotRuntime;
42
+ for (const key of Object.keys(hotOptions)) if (!KNOWN_HOT_RUNTIME_OPTIONS.includes(key)) {
43
+ const suggestion = findClosest(key, KNOWN_HOT_RUNTIME_OPTIONS);
44
+ throw new VitestNativeTypeError("UNKNOWN_OPTION", `Unknown hotRuntime option "${key}".` + (suggestion ? ` Did you mean '${suggestion}'?` : "") + ` Valid options: ${KNOWN_HOT_RUNTIME_OPTIONS.join(", ")}.`);
45
+ }
46
+ if (hotOptions.recycleAfterFiles !== void 0) assertNonNegativeInteger(hotOptions.recycleAfterFiles, "hotRuntime.recycleAfterFiles");
47
+ if (hotOptions.memoryLimit !== void 0) assertNonNegativeInteger(hotOptions.memoryLimit, "hotRuntime.memoryLimit");
48
+ if (hotOptions.preserveGlobals !== void 0) assertStringArray(hotOptions.preserveGlobals, "hotRuntime.preserveGlobals");
49
+ }
50
+ function satisfiesMinimum(version, minimum) {
51
+ const parse = (v) => v.replace(/^[^0-9]*/, "").split(/[-+]/)[0].split(".").map(Number);
52
+ const [aMaj, aMin = 0, aPat = 0] = parse(version);
53
+ const [bMaj, bMin = 0, bPat = 0] = parse(minimum);
54
+ if (aMaj !== bMaj) return aMaj > bMaj;
55
+ if (aMin !== bMin) return aMin > bMin;
56
+ return aPat >= bPat;
57
+ }
58
+ function validatePeerDependency(pkgName, minimumVersion, projectRoot, maximumMajorExclusive, minimumByMajor) {
59
+ const req = createRequire(path.join(projectRoot, "package.json"));
60
+ try {
61
+ const { version } = req(req.resolve(`${pkgName}/package.json`));
62
+ const major = Number(version.replace(/^[^0-9]*/, "").split(".")[0]);
63
+ const requiredMinimum = minimumByMajor?.[major] ?? minimumVersion;
64
+ if (!satisfiesMinimum(version, requiredMinimum)) return `vitest-native requires ${pkgName} >= ${requiredMinimum} for ${major}.x, but found ${version}. Please upgrade.`;
65
+ if (maximumMajorExclusive !== void 0 && major >= maximumMajorExclusive) return `vitest-native supports ${pkgName} >= ${minimumVersion} and < ${maximumMajorExclusive}, but found ${version}.`;
66
+ return null;
67
+ } catch {
68
+ return `vitest-native requires ${pkgName} >= ${minimumVersion}, but it was not found. Please install it.`;
69
+ }
70
+ }
71
+ function warnUnknownOptions(options) {
72
+ for (const key of Object.keys(options)) if (!KNOWN_OPTIONS.includes(key)) {
73
+ const suggestion = findClosest(key, KNOWN_OPTIONS);
74
+ const hint = suggestion ? ` Did you mean '${suggestion}'?` : "";
75
+ console.warn(`[vitest-native] Unknown option '${key}'.${hint}`);
76
+ }
77
+ }
78
+ function findClosest(input, candidates) {
79
+ let best = null;
80
+ let bestDist = Infinity;
81
+ for (const c of candidates) {
82
+ const d = levenshtein(input.toLowerCase(), c.toLowerCase());
83
+ if (d < bestDist && d <= 3) {
84
+ bestDist = d;
85
+ best = c;
86
+ }
87
+ }
88
+ return best;
89
+ }
90
+ function levenshtein(a, b) {
91
+ const m = a.length;
92
+ const n = b.length;
93
+ const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
94
+ for (let i = 0; i <= m; i++) dp[i][0] = i;
95
+ for (let j = 0; j <= n; j++) dp[0][j] = j;
96
+ for (let i = 1; i <= m; i++) for (let j = 1; j <= n; j++) dp[i][j] = a[i - 1] === b[j - 1] ? dp[i - 1][j - 1] : 1 + Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]);
97
+ return dp[m][n];
98
+ }
99
+ //#endregion
100
+ //#region src/peer-requirements.ts
101
+ const PEER_REQUIREMENTS = [
102
+ {
103
+ name: "vitest",
104
+ minimum: "4.0.0",
105
+ maximumMajor: 6
106
+ },
107
+ {
108
+ name: "vite",
109
+ minimum: "6.4.2",
110
+ maximumMajor: 9,
111
+ minimumByMajor: {
112
+ 6: "6.4.2",
113
+ 7: "7.3.2",
114
+ 8: "8.0.5"
115
+ }
116
+ },
117
+ {
118
+ name: "react",
119
+ minimum: "18.0.0"
120
+ },
121
+ {
122
+ name: "@testing-library/react-native",
123
+ minimum: "12.0.0",
124
+ maximumMajor: 15,
125
+ optional: true
126
+ }
127
+ ];
128
+ //#endregion
129
+ //#region src/native/match.mjs
130
+ /**
131
+ * Which files belong to which package — the one place that decides it.
132
+ *
133
+ * The native engine splits the module graph between Vite and Node (the rule itself is
134
+ * written down in the header of apply.ts). Four places used to answer "does this file
135
+ * belong to a Node-owned package?" independently: the externalization patterns handed
136
+ * to Vitest, auto-detection, and the transform matchers in the require hook and the
137
+ * ESM loader. They agreed by construction rather than by structure, and three of the
138
+ * defects in this area were one of them disagreeing with the others — a directory
139
+ * anchor the transform side applied and the config side did not, a `node_modules`
140
+ * rule that also matched any folder sharing a package's name, and a separator
141
+ * mismatch that only appeared on Windows.
142
+ *
143
+ * Vitest's `server.deps.external` takes patterns rather than a predicate, so config
144
+ * time and run time cannot literally call the same function. They can be generated
145
+ * from the same rules, which is what `packagePatterns` is for: `buildPkgMatcher`
146
+ * tests exactly the patterns that were handed to Vitest.
147
+ *
148
+ * Everything here is pure. apply.ts bundles a copy into the plugin entry while the
149
+ * worker loads this file directly, so it must stay that way — module-level state
150
+ * would exist twice.
151
+ */
152
+ /**
153
+ * React Native's own source, including the `@react-native/*` packages. Node owns
154
+ * these unconditionally: the Flow strip, the boundary mocks and the precompiled
155
+ * registry are all Node loader hooks.
156
+ */
157
+ const REACT_NATIVE_PATH = /[\\/]node_modules[\\/](react-native|@react-native)[\\/]/;
158
+ /** Escape a string for literal use inside a RegExp. */
159
+ function escapeRe(value) {
160
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
161
+ }
162
+ /** Forward slashes, the form Vitest presents module ids in. */
163
+ function toPosix(value) {
164
+ return value.replace(/\\/g, "/");
165
+ }
166
+ /**
167
+ * Does `dir` contain `target` (or equal it)?
168
+ *
169
+ * Used to recognise the package the run lives in. A package directory containing the
170
+ * Vitest root is the project, not a dependency of it — externalizing it hands Vitest
171
+ * its own source and test files back through Node, where they are compiled to
172
+ * CommonJS.
173
+ *
174
+ * Compared case-insensitively on Windows: `require.resolve` reports the on-disk
175
+ * casing while a working directory carries whatever the shell supplied, and a
176
+ * drive-letter difference alone would silently defeat the check.
177
+ */
178
+ function containsPath(dir, target) {
179
+ const normalize = (value) => {
180
+ const resolved = path.resolve(value);
181
+ return process.platform === "win32" ? resolved.toLowerCase() : resolved;
182
+ };
183
+ const outer = normalize(dir);
184
+ const inner = normalize(target);
185
+ return inner === outer || inner.startsWith(outer.endsWith(path.sep) ? outer : outer + path.sep);
186
+ }
187
+ /**
188
+ * The on-disk directory a package resolves to, or null.
189
+ *
190
+ * `pkg/package.json` is tried first because it names the package root exactly; some
191
+ * packages do not export it, so fall back to resolving the entry and walking up to
192
+ * the manifest that names them. Symlinked and workspace packages resolve to their
193
+ * real location, which is the whole point — see buildPkgMatcher.
194
+ */
195
+ function packageDirOf(name, projectRoot) {
196
+ const req = createRequire(path.join(projectRoot, "package.json"));
197
+ try {
198
+ return path.dirname(req.resolve(`${name}/package.json`));
199
+ } catch {}
200
+ let dir;
201
+ try {
202
+ dir = path.dirname(req.resolve(name));
203
+ } catch {
204
+ return null;
205
+ }
206
+ for (;;) {
207
+ try {
208
+ if (createRequire(path.join(dir, "index.js"))("./package.json").name === name) return dir;
209
+ } catch {}
210
+ const parent = path.dirname(dir);
211
+ if (parent === dir) return null;
212
+ dir = parent;
213
+ }
214
+ }
215
+ /**
216
+ * The patterns identifying one package's files. THE rule; everything else composes it.
217
+ *
218
+ * A bare `[/\]name[/\]` test — what this used to be — also matches any DIRECTORY
219
+ * that happens to share a package's name. A project folder called `expo`, or a source
220
+ * directory named after the library it implements, made every file beneath it look
221
+ * like third-party source to be compiled. That mis-compiled unrelated files, this
222
+ * package's own runtime among them.
223
+ *
224
+ * Anchoring on `node_modules` alone would fix that and break linked packages: a
225
+ * workspace or `file:` dependency resolves to its real path, which has no
226
+ * `node_modules` segment at all. So a file matches if it is either
227
+ *
228
+ * - under `node_modules/<name>/` (covers additional copies of a package that a
229
+ * single resolution cannot see, and projects where resolution fails), or
230
+ * - inside the package's resolved directory (exact; covers workspace links, and
231
+ * stores like pnpm's and bun's).
232
+ *
233
+ * The resolved-directory anchor is dropped when that directory CONTAINS the project
234
+ * root, because then it is the project. Externalizing the project hands Vitest its
235
+ * own source and test files back through Node, which compiles them to CommonJS: a
236
+ * test file's `import { it } from 'vitest'` becomes `require('vitest')` and throws.
237
+ *
238
+ * `projectRoot` is optional; without it only the `node_modules` rule applies, since
239
+ * there is nothing to resolve against.
240
+ */
241
+ function packagePatterns(name, projectRoot) {
242
+ const patterns = [new RegExp(`[\\\\/]node_modules[\\\\/]${escapeRe(name)}[\\\\/]`)];
243
+ if (!projectRoot) return patterns;
244
+ const dir = packageDirOf(name, projectRoot);
245
+ if (dir && !containsPath(dir, projectRoot)) patterns.push(new RegExp(`^${escapeRe(toPosix(dir).replace(/\/$/, ""))}[\\\\/]`));
246
+ return patterns;
247
+ }
248
+ /** Can this project run the native engine? (Both transform deps resolvable.) */
249
+ function isNativeCapable(projectRoot) {
250
+ try {
251
+ const req = createRequire(path.join(projectRoot, "package.json"));
252
+ req.resolve("@react-native/babel-preset");
253
+ req.resolve("@babel/core");
254
+ return true;
255
+ } catch {
256
+ return false;
257
+ }
258
+ }
259
+ /** Resolve the concrete engine for a run. Pure; never throws. */
260
+ function detectEngine(requested, projectRoot, opts) {
261
+ const nativeAvailable = isNativeCapable(projectRoot);
262
+ if (requested === "native") return {
263
+ engine: "native",
264
+ nativeAvailable,
265
+ notice: null
266
+ };
267
+ if (requested === "mock") return {
268
+ engine: "mock",
269
+ nativeAvailable,
270
+ notice: null
271
+ };
272
+ const prefersNative = opts?.autoPrefersNative ?? true;
273
+ if (prefersNative && nativeAvailable) return {
274
+ engine: "native",
275
+ nativeAvailable,
276
+ notice: null
277
+ };
278
+ if (prefersNative) return {
279
+ engine: "mock",
280
+ nativeAvailable: false,
281
+ notice: "[vitest-native] @react-native/babel-preset not found — using the mock engine. Install it (and @babel/core) to run real React Native, or set engine:'mock' to silence this."
282
+ };
283
+ return {
284
+ engine: "mock",
285
+ nativeAvailable,
286
+ notice: null
287
+ };
288
+ }
289
+ //#endregion
290
+ //#region src/native/ecosystem.ts
291
+ /**
292
+ * Packages that must never be auto-inlined even though they depend on React
293
+ * Native. The test library and the renderers underneath it are infrastructure the
294
+ * engine itself wires up; pulling a second copy of them into the module graph has
295
+ * corrupted rendering before, in ways that surface as unrelated act() and
296
+ * host-component failures.
297
+ *
298
+ * This list is one clause of the ownership rule; the whole of it is written down in
299
+ * the header of native/apply.ts, which is the file to read before changing what ends
300
+ * up in either graph.
301
+ */
302
+ const NEVER_INLINE = /* @__PURE__ */ new Set([
303
+ "@testing-library/react-native",
304
+ "react-test-renderer",
305
+ "test-renderer",
306
+ "react-native",
307
+ "react",
308
+ "react-is"
309
+ ]);
310
+ /** Manifest fields that make a package part of the React Native ecosystem. */
311
+ function dependsOnReactNative(manifest) {
312
+ for (const field of ["dependencies", "peerDependencies"]) {
313
+ const deps = manifest[field];
314
+ if (deps && typeof deps === "object" && "react-native" in deps) return true;
315
+ }
316
+ return false;
317
+ }
318
+ /**
319
+ * Every package manifest from the project up to the filesystem root.
320
+ *
321
+ * A workspace does not always declare its dependencies where the tests run: an app
322
+ * package may inherit React Native libraries from the repository root, and a Vitest
323
+ * `root` can point at a directory above or below the package that owns them. Reading
324
+ * only the project's own manifest silently found nothing in those layouts and sent
325
+ * the user back to maintaining `transform: [...]` by hand.
326
+ *
327
+ * Over-collecting is safe and under-collecting is not: a package that is listed but
328
+ * never imported costs nothing, because inlining only applies to files that are
329
+ * actually loaded.
330
+ */
331
+ /**
332
+ * Directories of the workspace members a manifest declares, plus any listed in a
333
+ * sibling pnpm-workspace.yaml.
334
+ *
335
+ * Needed because `manifestsFrom` only walks UP. In a workspace the run root is
336
+ * frequently ABOVE the package under test — Nx invokes tasks from the workspace
337
+ * root, and Vitest's root defaults to the working directory — so the app's own
338
+ * dependencies are declared in a manifest that walking up never reaches. The
339
+ * package then misses auto-detection and stays in Vite's graph while Node loads it
340
+ * too, which is the dual-ownership failure reproducing from nothing but a different
341
+ * working directory.
342
+ *
343
+ * Only the two glob shapes workspace fields actually use are expanded (`dir/*` and a
344
+ * literal path). Over-collecting is safe here — an unimported package costs nothing —
345
+ * so a shape that is not understood is skipped rather than approximated.
346
+ */
347
+ function workspaceMemberDirs(dir, manifest) {
348
+ const patterns = [];
349
+ const declared = manifest.workspaces;
350
+ if (Array.isArray(declared)) patterns.push(...declared.filter((p) => typeof p === "string"));
351
+ else if (declared && typeof declared === "object" && Array.isArray(declared.packages)) patterns.push(...declared.packages.filter((p) => typeof p === "string"));
352
+ try {
353
+ const yaml = fs.readFileSync(path.join(dir, "pnpm-workspace.yaml"), "utf8");
354
+ for (const line of yaml.split(/\r?\n/)) {
355
+ const entry = /^\s*-\s*["']?([^"'#]+?)["']?\s*$/.exec(line);
356
+ if (entry) patterns.push(entry[1]);
357
+ }
358
+ } catch {}
359
+ const dirs = [];
360
+ for (const pattern of patterns) if (pattern.endsWith("/*")) {
361
+ const parent = path.join(dir, pattern.slice(0, -2));
362
+ try {
363
+ for (const entry of fs.readdirSync(parent, { withFileTypes: true })) if (entry.isDirectory()) dirs.push(path.join(parent, entry.name));
364
+ } catch {}
365
+ } else if (!pattern.includes("*")) dirs.push(path.join(dir, pattern));
366
+ return dirs;
367
+ }
368
+ function manifestsFrom(projectRoot) {
369
+ const manifests = [];
370
+ let dir = path.resolve(projectRoot);
371
+ for (;;) {
372
+ try {
373
+ const raw = fs.readFileSync(path.join(dir, "package.json"), "utf8");
374
+ const manifest = JSON.parse(raw);
375
+ manifests.push({
376
+ dir,
377
+ manifest
378
+ });
379
+ for (const member of workspaceMemberDirs(dir, manifest)) try {
380
+ manifests.push({
381
+ dir: member,
382
+ manifest: JSON.parse(fs.readFileSync(path.join(member, "package.json"), "utf8"))
383
+ });
384
+ } catch {}
385
+ } catch {}
386
+ const parent = path.dirname(dir);
387
+ if (parent === dir) return manifests;
388
+ dir = parent;
389
+ }
390
+ }
391
+ /**
392
+ * Packages in the project that declare React Native in their own manifest.
393
+ *
394
+ * These are the ones published the way the React Native ecosystem publishes:
395
+ * untranspiled JSX, Flow, or TypeScript, on the assumption that Metro will compile
396
+ * them. Node cannot run that source, which is why they previously had to be listed
397
+ * by hand in `transform: [...]` — a list every project had to discover the hard way,
398
+ * one `SyntaxError: Unexpected token '<'` at a time.
399
+ *
400
+ * A package's own manifest is the authority here rather than a heuristic on its
401
+ * name: `react-native-*` misses `@gorhom/bottom-sheet` and would wrongly claim
402
+ * `react-native` itself, while the manifest states the relationship exactly.
403
+ *
404
+ * Declared dependencies are read from the project and every manifest above it, so a
405
+ * workspace that declares its React Native libraries at the repository root is covered
406
+ * too. Resolving each name is cheap and package-manager-agnostic, where walking the
407
+ * installed tree depends on the store layout. Transitive dependencies that nothing
408
+ * declares stay available through `transform: [...]`.
409
+ *
410
+ * Excluded: packages a preset already shadows (their real source never loads), the
411
+ * test infrastructure in NEVER_INLINE, and anything the consumer listed explicitly
412
+ * in `transform` — that option keeps its existing meaning and takes precedence.
413
+ */
414
+ function detectEcosystemPackages(projectRoot, explicit = [], testRoots = []) {
415
+ const roots = (Array.isArray(projectRoot) ? projectRoot : [projectRoot]).filter(Boolean);
416
+ const skip = /* @__PURE__ */ new Set([
417
+ ...NEVER_INLINE,
418
+ ...Object.keys(AUTO_DETECT_PRESETS),
419
+ ...explicit
420
+ ]);
421
+ const candidates = /* @__PURE__ */ new Set();
422
+ const found = roots.flatMap((root) => manifestsFrom(root));
423
+ const requires = [...new Set(found.map((entry) => entry.dir))].map((dir) => createRequire(path.join(dir, "package.json")));
424
+ for (const { manifest } of found) for (const field of [
425
+ "dependencies",
426
+ "devDependencies",
427
+ "optionalDependencies"
428
+ ]) {
429
+ const deps = manifest[field];
430
+ if (deps && typeof deps === "object") for (const name of Object.keys(deps)) candidates.add(name);
431
+ }
432
+ if (candidates.size === 0) return [];
433
+ /** Resolve a package's manifest from whichever root can see it. */
434
+ const manifestOf = (name) => {
435
+ for (const req of requires) try {
436
+ return req(`${name}/package.json`);
437
+ } catch {}
438
+ return null;
439
+ };
440
+ /**
441
+ * The packages the run itself lives in — the project, in other words.
442
+ *
443
+ * In a workspace, the package under test is usually declared as a dependency by a
444
+ * sibling or by the repository root, so it appears in the candidate set like any
445
+ * third-party library — and it declares React Native, because it is React Native
446
+ * code. Detecting it would claim the project's own source: its directory becomes a
447
+ * `server.deps.external` pattern, so Vitest hands every file under it to Node,
448
+ * where the loader compiles it to CommonJS. A test file's own
449
+ * `import { it } from 'vitest'` becomes `require('vitest')`, which throws
450
+ * "Vitest cannot be imported in a CommonJS module using require()" — a failure that
451
+ * appears in one workspace package and not another for no visible reason.
452
+ *
453
+ * A package cannot be its own dependency, so a manifest whose directory contains a
454
+ * run root belongs to the project. Read straight off the manifests already walked,
455
+ * which is both cheaper than resolving each candidate and independent of how a
456
+ * package manager happens to lay out its store — under pnpm every workspace member
457
+ * is additionally linked into a hidden directory on NODE_PATH, so a package can
458
+ * resolve its own name from its own directory, but nothing here depends on that.
459
+ *
460
+ * Workspace libraries the project merely depends on sit beside a run root rather
461
+ * than above it and are unaffected — detecting those is the point of the
462
+ * workspace-member walk above.
463
+ */
464
+ const ownerRoots = [...roots, ...testRoots];
465
+ const runOwners = new Set(found.filter(({ dir }) => ownerRoots.some((root) => containsPath(dir, root))).map(({ manifest }) => manifest.name).filter((name) => typeof name === "string"));
466
+ const ownsTheRun = (name) => runOwners.has(name);
467
+ const detected = [];
468
+ for (const name of candidates) {
469
+ if (skip.has(name) || name.startsWith("@react-native/")) continue;
470
+ const pkg = manifestOf(name);
471
+ if (pkg && dependsOnReactNative(pkg) && !ownsTheRun(name)) detected.push(name);
472
+ }
473
+ const rnOwned = new Set(Object.keys(manifestOf("react-native")?.dependencies ?? {}));
474
+ /** Every package reachable from `roots` through runtime dependencies. */
475
+ const closureOf = (starts) => {
476
+ const seen = /* @__PURE__ */ new Set();
477
+ const pending = [...starts];
478
+ while (pending.length > 0) {
479
+ const name = pending.pop();
480
+ if (seen.has(name)) continue;
481
+ seen.add(name);
482
+ const deps = manifestOf(name)?.dependencies;
483
+ if (deps && typeof deps === "object") pending.push(...Object.keys(deps));
484
+ }
485
+ return seen;
486
+ };
487
+ const toolchain = closureOf(["@babel/core", "@react-native/babel-preset"]);
488
+ const inClosure = new Set(detected);
489
+ const queue = [...detected];
490
+ while (queue.length > 0) {
491
+ const deps = manifestOf(queue.pop())?.dependencies;
492
+ if (!deps || typeof deps !== "object") continue;
493
+ for (const dep of Object.keys(deps)) {
494
+ if (inClosure.has(dep) || skip.has(dep) || dep.startsWith("@react-native/")) continue;
495
+ if (rnOwned.has(dep)) continue;
496
+ if (toolchain.has(dep)) continue;
497
+ if (ownsTheRun(dep)) continue;
498
+ if (!manifestOf(dep)) continue;
499
+ inClosure.add(dep);
500
+ queue.push(dep);
501
+ }
502
+ }
503
+ return [...inClosure].sort();
504
+ }
505
+ //#endregion
506
+ export { packageDirOf as a, validateOptions as c, containsPath as i, validatePeerDependency as l, detectEngine as n, packagePatterns as o, REACT_NATIVE_PATH as r, PEER_REQUIREMENTS as s, detectEcosystemPackages as t, warnUnknownOptions as u };
@@ -0,0 +1,75 @@
1
+ //#region src/errors.mjs
2
+ /**
3
+ * The error types this package throws.
4
+ *
5
+ * Plain .mjs on purpose. The shipped native and jest-compat runtimes are copied to dist
6
+ * verbatim and import this by relative path, and the test suite loads those same files
7
+ * from src — so the module has to resolve identically in both trees. A .ts source would
8
+ * only exist in one of them.
9
+ *
10
+ * WHAT SURVIVES WHERE, measured rather than assumed:
11
+ *
12
+ * - In the main process, and in a user's own try/catch inside a test, everything is
13
+ * intact.
14
+ * - Across the worker/reporter boundary Vitest keeps only `name`, `message` and
15
+ * `stack`. `code` and every other own property is dropped.
16
+ *
17
+ * So the message must stay self-sufficient: nothing may move out of it into a field on
18
+ * the assumption a reader will see it.
19
+ *
20
+ * `isVitestNativeError` deliberately checks SHAPE rather than `instanceof`. Bundled
21
+ * entries and the verbatim .mjs runtimes can hold separate copies of this module, and a
22
+ * prototype check would quietly fail across that seam. Shape does not care.
23
+ */
24
+ const PREFIX = "[vitest-native]";
25
+ /** Guarantees the prefix exactly once, however the caller wrote the message. */
26
+ function withPrefix(message) {
27
+ return message.startsWith(PREFIX) ? message : `${PREFIX} ${message}`;
28
+ }
29
+ function buildMessage(message, options) {
30
+ const base = withPrefix(message);
31
+ return options?.docs ? `${base}\nSee ${options.docs}` : base;
32
+ }
33
+ /**
34
+ * Error options, omitted entirely when there is no cause.
35
+ *
36
+ * `new Error(msg, { cause: undefined })` installs an own `cause` property set to
37
+ * undefined, which a plain `new Error(msg)` does not — enough to make some reporters
38
+ * print an empty cause and to make these errors shaped differently from every other
39
+ * error in the process. Passing nothing keeps them identical.
40
+ */
41
+ function errorOptions(options) {
42
+ return options && "cause" in options && options.cause !== void 0 ? { cause: options.cause } : void 0;
43
+ }
44
+ /** A failure originating in vitest-native. */
45
+ var VitestNativeError = class extends Error {
46
+ constructor(code, message, options) {
47
+ super(buildMessage(message, options), errorOptions(options));
48
+ this.name = "VitestNativeError";
49
+ this.code = code;
50
+ }
51
+ };
52
+ /**
53
+ * A vitest-native failure that is also a type error — a badly typed option, say.
54
+ * Extends TypeError so `instanceof TypeError` keeps working for consumers.
55
+ */
56
+ var VitestNativeTypeError = class extends TypeError {
57
+ constructor(code, message, options) {
58
+ super(buildMessage(message, options), errorOptions(options));
59
+ this.name = "VitestNativeTypeError";
60
+ this.code = code;
61
+ }
62
+ };
63
+ //#endregion
64
+ Object.defineProperty(exports, "VitestNativeError", {
65
+ enumerable: true,
66
+ get: function() {
67
+ return VitestNativeError;
68
+ }
69
+ });
70
+ Object.defineProperty(exports, "VitestNativeTypeError", {
71
+ enumerable: true,
72
+ get: function() {
73
+ return VitestNativeTypeError;
74
+ }
75
+ });
@@ -0,0 +1,64 @@
1
+ //#region src/errors.mjs
2
+ /**
3
+ * The error types this package throws.
4
+ *
5
+ * Plain .mjs on purpose. The shipped native and jest-compat runtimes are copied to dist
6
+ * verbatim and import this by relative path, and the test suite loads those same files
7
+ * from src — so the module has to resolve identically in both trees. A .ts source would
8
+ * only exist in one of them.
9
+ *
10
+ * WHAT SURVIVES WHERE, measured rather than assumed:
11
+ *
12
+ * - In the main process, and in a user's own try/catch inside a test, everything is
13
+ * intact.
14
+ * - Across the worker/reporter boundary Vitest keeps only `name`, `message` and
15
+ * `stack`. `code` and every other own property is dropped.
16
+ *
17
+ * So the message must stay self-sufficient: nothing may move out of it into a field on
18
+ * the assumption a reader will see it.
19
+ *
20
+ * `isVitestNativeError` deliberately checks SHAPE rather than `instanceof`. Bundled
21
+ * entries and the verbatim .mjs runtimes can hold separate copies of this module, and a
22
+ * prototype check would quietly fail across that seam. Shape does not care.
23
+ */
24
+ const PREFIX = "[vitest-native]";
25
+ /** Guarantees the prefix exactly once, however the caller wrote the message. */
26
+ function withPrefix(message) {
27
+ return message.startsWith(PREFIX) ? message : `${PREFIX} ${message}`;
28
+ }
29
+ function buildMessage(message, options) {
30
+ const base = withPrefix(message);
31
+ return options?.docs ? `${base}\nSee ${options.docs}` : base;
32
+ }
33
+ /**
34
+ * Error options, omitted entirely when there is no cause.
35
+ *
36
+ * `new Error(msg, { cause: undefined })` installs an own `cause` property set to
37
+ * undefined, which a plain `new Error(msg)` does not — enough to make some reporters
38
+ * print an empty cause and to make these errors shaped differently from every other
39
+ * error in the process. Passing nothing keeps them identical.
40
+ */
41
+ function errorOptions(options) {
42
+ return options && "cause" in options && options.cause !== void 0 ? { cause: options.cause } : void 0;
43
+ }
44
+ /** A failure originating in vitest-native. */
45
+ var VitestNativeError = class extends Error {
46
+ constructor(code, message, options) {
47
+ super(buildMessage(message, options), errorOptions(options));
48
+ this.name = "VitestNativeError";
49
+ this.code = code;
50
+ }
51
+ };
52
+ /**
53
+ * A vitest-native failure that is also a type error — a badly typed option, say.
54
+ * Extends TypeError so `instanceof TypeError` keeps working for consumers.
55
+ */
56
+ var VitestNativeTypeError = class extends TypeError {
57
+ constructor(code, message, options) {
58
+ super(buildMessage(message, options), errorOptions(options));
59
+ this.name = "VitestNativeTypeError";
60
+ this.code = code;
61
+ }
62
+ };
63
+ //#endregion
64
+ export { VitestNativeTypeError as n, VitestNativeError as t };