vitest-native 0.10.0 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/CHANGELOG.md +257 -0
  2. package/README.md +1 -0
  3. package/dist/cli.cjs +25 -7
  4. package/dist/cli.mjs +22 -4
  5. package/dist/{ecosystem-IuZ-Gv0R.cjs → ecosystem-DGlajfDG.cjs} +280 -14
  6. package/dist/{ecosystem-CO5vqExO.mjs → ecosystem-DJMGR2YY.mjs} +254 -12
  7. package/dist/helpers.cjs +1 -1
  8. package/dist/helpers.mjs +1 -1
  9. package/dist/{index-BJL4cQ-l.d.cts → index-CrMeE8rd.d.mts} +5 -5
  10. package/dist/{index-CvCU0cLl.d.mts → index-DIMbjH8R.d.cts} +6 -3
  11. package/dist/index.d.mts +1 -2
  12. package/dist/index.mjs +78 -48
  13. package/dist/jest-compat.cjs +4 -4
  14. package/dist/jest-compat.d.cts +0 -1
  15. package/dist/jest-compat.d.mts +0 -1
  16. package/dist/jest-compat.mjs +2 -2
  17. package/dist/native/hooks.mjs +77 -12
  18. package/dist/native/loader.mjs +10 -5
  19. package/dist/native/match.d.mts +33 -0
  20. package/dist/native/match.mjs +94 -22
  21. package/dist/native/registry.mjs +30 -2
  22. package/dist/{pool-CFND7plG.cjs → pool-BU-1ecIF.cjs} +6 -6
  23. package/dist/{pool-Bcxp4Qrg.mjs → pool-Bcxn9a3I.mjs} +3 -3
  24. package/dist/{preset-map-DxilQ4pI.cjs → preset-map-BoG19dLa.cjs} +1 -0
  25. package/dist/{preset-map-BpDG_D5m.mjs → preset-map-DuX0ocdn.mjs} +1 -0
  26. package/dist/{presets-BGTqVH6C.cjs → presets-CwO_c4aL.cjs} +131 -6
  27. package/dist/{presets-CK85x8ey.mjs → presets-IStcJEOa.mjs} +123 -4
  28. package/dist/presets.d.mts +2 -2
  29. package/dist/presets.mjs +2 -2
  30. package/dist/{chunk-CjcI7cDX.mjs → rolldown-runtime-BhDjJH2R.mjs} +1 -1
  31. package/dist/{chunk-CZWwpsFl.cjs → rolldown-runtime-C0BPl7ul.cjs} +1 -1
  32. package/dist/serializer.cjs +1 -1
  33. package/dist/serializer.mjs +1 -1
  34. package/dist/setup.d.mts +1 -1
  35. package/dist/setup.mjs +5 -5
  36. package/docs/versioning.md +1 -1
  37. package/package.json +17 -15
  38. /package/dist/{errors-flXDIeWk.cjs → errors-B3lJK46O.cjs} +0 -0
  39. /package/dist/{errors-Dm5yLNTF.mjs → errors-CxoBUfVJ.mjs} +0 -0
@@ -1,10 +1,10 @@
1
- const require_chunk = require("./chunk-CZWwpsFl.cjs");
2
- const require_errors = require("./errors-flXDIeWk.cjs");
3
- const require_preset_map = require("./preset-map-DxilQ4pI.cjs");
1
+ const require_rolldown_runtime = require("./rolldown-runtime-C0BPl7ul.cjs");
2
+ const require_errors = require("./errors-B3lJK46O.cjs");
3
+ const require_preset_map = require("./preset-map-BoG19dLa.cjs");
4
4
  let node_fs = require("node:fs");
5
- node_fs = require_chunk.__toESM(node_fs, 1);
5
+ node_fs = require_rolldown_runtime.__toESM(node_fs, 1);
6
6
  let node_path = require("node:path");
7
- node_path = require_chunk.__toESM(node_path, 1);
7
+ node_path = require_rolldown_runtime.__toESM(node_path, 1);
8
8
  let node_module = require("node:module");
9
9
  //#region src/validate.ts
10
10
  const KNOWN_OPTIONS = [
@@ -128,6 +128,126 @@ const PEER_REQUIREMENTS = [
128
128
  optional: true
129
129
  }
130
130
  ];
131
+ //#endregion
132
+ //#region src/native/match.mjs
133
+ /**
134
+ * Which files belong to which package — the one place that decides it.
135
+ *
136
+ * The native engine splits the module graph between Vite and Node (the rule itself is
137
+ * written down in the header of apply.ts). Four places used to answer "does this file
138
+ * belong to a Node-owned package?" independently: the externalization patterns handed
139
+ * to Vitest, auto-detection, and the transform matchers in the require hook and the
140
+ * ESM loader. They agreed by construction rather than by structure, and three of the
141
+ * defects in this area were one of them disagreeing with the others — a directory
142
+ * anchor the transform side applied and the config side did not, a `node_modules`
143
+ * rule that also matched any folder sharing a package's name, and a separator
144
+ * mismatch that only appeared on Windows.
145
+ *
146
+ * Vitest's `server.deps.external` takes patterns rather than a predicate, so config
147
+ * time and run time cannot literally call the same function. They can be generated
148
+ * from the same rules, which is what `packagePatterns` is for: `buildPkgMatcher`
149
+ * tests exactly the patterns that were handed to Vitest.
150
+ *
151
+ * Everything here is pure. apply.ts bundles a copy into the plugin entry while the
152
+ * worker loads this file directly, so it must stay that way — module-level state
153
+ * would exist twice.
154
+ */
155
+ /**
156
+ * React Native's own source, including the `@react-native/*` packages. Node owns
157
+ * these unconditionally: the Flow strip, the boundary mocks and the precompiled
158
+ * registry are all Node loader hooks.
159
+ */
160
+ const REACT_NATIVE_PATH = /[\\/]node_modules[\\/](react-native|@react-native)[\\/]/;
161
+ /** Escape a string for literal use inside a RegExp. */
162
+ function escapeRe(value) {
163
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
164
+ }
165
+ /** Forward slashes, the form Vitest presents module ids in. */
166
+ function toPosix(value) {
167
+ return value.replace(/\\/g, "/");
168
+ }
169
+ /**
170
+ * Does `dir` contain `target` (or equal it)?
171
+ *
172
+ * Used to recognise the package the run lives in. A package directory containing the
173
+ * Vitest root is the project, not a dependency of it — externalizing it hands Vitest
174
+ * its own source and test files back through Node, where they are compiled to
175
+ * CommonJS.
176
+ *
177
+ * Compared case-insensitively on Windows: `require.resolve` reports the on-disk
178
+ * casing while a working directory carries whatever the shell supplied, and a
179
+ * drive-letter difference alone would silently defeat the check.
180
+ */
181
+ function containsPath(dir, target) {
182
+ const normalize = (value) => {
183
+ const resolved = node_path.default.resolve(value);
184
+ return process.platform === "win32" ? resolved.toLowerCase() : resolved;
185
+ };
186
+ const outer = normalize(dir);
187
+ const inner = normalize(target);
188
+ return inner === outer || inner.startsWith(outer.endsWith(node_path.default.sep) ? outer : outer + node_path.default.sep);
189
+ }
190
+ /**
191
+ * The on-disk directory a package resolves to, or null.
192
+ *
193
+ * `pkg/package.json` is tried first because it names the package root exactly; some
194
+ * packages do not export it, so fall back to resolving the entry and walking up to
195
+ * the manifest that names them. Symlinked and workspace packages resolve to their
196
+ * real location, which is the whole point — see buildPkgMatcher.
197
+ */
198
+ function packageDirOf(name, projectRoot) {
199
+ const req = (0, node_module.createRequire)(node_path.default.join(projectRoot, "package.json"));
200
+ try {
201
+ return node_path.default.dirname(req.resolve(`${name}/package.json`));
202
+ } catch {}
203
+ let dir;
204
+ try {
205
+ dir = node_path.default.dirname(req.resolve(name));
206
+ } catch {
207
+ return null;
208
+ }
209
+ for (;;) {
210
+ try {
211
+ if ((0, node_module.createRequire)(node_path.default.join(dir, "index.js"))("./package.json").name === name) return dir;
212
+ } catch {}
213
+ const parent = node_path.default.dirname(dir);
214
+ if (parent === dir) return null;
215
+ dir = parent;
216
+ }
217
+ }
218
+ /**
219
+ * The patterns identifying one package's files. THE rule; everything else composes it.
220
+ *
221
+ * A bare `[/\]name[/\]` test — what this used to be — also matches any DIRECTORY
222
+ * that happens to share a package's name. A project folder called `expo`, or a source
223
+ * directory named after the library it implements, made every file beneath it look
224
+ * like third-party source to be compiled. That mis-compiled unrelated files, this
225
+ * package's own runtime among them.
226
+ *
227
+ * Anchoring on `node_modules` alone would fix that and break linked packages: a
228
+ * workspace or `file:` dependency resolves to its real path, which has no
229
+ * `node_modules` segment at all. So a file matches if it is either
230
+ *
231
+ * - under `node_modules/<name>/` (covers additional copies of a package that a
232
+ * single resolution cannot see, and projects where resolution fails), or
233
+ * - inside the package's resolved directory (exact; covers workspace links, and
234
+ * stores like pnpm's and bun's).
235
+ *
236
+ * The resolved-directory anchor is dropped when that directory CONTAINS the project
237
+ * root, because then it is the project. Externalizing the project hands Vitest its
238
+ * own source and test files back through Node, which compiles them to CommonJS: a
239
+ * test file's `import { it } from 'vitest'` becomes `require('vitest')` and throws.
240
+ *
241
+ * `projectRoot` is optional; without it only the `node_modules` rule applies, since
242
+ * there is nothing to resolve against.
243
+ */
244
+ function packagePatterns(name, projectRoot) {
245
+ const patterns = [new RegExp(`[\\\\/]node_modules[\\\\/]${escapeRe(name)}[\\\\/]`)];
246
+ if (!projectRoot) return patterns;
247
+ const dir = packageDirOf(name, projectRoot);
248
+ if (dir && !containsPath(dir, projectRoot)) patterns.push(new RegExp(`^${escapeRe(toPosix(dir).replace(/\/$/, ""))}[\\\\/]`));
249
+ return patterns;
250
+ }
131
251
  /** Can this project run the native engine? (Both transform deps resolvable.) */
132
252
  function isNativeCapable(projectRoot) {
133
253
  try {
@@ -177,13 +297,54 @@ function detectEngine(requested, projectRoot, opts) {
177
297
  * engine itself wires up; pulling a second copy of them into the module graph has
178
298
  * corrupted rendering before, in ways that surface as unrelated act() and
179
299
  * host-component failures.
300
+ *
301
+ * This list is one clause of the ownership rule; the whole of it is written down in
302
+ * the header of native/apply.ts, which is the file to read before changing what ends
303
+ * up in either graph.
180
304
  */
181
- const NEVER_INLINE = new Set([
305
+ const NEVER_INLINE = /* @__PURE__ */ new Set([
182
306
  "@testing-library/react-native",
183
307
  "react-test-renderer",
184
308
  "test-renderer",
185
- "react-native"
309
+ "react-native",
310
+ "react",
311
+ "react-is"
186
312
  ]);
313
+ /** Does this manifest offer a React Native build, by legacy field or export condition? */
314
+ function hasReactNativeBuild(manifest) {
315
+ if (typeof manifest["react-native"] === "string") return true;
316
+ const seen = /* @__PURE__ */ new Set();
317
+ const search = (node) => {
318
+ if (!node || typeof node !== "object" || seen.has(node)) return false;
319
+ seen.add(node);
320
+ for (const [key, value] of Object.entries(node)) {
321
+ if (key === "react-native") return true;
322
+ if (search(value)) return true;
323
+ }
324
+ return false;
325
+ };
326
+ return search(manifest.exports);
327
+ }
328
+ /**
329
+ * A package that ships ES modules and nothing React Native.
330
+ *
331
+ * The closure walk is a guess: a detected package's dependencies MIGHT be untranspiled
332
+ * React Native source, because the ecosystem publishes that way and the dependency's
333
+ * own manifest cannot say so. `"type": "module"` is the manifest saying the opposite —
334
+ * this is runnable ES modules — and with no React Native build anywhere in it, there is
335
+ * nothing for the preset to do. Compiling it anyway rewrites a package that publishes
336
+ * ESM into CommonJS and hands it to Node under that format, which is how a dependency
337
+ * reached this way (`zod`) failed to parse and took fourteen test files down with it.
338
+ *
339
+ * A genuine React Native library is unaffected: declaring `react-native` by field or
340
+ * export condition keeps it in the closure however it publishes.
341
+ *
342
+ * Only closure MEMBERS are judged this way. A package detected on its own manifest, or
343
+ * named in `transform: [...]`, was asked for explicitly and is still compiled.
344
+ */
345
+ function publishesOnlyEsm(manifest) {
346
+ return manifest.type === "module" && !hasReactNativeBuild(manifest);
347
+ }
187
348
  /** Manifest fields that make a package part of the React Native ecosystem. */
188
349
  function dependsOnReactNative(manifest) {
189
350
  for (const field of ["dependencies", "peerDependencies"]) {
@@ -288,9 +449,9 @@ function manifestsFrom(projectRoot) {
288
449
  * test infrastructure in NEVER_INLINE, and anything the consumer listed explicitly
289
450
  * in `transform` — that option keeps its existing meaning and takes precedence.
290
451
  */
291
- function detectEcosystemPackages(projectRoot, explicit = []) {
452
+ function detectEcosystemPackages(projectRoot, explicit = [], testRoots = []) {
292
453
  const roots = (Array.isArray(projectRoot) ? projectRoot : [projectRoot]).filter(Boolean);
293
- const skip = new Set([
454
+ const skip = /* @__PURE__ */ new Set([
294
455
  ...NEVER_INLINE,
295
456
  ...Object.keys(require_preset_map.AUTO_DETECT_PRESETS),
296
457
  ...explicit
@@ -307,15 +468,96 @@ function detectEcosystemPackages(projectRoot, explicit = []) {
307
468
  if (deps && typeof deps === "object") for (const name of Object.keys(deps)) candidates.add(name);
308
469
  }
309
470
  if (candidates.size === 0) return [];
471
+ /** Resolve a package's manifest from whichever root can see it. */
472
+ const manifestOf = (name) => {
473
+ for (const req of requires) try {
474
+ return req(`${name}/package.json`);
475
+ } catch {}
476
+ return null;
477
+ };
478
+ /**
479
+ * The packages the run itself lives in — the project, in other words.
480
+ *
481
+ * In a workspace, the package under test is usually declared as a dependency by a
482
+ * sibling or by the repository root, so it appears in the candidate set like any
483
+ * third-party library — and it declares React Native, because it is React Native
484
+ * code. Detecting it would claim the project's own source: its directory becomes a
485
+ * `server.deps.external` pattern, so Vitest hands every file under it to Node,
486
+ * where the loader compiles it to CommonJS. A test file's own
487
+ * `import { it } from 'vitest'` becomes `require('vitest')`, which throws
488
+ * "Vitest cannot be imported in a CommonJS module using require()" — a failure that
489
+ * appears in one workspace package and not another for no visible reason.
490
+ *
491
+ * A package cannot be its own dependency, so a manifest whose directory contains a
492
+ * run root belongs to the project. Read straight off the manifests already walked,
493
+ * which is both cheaper than resolving each candidate and independent of how a
494
+ * package manager happens to lay out its store — under pnpm every workspace member
495
+ * is additionally linked into a hidden directory on NODE_PATH, so a package can
496
+ * resolve its own name from its own directory, but nothing here depends on that.
497
+ *
498
+ * Workspace libraries the project merely depends on sit beside a run root rather
499
+ * than above it and are unaffected — detecting those is the point of the
500
+ * workspace-member walk above.
501
+ */
502
+ const ownerRoots = [...roots, ...testRoots];
503
+ const runOwners = new Set(found.filter(({ dir }) => ownerRoots.some((root) => containsPath(dir, root))).map(({ manifest }) => manifest.name).filter((name) => typeof name === "string"));
504
+ const ownsTheRun = (name) => runOwners.has(name);
310
505
  const detected = [];
311
506
  for (const name of candidates) {
312
507
  if (skip.has(name) || name.startsWith("@react-native/")) continue;
313
- for (const req of requires) try {
314
- if (dependsOnReactNative(req(`${name}/package.json`))) detected.push(name);
315
- break;
316
- } catch {}
508
+ const pkg = manifestOf(name);
509
+ if (pkg && dependsOnReactNative(pkg) && !ownsTheRun(name)) detected.push(name);
510
+ }
511
+ const rnOwned = new Set(Object.keys(manifestOf("react-native")?.dependencies ?? {}));
512
+ /** Every package reachable from `roots` through runtime dependencies. */
513
+ const closureOf = (starts) => {
514
+ const seen = /* @__PURE__ */ new Set();
515
+ const pending = [...starts];
516
+ while (pending.length > 0) {
517
+ const name = pending.pop();
518
+ if (seen.has(name)) continue;
519
+ seen.add(name);
520
+ const deps = manifestOf(name)?.dependencies;
521
+ if (deps && typeof deps === "object") pending.push(...Object.keys(deps));
522
+ }
523
+ return seen;
524
+ };
525
+ const toolchain = closureOf([
526
+ "@babel/core",
527
+ "@react-native/babel-preset",
528
+ "@babel/runtime",
529
+ "metro"
530
+ ]);
531
+ const projectDeclared = /* @__PURE__ */ new Set();
532
+ for (const { dir, manifest } of found) {
533
+ if (!ownerRoots.some((root) => containsPath(dir, root))) continue;
534
+ for (const field of [
535
+ "dependencies",
536
+ "devDependencies",
537
+ "optionalDependencies"
538
+ ]) {
539
+ const deps = manifest[field];
540
+ if (deps && typeof deps === "object") for (const name of Object.keys(deps)) projectDeclared.add(name);
541
+ }
317
542
  }
318
- return detected.sort();
543
+ const inClosure = new Set(detected);
544
+ const queue = detected.filter((name) => projectDeclared.has(name));
545
+ while (queue.length > 0) {
546
+ const deps = manifestOf(queue.pop())?.dependencies;
547
+ if (!deps || typeof deps !== "object") continue;
548
+ for (const dep of Object.keys(deps)) {
549
+ if (inClosure.has(dep) || skip.has(dep) || dep.startsWith("@react-native/")) continue;
550
+ if (rnOwned.has(dep)) continue;
551
+ if (toolchain.has(dep)) continue;
552
+ if (ownsTheRun(dep)) continue;
553
+ const depManifest = manifestOf(dep);
554
+ if (!depManifest) continue;
555
+ if (publishesOnlyEsm(depManifest)) continue;
556
+ inClosure.add(dep);
557
+ queue.push(dep);
558
+ }
559
+ }
560
+ return [...inClosure].sort();
319
561
  }
320
562
  //#endregion
321
563
  Object.defineProperty(exports, "PEER_REQUIREMENTS", {
@@ -324,6 +566,18 @@ Object.defineProperty(exports, "PEER_REQUIREMENTS", {
324
566
  return PEER_REQUIREMENTS;
325
567
  }
326
568
  });
569
+ Object.defineProperty(exports, "REACT_NATIVE_PATH", {
570
+ enumerable: true,
571
+ get: function() {
572
+ return REACT_NATIVE_PATH;
573
+ }
574
+ });
575
+ Object.defineProperty(exports, "containsPath", {
576
+ enumerable: true,
577
+ get: function() {
578
+ return containsPath;
579
+ }
580
+ });
327
581
  Object.defineProperty(exports, "detectEcosystemPackages", {
328
582
  enumerable: true,
329
583
  get: function() {
@@ -336,6 +590,18 @@ Object.defineProperty(exports, "detectEngine", {
336
590
  return detectEngine;
337
591
  }
338
592
  });
593
+ Object.defineProperty(exports, "packageDirOf", {
594
+ enumerable: true,
595
+ get: function() {
596
+ return packageDirOf;
597
+ }
598
+ });
599
+ Object.defineProperty(exports, "packagePatterns", {
600
+ enumerable: true,
601
+ get: function() {
602
+ return packagePatterns;
603
+ }
604
+ });
339
605
  Object.defineProperty(exports, "validateOptions", {
340
606
  enumerable: true,
341
607
  get: function() {
@@ -1,5 +1,5 @@
1
- import { n as VitestNativeTypeError } from "./errors-Dm5yLNTF.mjs";
2
- import { t as AUTO_DETECT_PRESETS } from "./preset-map-BpDG_D5m.mjs";
1
+ import { n as VitestNativeTypeError } from "./errors-CxoBUfVJ.mjs";
2
+ import { t as AUTO_DETECT_PRESETS } from "./preset-map-DuX0ocdn.mjs";
3
3
  import { createRequire } from "node:module";
4
4
  import fs from "node:fs";
5
5
  import path from "node:path";
@@ -125,6 +125,126 @@ const PEER_REQUIREMENTS = [
125
125
  optional: true
126
126
  }
127
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
+ }
128
248
  /** Can this project run the native engine? (Both transform deps resolvable.) */
129
249
  function isNativeCapable(projectRoot) {
130
250
  try {
@@ -174,13 +294,54 @@ function detectEngine(requested, projectRoot, opts) {
174
294
  * engine itself wires up; pulling a second copy of them into the module graph has
175
295
  * corrupted rendering before, in ways that surface as unrelated act() and
176
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.
177
301
  */
178
- const NEVER_INLINE = new Set([
302
+ const NEVER_INLINE = /* @__PURE__ */ new Set([
179
303
  "@testing-library/react-native",
180
304
  "react-test-renderer",
181
305
  "test-renderer",
182
- "react-native"
306
+ "react-native",
307
+ "react",
308
+ "react-is"
183
309
  ]);
310
+ /** Does this manifest offer a React Native build, by legacy field or export condition? */
311
+ function hasReactNativeBuild(manifest) {
312
+ if (typeof manifest["react-native"] === "string") return true;
313
+ const seen = /* @__PURE__ */ new Set();
314
+ const search = (node) => {
315
+ if (!node || typeof node !== "object" || seen.has(node)) return false;
316
+ seen.add(node);
317
+ for (const [key, value] of Object.entries(node)) {
318
+ if (key === "react-native") return true;
319
+ if (search(value)) return true;
320
+ }
321
+ return false;
322
+ };
323
+ return search(manifest.exports);
324
+ }
325
+ /**
326
+ * A package that ships ES modules and nothing React Native.
327
+ *
328
+ * The closure walk is a guess: a detected package's dependencies MIGHT be untranspiled
329
+ * React Native source, because the ecosystem publishes that way and the dependency's
330
+ * own manifest cannot say so. `"type": "module"` is the manifest saying the opposite —
331
+ * this is runnable ES modules — and with no React Native build anywhere in it, there is
332
+ * nothing for the preset to do. Compiling it anyway rewrites a package that publishes
333
+ * ESM into CommonJS and hands it to Node under that format, which is how a dependency
334
+ * reached this way (`zod`) failed to parse and took fourteen test files down with it.
335
+ *
336
+ * A genuine React Native library is unaffected: declaring `react-native` by field or
337
+ * export condition keeps it in the closure however it publishes.
338
+ *
339
+ * Only closure MEMBERS are judged this way. A package detected on its own manifest, or
340
+ * named in `transform: [...]`, was asked for explicitly and is still compiled.
341
+ */
342
+ function publishesOnlyEsm(manifest) {
343
+ return manifest.type === "module" && !hasReactNativeBuild(manifest);
344
+ }
184
345
  /** Manifest fields that make a package part of the React Native ecosystem. */
185
346
  function dependsOnReactNative(manifest) {
186
347
  for (const field of ["dependencies", "peerDependencies"]) {
@@ -285,9 +446,9 @@ function manifestsFrom(projectRoot) {
285
446
  * test infrastructure in NEVER_INLINE, and anything the consumer listed explicitly
286
447
  * in `transform` — that option keeps its existing meaning and takes precedence.
287
448
  */
288
- function detectEcosystemPackages(projectRoot, explicit = []) {
449
+ function detectEcosystemPackages(projectRoot, explicit = [], testRoots = []) {
289
450
  const roots = (Array.isArray(projectRoot) ? projectRoot : [projectRoot]).filter(Boolean);
290
- const skip = new Set([
451
+ const skip = /* @__PURE__ */ new Set([
291
452
  ...NEVER_INLINE,
292
453
  ...Object.keys(AUTO_DETECT_PRESETS),
293
454
  ...explicit
@@ -304,15 +465,96 @@ function detectEcosystemPackages(projectRoot, explicit = []) {
304
465
  if (deps && typeof deps === "object") for (const name of Object.keys(deps)) candidates.add(name);
305
466
  }
306
467
  if (candidates.size === 0) return [];
468
+ /** Resolve a package's manifest from whichever root can see it. */
469
+ const manifestOf = (name) => {
470
+ for (const req of requires) try {
471
+ return req(`${name}/package.json`);
472
+ } catch {}
473
+ return null;
474
+ };
475
+ /**
476
+ * The packages the run itself lives in — the project, in other words.
477
+ *
478
+ * In a workspace, the package under test is usually declared as a dependency by a
479
+ * sibling or by the repository root, so it appears in the candidate set like any
480
+ * third-party library — and it declares React Native, because it is React Native
481
+ * code. Detecting it would claim the project's own source: its directory becomes a
482
+ * `server.deps.external` pattern, so Vitest hands every file under it to Node,
483
+ * where the loader compiles it to CommonJS. A test file's own
484
+ * `import { it } from 'vitest'` becomes `require('vitest')`, which throws
485
+ * "Vitest cannot be imported in a CommonJS module using require()" — a failure that
486
+ * appears in one workspace package and not another for no visible reason.
487
+ *
488
+ * A package cannot be its own dependency, so a manifest whose directory contains a
489
+ * run root belongs to the project. Read straight off the manifests already walked,
490
+ * which is both cheaper than resolving each candidate and independent of how a
491
+ * package manager happens to lay out its store — under pnpm every workspace member
492
+ * is additionally linked into a hidden directory on NODE_PATH, so a package can
493
+ * resolve its own name from its own directory, but nothing here depends on that.
494
+ *
495
+ * Workspace libraries the project merely depends on sit beside a run root rather
496
+ * than above it and are unaffected — detecting those is the point of the
497
+ * workspace-member walk above.
498
+ */
499
+ const ownerRoots = [...roots, ...testRoots];
500
+ const runOwners = new Set(found.filter(({ dir }) => ownerRoots.some((root) => containsPath(dir, root))).map(({ manifest }) => manifest.name).filter((name) => typeof name === "string"));
501
+ const ownsTheRun = (name) => runOwners.has(name);
307
502
  const detected = [];
308
503
  for (const name of candidates) {
309
504
  if (skip.has(name) || name.startsWith("@react-native/")) continue;
310
- for (const req of requires) try {
311
- if (dependsOnReactNative(req(`${name}/package.json`))) detected.push(name);
312
- break;
313
- } catch {}
505
+ const pkg = manifestOf(name);
506
+ if (pkg && dependsOnReactNative(pkg) && !ownsTheRun(name)) detected.push(name);
507
+ }
508
+ const rnOwned = new Set(Object.keys(manifestOf("react-native")?.dependencies ?? {}));
509
+ /** Every package reachable from `roots` through runtime dependencies. */
510
+ const closureOf = (starts) => {
511
+ const seen = /* @__PURE__ */ new Set();
512
+ const pending = [...starts];
513
+ while (pending.length > 0) {
514
+ const name = pending.pop();
515
+ if (seen.has(name)) continue;
516
+ seen.add(name);
517
+ const deps = manifestOf(name)?.dependencies;
518
+ if (deps && typeof deps === "object") pending.push(...Object.keys(deps));
519
+ }
520
+ return seen;
521
+ };
522
+ const toolchain = closureOf([
523
+ "@babel/core",
524
+ "@react-native/babel-preset",
525
+ "@babel/runtime",
526
+ "metro"
527
+ ]);
528
+ const projectDeclared = /* @__PURE__ */ new Set();
529
+ for (const { dir, manifest } of found) {
530
+ if (!ownerRoots.some((root) => containsPath(dir, root))) continue;
531
+ for (const field of [
532
+ "dependencies",
533
+ "devDependencies",
534
+ "optionalDependencies"
535
+ ]) {
536
+ const deps = manifest[field];
537
+ if (deps && typeof deps === "object") for (const name of Object.keys(deps)) projectDeclared.add(name);
538
+ }
539
+ }
540
+ const inClosure = new Set(detected);
541
+ const queue = detected.filter((name) => projectDeclared.has(name));
542
+ while (queue.length > 0) {
543
+ const deps = manifestOf(queue.pop())?.dependencies;
544
+ if (!deps || typeof deps !== "object") continue;
545
+ for (const dep of Object.keys(deps)) {
546
+ if (inClosure.has(dep) || skip.has(dep) || dep.startsWith("@react-native/")) continue;
547
+ if (rnOwned.has(dep)) continue;
548
+ if (toolchain.has(dep)) continue;
549
+ if (ownsTheRun(dep)) continue;
550
+ const depManifest = manifestOf(dep);
551
+ if (!depManifest) continue;
552
+ if (publishesOnlyEsm(depManifest)) continue;
553
+ inClosure.add(dep);
554
+ queue.push(dep);
555
+ }
314
556
  }
315
- return detected.sort();
557
+ return [...inClosure].sort();
316
558
  }
317
559
  //#endregion
318
- export { validatePeerDependency as a, validateOptions as i, detectEngine as n, warnUnknownOptions as o, PEER_REQUIREMENTS as r, detectEcosystemPackages as t };
560
+ 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 };
package/dist/helpers.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_errors = require("./errors-flXDIeWk.cjs");
2
+ const require_errors = require("./errors-B3lJK46O.cjs");
3
3
  //#region src/helpers.ts
4
4
  /**
5
5
  * Test helpers for vitest-native.
package/dist/helpers.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { t as VitestNativeError } from "./errors-Dm5yLNTF.mjs";
1
+ import { t as VitestNativeError } from "./errors-CxoBUfVJ.mjs";
2
2
  //#region src/helpers.ts
3
3
  /**
4
4
  * Test helpers for vitest-native.