vitest-native 0.14.0-rc.11 → 0.14.0-rc.12

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.
package/dist/cli.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { C as validatePeerDependency, _ as fsModuleCacheOnByDefault, b as installedExpoVersion, c as detectEngine, i as ownVitestPackage, l as resolveTransformPreset, o as usesVitePlus, p as formatNativeOwnershipManifest, r as installedViteVersion, s as detectEcosystemPackages, u as createNativeOwnershipPolicy, x as unsupportedExpoSdkMessage, y as PEER_REQUIREMENTS } from "./host-C3wt9zUE.mjs";
2
+ import { C as unsupportedExpoSdkMessage, S as installedExpoVersion, T as validatePeerDependency, c as detectEngine, i as ownVitestPackage, l as resolveTransformPreset, o as usesVitePlus, p as formatNativeOwnershipManifest, r as installedViteVersion, s as detectEcosystemPackages, u as createNativeOwnershipPolicy, x as PEER_REQUIREMENTS, y as fsModuleCacheOnByDefault } from "./host-B4fG_RZ8.mjs";
3
3
  import { i as autoDetectedPresetApplies, n as DEFAULT_ASSET_EXTS, o as presetShadowing, r as PRESET_MODULES, s as testsItself, t as AUTO_DETECT_PRESETS } from "./preset-map-L1-vD19T.mjs";
4
4
  import { n as formatHotMemoryPlan, t as createHotMemoryPlan } from "./memory-BFxB285Z.mjs";
5
5
  import { createRequire } from "node:module";
@@ -416,10 +416,19 @@ function containsPath(dir, target) {
416
416
  * point — see buildPkgMatcher.
417
417
  */
418
418
  function packageDirOf(name, fromDir) {
419
+ return findPackageDir(name, fromDir, false);
420
+ }
421
+ /** packageDirOf, or with `installedOnly` dependencyDirOf. */
422
+ function findPackageDir(name, fromDir, installedOnly) {
419
423
  const req = createRequire(path.join(fromDir, "package.json"));
420
424
  try {
421
425
  return canonicalDir(path.dirname(req.resolve(`${name}/package.json`)));
422
426
  } catch {}
427
+ const found = findUnexportedPackageDir(name, req);
428
+ return installedOnly && found !== null && !NODE_MODULES_PATH.test(found) ? null : found;
429
+ }
430
+ /** The steps after `<name>/package.json` fails: the lookup paths, then the entry. */
431
+ function findUnexportedPackageDir(name, req) {
423
432
  for (const lookup of req.resolve.paths(name) ?? []) {
424
433
  const candidate = path.join(lookup, ...name.split("/"));
425
434
  if (fs.existsSync(path.join(candidate, "package.json"))) return canonicalDir(candidate);
@@ -440,6 +449,60 @@ function packageDirOf(name, fromDir) {
440
449
  }
441
450
  }
442
451
  /**
452
+ * The directory of a dependency the engine may DETECT (ecosystem detection), or null.
453
+ *
454
+ * A package whose `exports` map leaves out `./package.json` is found the way
455
+ * packageDirOf finds it only when it is installed: its real path lies inside a node_modules directory, as
456
+ * expo-symbols 57's does (#406). A workspace member, whose real path lies outside every
457
+ * node_modules, is found only when `<name>/package.json` resolves, which is the rule
458
+ * 0.14.0-rc.10 and earlier applied to every package.
459
+ *
460
+ * Why the two differ: detecting a workspace member makes it Node-owned, so `vi.mock`
461
+ * from a test no longer reaches its internal imports and any of its files that imports
462
+ * `vitest` fails. Widening detection to every workspace member whose exports omit
463
+ * `./package.json` changed that silently for libraries that ran in Vite before. Which
464
+ * owner a workspace member should have is the ownership track's decision (A3, the
465
+ * ownership predicate; A6, the fix for `vi.mock` reaching a Node-owned package's own
466
+ * imports, #322), not a side effect of how its manifest is found. Rejected: applying
467
+ * #406 to workspace members as well (the silent change above), and reverting #406
468
+ * (expo-symbols then runs uncompiled again).
469
+ */
470
+ function dependencyDirOf(name, fromDir) {
471
+ return findPackageDir(name, fromDir, true);
472
+ }
473
+ /**
474
+ * `packageDirOf` (or `resolve`, such as dependencyDirOf) with each answer kept for the
475
+ * life of the returned function.
476
+ *
477
+ * One config evaluation asks for the same directories several times: detection, the
478
+ * linked-package check, and every pattern list and matcher the ownership policy
479
+ * builds. On an Expo project that is hundreds of packages, each a handful of
480
+ * resolutions and real-path calls, repeated three to five times over.
481
+ *
482
+ * Nothing here is module state, so this file stays pure (see the header): the caller
483
+ * owns the cache and decides how long it lives. The plugin makes one per lookup
484
+ * function per config evaluation, and Vitest evaluates the config afresh when it
485
+ * restarts in watch mode, so a package installed mid-session is seen on the next
486
+ * restart, as before.
487
+ *
488
+ * Keyed by `fromDir` as resolved, not by its real path. The answer is already in
489
+ * Node's real-path spelling (canonicalDir); it is the QUESTION that depends on the
490
+ * spelling, because Node's lookup paths are built from `fromDir` as written, and a
491
+ * symlinked spelling walks different parent node_modules than the real one. Two
492
+ * spellings of one directory therefore cost two lookups, but can never be handed each
493
+ * other's answer.
494
+ */
495
+ function memoizePackageDirOf(resolve = packageDirOf) {
496
+ const dirs = /* @__PURE__ */ new Map();
497
+ return (name, fromDir) => {
498
+ const key = `${path.resolve(fromDir)}\0${name}`;
499
+ if (dirs.has(key)) return dirs.get(key);
500
+ const dir = resolve(name, fromDir);
501
+ dirs.set(key, dir);
502
+ return dir;
503
+ };
504
+ }
505
+ /**
443
506
  * The patterns identifying one package's files. THE rule; everything else composes it.
444
507
  *
445
508
  * A bare `[/\]name[/\]` test — what this used to be — also matches any DIRECTORY
@@ -463,12 +526,13 @@ function packageDirOf(name, fromDir) {
463
526
  * test file's `import { it } from 'vitest'` becomes `require('vitest')` and throws.
464
527
  *
465
528
  * `projectRoot` is optional; without it only the `node_modules` rule applies, since
466
- * there is nothing to resolve against.
529
+ * there is nothing to resolve against. `dirOf` is how the directory is found:
530
+ * `packageDirOf`, or a memoized copy of it (memoizePackageDirOf).
467
531
  */
468
- function packagePatterns(name, projectRoot) {
532
+ function packagePatterns(name, projectRoot, dirOf = packageDirOf) {
469
533
  const patterns = [new RegExp(`[\\\\/]node_modules[\\\\/]${escapeRe$1(name)}[\\\\/]`)];
470
534
  if (!projectRoot) return patterns;
471
- const dir = packageDirOf(name, projectRoot);
535
+ const dir = dirOf(name, projectRoot);
472
536
  if (dir && !containsPath(dir, projectRoot)) patterns.push(new RegExp(`^${escapeRe$1(toPosix(dir).replace(/\/$/, ""))}[\\\\/]`));
473
537
  return patterns;
474
538
  }
@@ -480,8 +544,8 @@ function packagePatterns(name, projectRoot) {
480
544
  * slashes (the form Vitest presents module ids in) while callers here pass whatever
481
545
  * Node handed them, which on Windows is backslashes.
482
546
  */
483
- function buildPkgMatcher(pkgs, projectRoot) {
484
- const patterns = (pkgs || []).flatMap((name) => packagePatterns(name, projectRoot));
547
+ function buildPkgMatcher(pkgs, projectRoot, dirOf = packageDirOf) {
548
+ const patterns = (pkgs || []).flatMap((name) => packagePatterns(name, projectRoot, dirOf));
485
549
  return (file) => {
486
550
  const norm = toPosix(file);
487
551
  return patterns.some((re) => re.test(norm));
@@ -498,7 +562,12 @@ function buildPkgMatcher(pkgs, projectRoot) {
498
562
  * the Vite main process and every worker reconstruct the same decision.
499
563
  */
500
564
  const OUTSIDE_NODE_MODULES = String.raw`^(?!.*[\\/]node_modules[\\/])`;
501
- /** Files Vitest may execute as entries. They always belong to Vite. */
565
+ /**
566
+ * Files Vitest may execute as entries. They always belong to Vite.
567
+ *
568
+ * Test files are recognised by name. A setup file has no naming convention, so the
569
+ * project's `test.setupFiles` are passed in as `entryFiles` instead (see decideFile).
570
+ */
502
571
  const TEST_ENTRY_PATTERNS = Object.freeze([new RegExp(String.raw`${OUTSIDE_NODE_MODULES}.*\.(?:test|spec)\.[cm]?[jt]sx?$`), new RegExp(String.raw`${OUTSIDE_NODE_MODULES}.*[\\/]__tests__[\\/].*\.[cm]?[jt]sx?$`)]);
503
572
  /**
504
573
  * Identity-sensitive runtime packages whose CJS entries cannot be dropped while
@@ -552,8 +621,14 @@ function decision(owner, format, transform, reset, reasons, evidence) {
552
621
  * `ecosystemPackages` is the detected RN dependency closure.
553
622
  * `runtimeTransforms` is for workers reconstructing the already-combined list from
554
623
  * serialized setup data; config-time callers normally leave it empty.
624
+ *
625
+ * `packageDirOf` finds each package's directory. Each package is looked up once per
626
+ * policy whatever is passed (the patterns and every matcher share the answers); a
627
+ * caller that has already resolved the same packages from the same root passes its
628
+ * own memoized lookup (memoizePackageDirOf) so they are not resolved again.
555
629
  */
556
- function createNativeOwnershipPolicy({ projectRoot = process.cwd(), explicitTransforms = [], ecosystemPackages = [], runtimeTransforms = [], runtimeTransformAugmentations = [], projectDirs = [], reactNativeRoots = [], serverDepsInlineAll = false } = {}) {
630
+ function createNativeOwnershipPolicy({ projectRoot = process.cwd(), explicitTransforms = [], ecosystemPackages = [], runtimeTransforms = [], runtimeTransformAugmentations = [], projectDirs = [], reactNativeRoots = [], entryFiles = [], serverDepsInlineAll = false, packageDirOf } = {}) {
631
+ const dirOf = memoizePackageDirOf(packageDirOf);
557
632
  const enforcement = serverDepsInlineAll ? "overridden-by-inline-all" : "enforced";
558
633
  const root = path.resolve(projectRoot);
559
634
  const explicit = unique(explicitTransforms);
@@ -581,16 +656,23 @@ function createNativeOwnershipPolicy({ projectRoot = process.cwd(), explicitTran
581
656
  const externalPatterns = [
582
657
  REACT_NATIVE_PATH,
583
658
  ...reactNativeRootPatterns,
584
- ...nodeTransformPackages.flatMap((name) => packagePatterns(name, root))
659
+ ...nodeTransformPackages.flatMap((name) => packagePatterns(name, root, dirOf))
585
660
  ];
586
- const matchesNodeTransformedFile = buildPkgMatcher(nodeTransformPackages, root);
587
- const explicitMatcher = buildPkgMatcher(explicit, root);
588
- const ecosystemMatcher = buildPkgMatcher(ecosystem, root);
589
- const runtimeMatcher = buildPkgMatcher(runtime, root);
661
+ const matchesNodeTransformedFile = buildPkgMatcher(nodeTransformPackages, root, dirOf);
662
+ const explicitMatcher = buildPkgMatcher(explicit, root, dirOf);
663
+ const ecosystemMatcher = buildPkgMatcher(ecosystem, root, dirOf);
664
+ const runtimeMatcher = buildPkgMatcher(runtime, root, dirOf);
590
665
  const normalizedProjectDirs = Object.freeze(unique(projectDirs).map((dir) => path.resolve(dir)));
666
+ const normalizedEntryFiles = Object.freeze(unique(entryFiles).map((file) => path.resolve(file)));
667
+ const entryKey = (file) => {
668
+ const resolved = path.resolve(file);
669
+ return process.platform === "win32" ? resolved.toLowerCase() : resolved;
670
+ };
671
+ const entryKeys = new Set(normalizedEntryFiles.map(entryKey));
591
672
  const decideFile = (rawFile) => {
592
673
  const file = cleanFileId(rawFile);
593
674
  if (TEST_ENTRY_PATTERNS.some((pattern) => pattern.test(file))) return decision("vite", "source", "vite", "per-file", ["test-entry"], [file]);
675
+ if (entryKeys.size > 0 && !NODE_MODULES_PATH.test(file) && entryKeys.has(entryKey(cleanRawFileId(rawFile)))) return decision("vite", "source", "vite", "per-file", ["test-entry"], ["test.setupFiles", file]);
594
676
  const runtimeResident = isRuntimeResidentFile(file);
595
677
  const testRuntimeResident = isTestRuntimeResidentFile(file);
596
678
  if (isReactNativeCore(file, rawFile)) return decision("node", "cjs", "registry", "worker-resident", ["react-native-core"], [normalizedReactNativeRoots.find((dir) => containsPath(dir, cleanRawFileId(rawFile))) ?? "react-native/@react-native path", "preloaded before the hot reset baseline"]);
@@ -610,6 +692,7 @@ function createNativeOwnershipPolicy({ projectRoot = process.cwd(), explicitTran
610
692
  enforcement,
611
693
  projectRoot: root,
612
694
  projectDirs: normalizedProjectDirs,
695
+ entryFiles: normalizedEntryFiles,
613
696
  reactNativeRoots: normalizedReactNativeRoots,
614
697
  nodeTransformPackages,
615
698
  runtimeTransformAugmentations: runtimeAugmentations,
@@ -660,7 +743,8 @@ function createNativeOwnershipPolicy({ projectRoot = process.cwd(), explicitTran
660
743
  transform: "vite",
661
744
  reset: "per-file",
662
745
  reason: "test-entry",
663
- patterns: Object.freeze(TEST_ENTRY_PATTERNS.map(String))
746
+ patterns: Object.freeze(TEST_ENTRY_PATTERNS.map(String)),
747
+ files: normalizedEntryFiles
664
748
  }),
665
749
  Object.freeze({
666
750
  effect: "reset-if-external",
@@ -686,7 +770,8 @@ function createNativeOwnershipPolicy({ projectRoot = process.cwd(), explicitTran
686
770
  isReactNativeFile: (file) => isReactNativeCore(cleanFileId(file), file),
687
771
  reactNativePathFor,
688
772
  decideFile,
689
- manifest
773
+ manifest,
774
+ packageDirOf: (name) => dirOf(name, root)
690
775
  });
691
776
  }
692
777
  /**
@@ -726,7 +811,7 @@ function findNativeInlineConflicts(policy, inline) {
726
811
  for (const name of packages) {
727
812
  const concrete = name === "@react-native/*" ? "@react-native/assets-registry" : name;
728
813
  const probes = [`/project/node_modules/${concrete}/index.js`, `C:\\project\\node_modules\\${concrete.replaceAll("/", "\\")}\\index.js`];
729
- const dir = name.includes("*") ? null : packageDirOf(name, policy.projectRoot);
814
+ const dir = name.includes("*") ? null : policy.packageDirOf(name);
730
815
  if (dir) probes.push(`${normalizeFile(dir).replace(/\/$/, "")}/index.js`);
731
816
  if (patterns.some((pattern) => {
732
817
  if (typeof pattern === "string") {
@@ -757,6 +842,7 @@ function parseNativeOwnershipManifest(raw) {
757
842
  if (!value || typeof value !== "object" || value.version !== 1) return null;
758
843
  if (value.enforcement !== "enforced" && value.enforcement !== "overridden-by-inline-all") return null;
759
844
  if (typeof value.projectRoot !== "string") return null;
845
+ if (value.entryFiles !== void 0 && !(Array.isArray(value.entryFiles) && value.entryFiles.every((entry) => typeof entry === "string"))) return null;
760
846
  for (const key of [
761
847
  "projectDirs",
762
848
  "reactNativeRoots",
@@ -786,7 +872,7 @@ function formatNativeOwnershipManifest(input) {
786
872
  const list = (values) => values.length > 0 ? values.join(", ") : "(none)";
787
873
  const lines = [
788
874
  `project: ${manifest.projectRoot}`,
789
- `Vite / reset per file: ${list(manifest.projectDirs)} plus test entries`,
875
+ `Vite / reset per file: ${list(manifest.projectDirs)} plus test entries${manifest.entryFiles?.length ? ` and setup files (${manifest.entryFiles.join(", ")})` : ""}`,
790
876
  `Node / worker resident: react-native, @react-native/* (${list(manifest.reactNativeRoots)})`,
791
877
  `Node / native transform / reset per file: ${list(manifest.nodeTransformPackages)}`,
792
878
  `worker-time transform augmentations: ${list(manifest.runtimeTransformAugmentations)}`,
@@ -915,6 +1001,8 @@ function detectEngine(requested, projectRoot, opts) {
915
1001
  }
916
1002
  //#endregion
917
1003
  //#region src/native/ecosystem.ts
1004
+ /** A path inside a node_modules directory: an installed package's, not a workspace member's. */
1005
+ const NODE_MODULES_DIR = /[\\/]node_modules[\\/]/;
918
1006
  /**
919
1007
  * Packages that must never be auto-inlined even though they depend on React
920
1008
  * Native. The test library and the renderers underneath it are infrastructure the
@@ -1072,8 +1160,14 @@ function manifestsFrom(projectRoot) {
1072
1160
  * Excluded: packages a preset already shadows (their real source never loads), the
1073
1161
  * test infrastructure in NEVER_INLINE, and anything the consumer listed explicitly
1074
1162
  * in `transform` — that option keeps its existing meaning and takes precedence.
1163
+ *
1164
+ * `dirOf` finds a dependency's directory from a directory: `dependencyDirOf`, or a
1165
+ * memoized copy of it (memoizePackageDirOf). Not `packageDirOf`, whose answer for a
1166
+ * workspace member differs (see dependencyDirOf).
1167
+ *
1168
+ * `reachedPaths` adds the workspace members an alias reaches; see ReachedPackages.
1075
1169
  */
1076
- function detectEcosystemPackages(projectRoot, explicit = [], testRoots = [], neverTransform = [], activePresets) {
1170
+ function detectEcosystemPackages(projectRoot, explicit = [], testRoots = [], neverTransform = [], activePresets, dirOf = dependencyDirOf, { reachedPaths = [], onReachedUndeclared } = {}) {
1077
1171
  const roots = (Array.isArray(projectRoot) ? projectRoot : [projectRoot]).filter(Boolean);
1078
1172
  const shadowed = Object.entries(AUTO_DETECT_PRESETS).filter(([, presetName]) => activePresets === void 0 || activePresets.includes(presetName)).map(([pkg]) => pkg);
1079
1173
  const skip = /* @__PURE__ */ new Set([
@@ -1095,7 +1189,7 @@ function detectEcosystemPackages(projectRoot, explicit = [], testRoots = [], nev
1095
1189
  }
1096
1190
  if (candidates.size === 0) return [];
1097
1191
  const installedFrom = (fromDir, name) => {
1098
- const dir = packageDirOf(name, fromDir);
1192
+ const dir = dirOf(name, fromDir);
1099
1193
  if (!dir) return null;
1100
1194
  try {
1101
1195
  return {
@@ -1212,23 +1306,62 @@ function detectEcosystemPackages(projectRoot, explicit = [], testRoots = [], nev
1212
1306
  }
1213
1307
  /** A dependency or peer the walk may not take, whatever its manifest says. */
1214
1308
  const excluded = (dep) => skip.has(dep) || dep.startsWith("@react-native/") || rnOwned.has(dep) || toolchain.has(dep) || ownsTheRun(dep);
1215
- while (queue.length > 0) {
1216
- const pkg = queue.pop();
1217
- const deps = pkg.manifest.dependencies;
1309
+ /**
1310
+ * Walk the queue. With `installedOnly`, only installed packages (a real path inside a
1311
+ * node_modules directory) are added: see "Workspace members the run reaches" below.
1312
+ */
1313
+ const walk = (installedOnly) => {
1314
+ const admits = (installed) => !installedOnly || NODE_MODULES_DIR.test(installed.dir);
1315
+ while (queue.length > 0) {
1316
+ const pkg = queue.pop();
1317
+ const deps = pkg.manifest.dependencies;
1318
+ for (const dep of deps && typeof deps === "object" ? Object.keys(deps) : []) {
1319
+ if (walked.has(dep) || excluded(dep)) continue;
1320
+ const installed = dependencyOf(pkg, dep);
1321
+ if (!installed) continue;
1322
+ if (!inClosure.has(dep) && publishesOnlyEsm(installed.manifest)) continue;
1323
+ if (admits(installed)) reach(dep, installed);
1324
+ }
1325
+ const peers = pkg.manifest.peerDependencies;
1326
+ for (const peer of peers && typeof peers === "object" ? Object.keys(peers) : []) {
1327
+ if (walked.has(peer) || excluded(peer) || !detectedSet.has(peer)) continue;
1328
+ const installed = dependencyOf(pkg, peer);
1329
+ if (installed && admits(installed)) reach(peer, installed);
1330
+ }
1331
+ }
1332
+ };
1333
+ walk(false);
1334
+ const members = found.filter(({ dir, manifest }) => typeof manifest.name === "string" && !ownerRoots.some((root) => containsPath(dir, root)));
1335
+ const memberByName = new Map(members.map((m) => [m.manifest.name, m]));
1336
+ const reachedMembers = /* @__PURE__ */ new Map();
1337
+ const reachMember = (member) => {
1338
+ if (reachedMembers.has(member.dir)) return;
1339
+ reachedMembers.set(member.dir, member);
1340
+ const deps = member.manifest.dependencies;
1218
1341
  for (const dep of deps && typeof deps === "object" ? Object.keys(deps) : []) {
1219
- if (walked.has(dep) || excluded(dep)) continue;
1220
- const installed = dependencyOf(pkg, dep);
1221
- if (!installed) continue;
1222
- if (!inClosure.has(dep) && publishesOnlyEsm(installed.manifest)) continue;
1223
- reach(dep, installed);
1342
+ const other = memberByName.get(dep);
1343
+ if (other) reachMember(other);
1224
1344
  }
1225
- const peers = pkg.manifest.peerDependencies;
1226
- for (const peer of peers && typeof peers === "object" ? Object.keys(peers) : []) {
1227
- if (walked.has(peer) || excluded(peer) || !detectedSet.has(peer)) continue;
1228
- const installed = dependencyOf(pkg, peer);
1229
- if (installed) reach(peer, installed);
1345
+ };
1346
+ for (const name of projectDeclared) {
1347
+ const member = memberByName.get(name);
1348
+ if (member) reachMember(member);
1349
+ }
1350
+ for (const target of reachedPaths) {
1351
+ const member = members.filter(({ dir }) => containsPath(dir, target)).sort((a, b) => b.dir.length - a.dir.length)[0];
1352
+ if (!member) continue;
1353
+ if (!reachedMembers.has(member.dir)) onReachedUndeclared?.(member.manifest.name, member.dir);
1354
+ reachMember(member);
1355
+ }
1356
+ for (const member of reachedMembers.values()) {
1357
+ const deps = member.manifest.dependencies;
1358
+ for (const dep of deps && typeof deps === "object" ? Object.keys(deps) : []) {
1359
+ if (walked.has(dep) || excluded(dep) || !detectedSet.has(dep)) continue;
1360
+ const installed = installedFrom(member.dir, dep);
1361
+ if (installed) reach(dep, installed);
1230
1362
  }
1231
1363
  }
1364
+ walk(true);
1232
1365
  return [...inClosure].sort();
1233
1366
  }
1234
1367
  //#endregion
@@ -1364,4 +1497,4 @@ function assertHotWorkerLoadsRunningVitest(running, workerEntry) {
1364
1497
  }, loadedRoot, "the hot runtime's worker", " Or set `hotRuntime: false`: per-file isolation loads Vitest through Vitest's own resolver, which reaches the running copy.");
1365
1498
  }
1366
1499
  //#endregion
1367
- export { validatePeerDependency as C, validateOptions as S, fsModuleCacheOnByDefault as _, runningVite as a, installedExpoVersion as b, detectEngine as c, findNativeInlineConflicts as d, findNativeOwnershipConflict as f, fsModuleCacheKey as g, packageDirOf as h, ownVitestPackage as i, resolveTransformPreset as l, containsPath as m, assertHotWorkerLoadsRunningVitest as n, usesVitePlus as o, formatNativeOwnershipManifest as p, installedViteVersion as r, detectEcosystemPackages as s, assertHostResolvesRunningVitest as t, createNativeOwnershipPolicy as u, shouldDefaultFsModuleCache as v, warnUnknownOptions as w, unsupportedExpoSdkMessage as x, PEER_REQUIREMENTS as y };
1500
+ export { unsupportedExpoSdkMessage as C, warnUnknownOptions as E, installedExpoVersion as S, validatePeerDependency as T, packageDirOf as _, runningVite as a, shouldDefaultFsModuleCache as b, detectEngine as c, findNativeInlineConflicts as d, findNativeOwnershipConflict as f, memoizePackageDirOf as g, dependencyDirOf as h, ownVitestPackage as i, resolveTransformPreset as l, containsPath as m, assertHotWorkerLoadsRunningVitest as n, usesVitePlus as o, formatNativeOwnershipManifest as p, installedViteVersion as r, detectEcosystemPackages as s, assertHostResolvesRunningVitest as t, createNativeOwnershipPolicy as u, fsModuleCacheKey as v, validateOptions as w, PEER_REQUIREMENTS as x, fsModuleCacheOnByDefault as y };
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { n as VitestNativeTypeError, t as VitestNativeError } from "./errors-CxoBUfVJ.mjs";
2
- import { C as validatePeerDependency, S as validateOptions, a as runningVite, b as installedExpoVersion, c as detectEngine, d as findNativeInlineConflicts, f as findNativeOwnershipConflict, g as fsModuleCacheKey, h as packageDirOf, i as ownVitestPackage, m as containsPath, n as assertHotWorkerLoadsRunningVitest, p as formatNativeOwnershipManifest, s as detectEcosystemPackages, t as assertHostResolvesRunningVitest, u as createNativeOwnershipPolicy, v as shouldDefaultFsModuleCache, w as warnUnknownOptions, x as unsupportedExpoSdkMessage, y as PEER_REQUIREMENTS } from "./host-C3wt9zUE.mjs";
2
+ import { C as unsupportedExpoSdkMessage, E as warnUnknownOptions, S as installedExpoVersion, T as validatePeerDependency, _ as packageDirOf, a as runningVite, b as shouldDefaultFsModuleCache, c as detectEngine, d as findNativeInlineConflicts, f as findNativeOwnershipConflict, g as memoizePackageDirOf, h as dependencyDirOf, i as ownVitestPackage, m as containsPath, n as assertHotWorkerLoadsRunningVitest, p as formatNativeOwnershipManifest, s as detectEcosystemPackages, t as assertHostResolvesRunningVitest, u as createNativeOwnershipPolicy, v as fsModuleCacheKey, w as validateOptions, x as PEER_REQUIREMENTS } from "./host-B4fG_RZ8.mjs";
3
3
  import { n as presetFromModule } from "./preset-modules-Bt6k_Wdw.mjs";
4
4
  import { M as BUILT_IN_PRESET, t as presets_exports } from "./presets-DuXiUNAx.mjs";
5
5
  import { a as presetForInstalled, i as autoDetectedPresetApplies, n as DEFAULT_ASSET_EXTS, r as PRESET_MODULES, t as AUTO_DETECT_PRESETS } from "./preset-map-L1-vD19T.mjs";
@@ -301,6 +301,7 @@ const SKIPPED_DIRS = /* @__PURE__ */ new Set([
301
301
  ]);
302
302
  /** Modules vitest-native implements at the boundary, beyond React Native's own. */
303
303
  const BOUNDARY_NATIVE_MODULES = Object.freeze(["NitroModules"]);
304
+ Object.freeze(["EXDevLauncher"]);
304
305
  const CALL_RE = /TurboModuleRegistry\s*\.\s*(get|getEnforcing)\b/g;
305
306
  const NAMED_CALL_RE = /TurboModuleRegistry\s*\.\s*(get|getEnforcing)\s*(?:<[^()]*?>)?\s*\(\s*(['"])([^'"]+)\2/g;
306
307
  const NATIVE_MODULES_RE = /\bNativeModules\s*(?:\?\.|\.)\s*([A-Za-z_$][\w$]*)|\bNativeModules\s*(?:\?\.)?\s*\[\s*(['"])([^'"]+)\2\s*\]/g;
@@ -590,6 +591,36 @@ function testIncludeRoots(include, projectRoot) {
590
591
  return [...dirs];
591
592
  }
592
593
  /**
594
+ * The files `test.setupFiles` names, resolved as Vitest resolves them (from the run
595
+ * root: a package request first, then a path), in the spelling given and in the real
596
+ * path's spellings, since Vite reports a module by its real path.
597
+ *
598
+ * Vitest evaluates every setup file in Vite whatever `server.deps.external` says, so
599
+ * the ownership policy treats them as entries (see decideFile in native/ownership.mjs).
600
+ */
601
+ function setupEntryFiles(setupFiles, projectRoot) {
602
+ const list = Array.isArray(setupFiles) ? setupFiles : [setupFiles];
603
+ const req = createRequire(path.join(projectRoot, "package.json"));
604
+ const files = /* @__PURE__ */ new Set();
605
+ for (const entry of list) {
606
+ if (typeof entry !== "string" || entry === "") continue;
607
+ let file;
608
+ if (entry.startsWith("file:")) file = fileURLToPath(entry);
609
+ else if (path.isAbsolute(entry)) file = entry;
610
+ else try {
611
+ file = req.resolve(entry);
612
+ } catch {
613
+ file = path.resolve(projectRoot, entry);
614
+ }
615
+ files.add(path.resolve(file));
616
+ if (fs.existsSync(file)) {
617
+ files.add(fs.realpathSync(file));
618
+ files.add(fs.realpathSync.native(file));
619
+ }
620
+ }
621
+ return [...files];
622
+ }
623
+ /**
593
624
  * Where a glob stops being a literal path.
594
625
  *
595
626
  * `!`, `+` and `@` only introduce a pattern as part of an extglob — `@(a|b)` — and
@@ -1688,8 +1719,14 @@ function reactNative(options) {
1688
1719
  const includeRoots = testIncludeRoots(userConfig.test?.include, resolvedRoot);
1689
1720
  const userInline = userConfig.test?.server?.deps?.inline;
1690
1721
  const userInlinesEverything = userInline === true;
1691
- const ecosystem = detectEcosystemPackages([resolvedRoot, ...includeRoots], transformPkgs, includeRoots, neverTransform, nativePresetNames);
1692
- const linkedDetectedDirs = ecosystem.map((name) => packageDirOf(name, resolvedRoot)).filter((dir) => dir !== null && !/[\\/]node_modules[\\/]/.test(dir));
1722
+ const dirOf = memoizePackageDirOf();
1723
+ const ecosystem = detectEcosystemPackages([resolvedRoot, ...includeRoots], transformPkgs, includeRoots, neverTransform, nativePresetNames, memoizePackageDirOf(dependencyDirOf), {
1724
+ reachedPaths: requireAliases.entries.map(([, target]) => target).filter((target) => path.isAbsolute(target)),
1725
+ onReachedUndeclared: (name, dir) => {
1726
+ if (diagnostics) console.log(`[vitest-native] ${name} (${dir}) is reached through an alias (resolve.alias or tsconfig paths) but is not a dependency of this package. Its installed React Native dependencies are compiled as if it were declared; declaring it makes the dependency explicit.`);
1727
+ }
1728
+ });
1729
+ const linkedDetectedDirs = ecosystem.map((name) => dirOf(name, resolvedRoot)).filter((dir) => dir !== null && !/[\\/]node_modules[\\/]/.test(dir));
1693
1730
  const projectDirs = [...new Set([resolvedRoot, ...includeRoots].map((dir) => nearestPackageDir(dir)).filter((dir) => dir !== null))].filter((dir) => !linkedDetectedDirs.some((detected) => containsPath(dir, detected)));
1694
1731
  if (projectDirs.length > 0) fields.projectDirs = projectDirs;
1695
1732
  nativeOwnership = createNativeOwnershipPolicy({
@@ -1698,7 +1735,9 @@ function reactNative(options) {
1698
1735
  ecosystemPackages: ecosystem,
1699
1736
  runtimeTransformAugmentations: nativePresetNames.length > 0 ? ["preset-pass-through-modules"] : [],
1700
1737
  projectDirs,
1701
- serverDepsInlineAll: userInlinesEverything
1738
+ entryFiles: setupEntryFiles(userConfig.test?.setupFiles, resolvedRoot),
1739
+ serverDepsInlineAll: userInlinesEverything,
1740
+ packageDirOf: dirOf
1702
1741
  });
1703
1742
  assertInlineOwnership(userInline);
1704
1743
  const userTest = userConfig.test;
@@ -2,6 +2,7 @@
2
2
  // code, replaced with mocks. Everything ELSE in RN runs for real. Modules are
3
3
  // expressed as CJS source strings so both transform hooks (loader + require) can
4
4
  // serve them identically. Mirrors react-native/jest/setup.js's mock set.
5
+ import { EXPO_GO_ABSENT_MODULES } from "./native-modules.mjs";
5
6
 
6
7
  function parseVersion(version) {
7
8
  const [major = 0, minor = 0, patch = 0] = String(version || "0.0.0")
@@ -135,12 +136,17 @@ function turboStubSource(platform, version) {
135
136
  // the setup file installs the set and module mocks change during a test.
136
137
  // The plugin's \`nativeModules: 'permissive'\`: every name present, every member a
137
138
  // method, for suites written against that behaviour.
139
+ // A module the default runtime (Expo Go) lacks (EXPO_GO_ABSENT_MODULES,
140
+ // native/native-modules.mjs) is absent in every mode, unless the test mocks it.
138
141
  const __permissive = () => globalThis.__vitest_native_permissive_modules === true;
142
+ const __ABSENT = new Set(${JSON.stringify(EXPO_GO_ABSENT_MODULES)});
143
+ const isAbsent = (name) => getModuleMock(name) == null && __ABSENT.has(name);
139
144
  const isKnownModule = (name) =>
140
- __permissive() ||
141
145
  getModuleMock(name) != null ||
142
- Object.prototype.hasOwnProperty.call(__C, name) ||
143
- (globalThis.__vitest_native_known_modules?.has(name) ?? false);
146
+ (!__ABSENT.has(name) &&
147
+ (__permissive() ||
148
+ Object.prototype.hasOwnProperty.call(__C, name) ||
149
+ (globalThis.__vitest_native_known_modules?.has(name) ?? false)));
144
150
  // Native methods that return a Promise on the device (no callback arg). Without
145
151
  // this, real RN code doing \`NativeModule.canOpenURL(url).then(...)\` would crash
146
152
  // on \`undefined\`. Values are the no-native defaults.
@@ -266,8 +272,19 @@ export const BOUNDARY_SOURCES = {
266
272
  exports.get = (n) => getModuleMock(n) || (isKnownModule(n) ? turboStub(n) : null);
267
273
  // getEnforcing(): React Native throws for an absent module. Its callers cannot
268
274
  // run without one, so a stub stands in instead, and code that requires a native
269
- // module still runs without per-module setup.
270
- exports.getEnforcing = (n) => getModuleMock(n) || turboStub(n);
275
+ // module still runs without per-module setup. A module the default runtime lacks
276
+ // throws React Native's own error, as on a device.
277
+ exports.getEnforcing = (n) => {
278
+ const mock = getModuleMock(n);
279
+ if (mock) return mock;
280
+ if (isAbsent(n)) {
281
+ const missing =
282
+ "TurboModuleRegistry.getEnforcing(...): '" + n + "' could not be found. " +
283
+ "Verify that a module by this name is registered in the native binary.";
284
+ throw Object.assign(new Error(missing), { name: "Invariant Violation" });
285
+ }
286
+ return turboStub(n);
287
+ };
271
288
  `,
272
289
  "Libraries/BatchedBridge/NativeModules.js": (platform, version) => `
273
290
  ${turboStubSource(platform, version)}
@@ -4,6 +4,10 @@
4
4
  // The package's JavaScript is the package; only the native module it reaches with
5
5
  // requireNativeModule is substituted, in this order:
6
6
  //
7
+ // 0. Absent, when the default runtime (Expo Go) lacks it (EXPO_GO_ABSENT_MODULES,
8
+ // native-modules.mjs), as the React Native boundary answers it. A test's
9
+ // mockNativeModule() reaches expo-modules-core through TurboModuleRegistry, where it
10
+ // looks next.
7
11
  // 1. Absent, when an installed package only probes for it and nothing installed
8
12
  // defines it (expoAbsentModules): requireOptionalNativeModule returns null, as on a
9
13
  // device. Unless a package mock stands in for it.
@@ -24,6 +28,7 @@ import {
24
28
  expoModuleTableDescribesInstalledSdk,
25
29
  expoModuleTableMembers,
26
30
  } from "./expo-module-mocks.mjs";
31
+ import { EXPO_GO_ABSENT_MODULES } from "./native-modules.mjs";
27
32
 
28
33
  /**
29
34
  * @typedef {{ members: Record<string, unknown>, complete: boolean, listsConstants?: boolean }} ExpoNativeModuleSeed
@@ -42,8 +47,9 @@ export function createExpoNativeModuleResolver({ projectRoot, cacheDir, mockFn }
42
47
  // Expo module pays nothing.
43
48
  let absent;
44
49
  return {
45
- /** Whether the module exists (layer 1). */
50
+ /** Whether the module exists (layers 0 and 1). */
46
51
  present(name) {
52
+ if (EXPO_GO_ABSENT_MODULES.includes(name)) return false;
47
53
  absent ??= expoAbsentModules(projectRoot, cacheDir());
48
54
  return !absent.has(name) || expoModuleMockIndex(projectRoot).has(name);
49
55
  },
@@ -129,7 +129,12 @@ function installExpoGlobal(g) {
129
129
  }
130
130
  // NativeModule / SharedObject / SharedRef extend EventEmitter in expo's runtime.
131
131
  class NativeModule extends EventEmitter {}
132
- class SharedObject extends EventEmitter {}
132
+ // A shared object is released when its owner is done with it; expo-modules-core's
133
+ // `useReleasingSharedObject` hooks (expo-video, expo-audio, expo-image) call it from
134
+ // the effect cleanup, so without it every unmount threw.
135
+ class SharedObject extends EventEmitter {
136
+ release() {}
137
+ }
133
138
  class SharedRef extends SharedObject {}
134
139
 
135
140
  // `globalThis.expo.modules` is the native-module registry expo libs read via
@@ -382,8 +387,17 @@ export function installErrorUtils(projectRoot) {
382
387
  *
383
388
  * Resolved from the project, so this is the module `expo`'s entry later finds in
384
389
  * the require cache rather than a second copy. Silent when `expo` is not installed.
390
+ *
391
+ * Installed only when Node compiles `expo` for the project (`nodeCompiles`, the require
392
+ * hooks' own rule: a declared or detected package, or one named in `transform`).
393
+ * jest-expo installs it only for projects that use its preset. SDK 58 publishes the
394
+ * runtime as ES module syntax with Metro `require` calls in a package without
395
+ * `"type": "module"`, so Node runs it only compiled; where `expo` merely
396
+ * resolves (a hoisted workspace with an Expo app beside this package, or a library whose
397
+ * expo-* devDependencies pull it in as a peer) it is not this project's, and loading it
398
+ * raw failed every test file.
385
399
  */
386
- export function installExpoRuntime(projectRoot) {
400
+ export function installExpoRuntime(projectRoot, nodeCompiles) {
387
401
  let winter;
388
402
  try {
389
403
  const req = createRequire(path.join(projectRoot, "package.json"));
@@ -401,6 +415,10 @@ export function installExpoRuntime(projectRoot) {
401
415
  } catch {
402
416
  return;
403
417
  }
418
+ // Outside the try: a missing rule is a wiring fault, never a project's state, and
419
+ // skipping the runtime silently would hide it behind tests that pass without Expo's
420
+ // globals.
421
+ if (!nodeCompiles(winter)) return;
404
422
  const KEEP_FETCH = "EXPO_PUBLIC_USE_RN_FETCH";
405
423
  const projectSet = Object.hasOwn(process.env, KEEP_FETCH);
406
424
  if (!projectSet) process.env[KEEP_FETCH] = "1";
@@ -192,12 +192,11 @@ export function installRequireHooks(
192
192
  // pin the boot-time env list forever, and the divergence is hot-only because
193
193
  // under stock the setup file IS the first caller. Rebuild the matcher when
194
194
  // a later caller brings a different list; hook layers are never stacked.
195
- globalThis.__vitest_native_require_hooks_update?.({
195
+ return globalThis.__vitest_native_require_hooks_update?.({
196
196
  transformPkgs,
197
197
  assetExts,
198
198
  sourceExts,
199
199
  });
200
- return;
201
200
  }
202
201
  globalThis.__vitest_native_require_hooks_installed = true;
203
202
 
@@ -241,6 +240,11 @@ export function installRequireHooks(
241
240
  });
242
241
  let isExtra = ownership.matchesNodeTransformedFile;
243
242
  let isExtraKey = JSON.stringify(transformPkgs);
243
+ // Whether these hooks compile a package file for the project, read at call time so a
244
+ // rebuilt matcher (below) answers. Returned by every call, the first and the later ones
245
+ // the updater serves: Expo's runtime is installed only for files this says yes to
246
+ // (globals.mjs installExpoRuntime), one rule for what Node compiles.
247
+ const compiles = (file) => isExtra(String(file).replace(/\\/g, "/"));
244
248
  // A field left out keeps its current value (tests-native/resolution-memo.test.ts
245
249
  // changes the source extensions alone, and puts them back).
246
250
  let activeAssetExts = assetExts;
@@ -255,10 +259,11 @@ export function installRequireHooks(
255
259
  assetExtSet = new Set(activeAssetExts.map((e) => String(e).replace(/^\./, "").toLowerCase()));
256
260
  installAssetExtensions(activeAssetExts);
257
261
  const key = JSON.stringify(pkgs);
258
- if (key === isExtraKey) return;
262
+ if (key === isExtraKey) return compiles;
259
263
  isExtraKey = key;
260
264
  ownership = createNativeOwnershipPolicy({ ...ownershipBase, runtimeTransforms: pkgs });
261
265
  isExtra = ownership.matchesNodeTransformedFile;
266
+ return compiles;
262
267
  };
263
268
 
264
269
  // Preset redirect (CJS): when an externalized third-party module require()s a
@@ -633,4 +638,5 @@ export function installRequireHooks(
633
638
  return mod._compile(transformRN(filename, undefined, projectRoot, platform), filename);
634
639
  };
635
640
  }
641
+ return compiles;
636
642
  }
@@ -12,18 +12,34 @@ export declare function installedPackageDirOf(name: string, projectRoot: string)
12
12
 
13
13
  /** The on-disk directory a package resolves to from `projectRoot`, or null. */
14
14
  export declare function packageDirOf(name: string, fromDir: string): string | null;
15
+ /** A dependency the engine may detect: installed, or resolvable through `<name>/package.json`. */
16
+ export declare function dependencyDirOf(name: string, fromDir: string): string | null;
17
+
18
+ /** How a package's directory is found from a directory: `packageDirOf`, `dependencyDirOf`, or a memoized copy. */
19
+ export type PackageDirOf = (name: string, fromDir: string) => string | null;
20
+
21
+ /**
22
+ * `resolve` (default `packageDirOf`) with each answer kept for the life of the returned
23
+ * function, keyed by the resolved `fromDir` and the package name.
24
+ */
25
+ export declare function memoizePackageDirOf(resolve?: PackageDirOf): PackageDirOf;
15
26
 
16
27
  /**
17
28
  * The patterns identifying one package's files: under `node_modules/<name>/`, and
18
29
  * inside the directory it resolves to. The second is omitted when that directory
19
30
  * contains `projectRoot` — the project is not one of its own dependencies.
20
31
  */
21
- export declare function packagePatterns(name: string, projectRoot?: string): RegExp[];
32
+ export declare function packagePatterns(
33
+ name: string,
34
+ projectRoot?: string,
35
+ dirOf?: PackageDirOf,
36
+ ): RegExp[];
22
37
 
23
38
  /** A predicate over `packagePatterns` for every named package. */
24
39
  export declare function buildPkgMatcher(
25
40
  pkgs: string[] | undefined,
26
41
  projectRoot?: string,
42
+ dirOf?: PackageDirOf,
27
43
  ): (file: string) => boolean;
28
44
 
29
45
  /** The bare package name of an import specifier. */
@@ -114,10 +114,21 @@ export function containsPath(dir, target) {
114
114
  * point — see buildPkgMatcher.
115
115
  */
116
116
  export function packageDirOf(name, fromDir) {
117
+ return findPackageDir(name, fromDir, false);
118
+ }
119
+
120
+ /** packageDirOf, or with `installedOnly` dependencyDirOf. */
121
+ function findPackageDir(name, fromDir, installedOnly) {
117
122
  const req = createRequire(path.join(fromDir, "package.json"));
118
123
  try {
119
124
  return canonicalDir(path.dirname(req.resolve(`${name}/package.json`)));
120
125
  } catch {}
126
+ const found = findUnexportedPackageDir(name, req);
127
+ return installedOnly && found !== null && !NODE_MODULES_PATH.test(found) ? null : found;
128
+ }
129
+
130
+ /** The steps after `<name>/package.json` fails: the lookup paths, then the entry. */
131
+ function findUnexportedPackageDir(name, req) {
121
132
  for (const lookup of req.resolve.paths(name) ?? []) {
122
133
  const candidate = path.join(lookup, ...name.split("/"));
123
134
  if (fs.existsSync(path.join(candidate, "package.json"))) return canonicalDir(candidate);
@@ -140,6 +151,62 @@ export function packageDirOf(name, fromDir) {
140
151
  }
141
152
  }
142
153
 
154
+ /**
155
+ * The directory of a dependency the engine may DETECT (ecosystem detection), or null.
156
+ *
157
+ * A package whose `exports` map leaves out `./package.json` is found the way
158
+ * packageDirOf finds it only when it is installed: its real path lies inside a node_modules directory, as
159
+ * expo-symbols 57's does (#406). A workspace member, whose real path lies outside every
160
+ * node_modules, is found only when `<name>/package.json` resolves, which is the rule
161
+ * 0.14.0-rc.10 and earlier applied to every package.
162
+ *
163
+ * Why the two differ: detecting a workspace member makes it Node-owned, so `vi.mock`
164
+ * from a test no longer reaches its internal imports and any of its files that imports
165
+ * `vitest` fails. Widening detection to every workspace member whose exports omit
166
+ * `./package.json` changed that silently for libraries that ran in Vite before. Which
167
+ * owner a workspace member should have is the ownership track's decision (A3, the
168
+ * ownership predicate; A6, the fix for `vi.mock` reaching a Node-owned package's own
169
+ * imports, #322), not a side effect of how its manifest is found. Rejected: applying
170
+ * #406 to workspace members as well (the silent change above), and reverting #406
171
+ * (expo-symbols then runs uncompiled again).
172
+ */
173
+ export function dependencyDirOf(name, fromDir) {
174
+ return findPackageDir(name, fromDir, true);
175
+ }
176
+
177
+ /**
178
+ * `packageDirOf` (or `resolve`, such as dependencyDirOf) with each answer kept for the
179
+ * life of the returned function.
180
+ *
181
+ * One config evaluation asks for the same directories several times: detection, the
182
+ * linked-package check, and every pattern list and matcher the ownership policy
183
+ * builds. On an Expo project that is hundreds of packages, each a handful of
184
+ * resolutions and real-path calls, repeated three to five times over.
185
+ *
186
+ * Nothing here is module state, so this file stays pure (see the header): the caller
187
+ * owns the cache and decides how long it lives. The plugin makes one per lookup
188
+ * function per config evaluation, and Vitest evaluates the config afresh when it
189
+ * restarts in watch mode, so a package installed mid-session is seen on the next
190
+ * restart, as before.
191
+ *
192
+ * Keyed by `fromDir` as resolved, not by its real path. The answer is already in
193
+ * Node's real-path spelling (canonicalDir); it is the QUESTION that depends on the
194
+ * spelling, because Node's lookup paths are built from `fromDir` as written, and a
195
+ * symlinked spelling walks different parent node_modules than the real one. Two
196
+ * spellings of one directory therefore cost two lookups, but can never be handed each
197
+ * other's answer.
198
+ */
199
+ export function memoizePackageDirOf(resolve = packageDirOf) {
200
+ const dirs = new Map();
201
+ return (name, fromDir) => {
202
+ const key = `${path.resolve(fromDir)}\0${name}`;
203
+ if (dirs.has(key)) return dirs.get(key);
204
+ const dir = resolve(name, fromDir);
205
+ dirs.set(key, dir);
206
+ return dir;
207
+ };
208
+ }
209
+
143
210
  /**
144
211
  * The patterns identifying one package's files. THE rule; everything else composes it.
145
212
  *
@@ -164,12 +231,13 @@ export function packageDirOf(name, fromDir) {
164
231
  * test file's `import { it } from 'vitest'` becomes `require('vitest')` and throws.
165
232
  *
166
233
  * `projectRoot` is optional; without it only the `node_modules` rule applies, since
167
- * there is nothing to resolve against.
234
+ * there is nothing to resolve against. `dirOf` is how the directory is found:
235
+ * `packageDirOf`, or a memoized copy of it (memoizePackageDirOf).
168
236
  */
169
- export function packagePatterns(name, projectRoot) {
237
+ export function packagePatterns(name, projectRoot, dirOf = packageDirOf) {
170
238
  const patterns = [new RegExp(`[\\\\/]node_modules[\\\\/]${escapeRe(name)}[\\\\/]`)];
171
239
  if (!projectRoot) return patterns;
172
- const dir = packageDirOf(name, projectRoot);
240
+ const dir = dirOf(name, projectRoot);
173
241
  if (dir && !containsPath(dir, projectRoot)) {
174
242
  patterns.push(new RegExp(`^${escapeRe(toPosix(dir).replace(/\/$/, ""))}[\\\\/]`));
175
243
  }
@@ -184,8 +252,8 @@ export function packagePatterns(name, projectRoot) {
184
252
  * slashes (the form Vitest presents module ids in) while callers here pass whatever
185
253
  * Node handed them, which on Windows is backslashes.
186
254
  */
187
- export function buildPkgMatcher(pkgs, projectRoot) {
188
- const patterns = (pkgs || []).flatMap((name) => packagePatterns(name, projectRoot));
255
+ export function buildPkgMatcher(pkgs, projectRoot, dirOf = packageDirOf) {
256
+ const patterns = (pkgs || []).flatMap((name) => packagePatterns(name, projectRoot, dirOf));
189
257
  return (file) => {
190
258
  const norm = toPosix(file);
191
259
  return patterns.some((re) => re.test(norm));
@@ -13,3 +13,5 @@ export declare function reactNativeRootFor(projectRoot: string): string | null;
13
13
  export declare function knownNativeModulesFor(projectRoot: string): string[];
14
14
  export declare function nativeModuleSpecsFor(projectRoot: string): Record<string, string[]>;
15
15
  export declare function installKnownNativeModules(projectRoot: string): void;
16
+ export declare const DEV_LAUNCHER_MODULE: "EXDevLauncher";
17
+ export declare const EXPO_GO_ABSENT_MODULES: readonly string[];
@@ -40,6 +40,24 @@ export const BOUNDARY_NATIVE_MODULES = Object.freeze([
40
40
  "NitroModules",
41
41
  ]);
42
42
 
43
+ // The default runtime models Expo Go, as jest-expo does, and Expo Go registers no dev
44
+ // launcher: `EXDevLauncher` is registered only by expo-dev-launcher, in a development
45
+ // build. Expo reads the module as its development-client signal: expo sets
46
+ // `IS_RUNNING_IN_DEV_CLIENT = !!NativeModules.EXDevLauncher` (expo/src/Expo.fx.tsx), and
47
+ // expo-constants parses `NativeModules.EXDevLauncher.manifestString` whenever the module
48
+ // is present (expo-constants/src/Constants.ts). tests/expo-dev-launcher-fact.test.ts
49
+ // reads that source again, so an Expo release that changes either read fails by name.
50
+ /** The native module only expo-dev-launcher registers, in a development build. */
51
+ export const DEV_LAUNCHER_MODULE = "EXDevLauncher";
52
+
53
+ /**
54
+ * Modules the default runtime (Expo Go) does not have. Each is absent from every lookup
55
+ * (`NativeModules`, `TurboModuleRegistry`, `globalThis.expo.modules`) in every mode,
56
+ * `nativeModules: 'permissive'` included, unless a test registers it with
57
+ * mockNativeModule().
58
+ */
59
+ export const EXPO_GO_ABSENT_MODULES = Object.freeze([DEV_LAUNCHER_MODULE]);
60
+
43
61
  const CALL_RE = /TurboModuleRegistry\s*\.\s*(get|getEnforcing)\b/g;
44
62
  // `TurboModuleRegistry.get<Spec>('Name')`, including the multi-line form the
45
63
  // formatter produces for long names. The type argument never contains a paren.
@@ -29,6 +29,7 @@ export interface NativeOwnershipRule {
29
29
  readonly packages?: readonly string[];
30
30
  readonly roots?: readonly string[];
31
31
  readonly patterns?: readonly string[];
32
+ readonly files?: readonly string[];
32
33
  }
33
34
 
34
35
  export interface NativeOwnershipManifest {
@@ -36,6 +37,8 @@ export interface NativeOwnershipManifest {
36
37
  readonly enforcement: "enforced" | "overridden-by-inline-all";
37
38
  readonly projectRoot: string;
38
39
  readonly projectDirs: readonly string[];
40
+ /** The project's `test.setupFiles`: Vite-owned entries wherever they live outside node_modules. */
41
+ readonly entryFiles?: readonly string[];
39
42
  readonly reactNativeRoots: readonly string[];
40
43
  readonly nodeTransformPackages: readonly string[];
41
44
  readonly runtimeTransformAugmentations: readonly string[];
@@ -56,6 +59,8 @@ export interface NativeOwnershipPolicy {
56
59
  readonly reactNativePathFor: (file: string) => string | null;
57
60
  readonly decideFile: (file: string) => NativeOwnershipDecision;
58
61
  readonly manifest: () => NativeOwnershipManifest;
62
+ /** The directory a package resolves to from the project root, as the patterns used it. */
63
+ readonly packageDirOf: (name: string) => string | null;
59
64
  }
60
65
 
61
66
  export interface NativeOwnershipConflict {
@@ -74,7 +79,11 @@ export interface NativeOwnershipOptions {
74
79
  runtimeTransformAugmentations?: string[];
75
80
  projectDirs?: string[];
76
81
  reactNativeRoots?: string[];
82
+ /** Files Vitest runs as entries without a test-file name: the project's `test.setupFiles`. */
83
+ entryFiles?: string[];
77
84
  serverDepsInlineAll?: boolean;
85
+ /** How each package's directory is found; defaults to `packageDirOf` (match.mjs). */
86
+ packageDirOf?: (name: string, fromDir: string) => string | null;
78
87
  }
79
88
 
80
89
  export declare const TEST_ENTRY_PATTERNS: readonly RegExp[];
@@ -13,13 +13,18 @@ import {
13
13
  buildPkgMatcher,
14
14
  containsPath,
15
15
  installedPackageDirOf,
16
- packageDirOf,
16
+ memoizePackageDirOf,
17
17
  packagePatterns,
18
18
  } from "./match.mjs";
19
19
 
20
20
  const OUTSIDE_NODE_MODULES = String.raw`^(?!.*[\\/]node_modules[\\/])`;
21
21
 
22
- /** Files Vitest may execute as entries. They always belong to Vite. */
22
+ /**
23
+ * Files Vitest may execute as entries. They always belong to Vite.
24
+ *
25
+ * Test files are recognised by name. A setup file has no naming convention, so the
26
+ * project's `test.setupFiles` are passed in as `entryFiles` instead (see decideFile).
27
+ */
23
28
  export const TEST_ENTRY_PATTERNS = Object.freeze([
24
29
  new RegExp(String.raw`${OUTSIDE_NODE_MODULES}.*\.(?:test|spec)\.[cm]?[jt]sx?$`),
25
30
  new RegExp(String.raw`${OUTSIDE_NODE_MODULES}.*[\\/]__tests__[\\/].*\.[cm]?[jt]sx?$`),
@@ -90,6 +95,11 @@ function decision(owner, format, transform, reset, reasons, evidence) {
90
95
  * `ecosystemPackages` is the detected RN dependency closure.
91
96
  * `runtimeTransforms` is for workers reconstructing the already-combined list from
92
97
  * serialized setup data; config-time callers normally leave it empty.
98
+ *
99
+ * `packageDirOf` finds each package's directory. Each package is looked up once per
100
+ * policy whatever is passed (the patterns and every matcher share the answers); a
101
+ * caller that has already resolved the same packages from the same root passes its
102
+ * own memoized lookup (memoizePackageDirOf) so they are not resolved again.
93
103
  */
94
104
  export function createNativeOwnershipPolicy({
95
105
  projectRoot = process.cwd(),
@@ -99,8 +109,11 @@ export function createNativeOwnershipPolicy({
99
109
  runtimeTransformAugmentations = [],
100
110
  projectDirs = [],
101
111
  reactNativeRoots = [],
112
+ entryFiles = [],
102
113
  serverDepsInlineAll = false,
114
+ packageDirOf,
103
115
  } = {}) {
116
+ const dirOf = memoizePackageDirOf(packageDirOf);
104
117
  const enforcement = serverDepsInlineAll ? "overridden-by-inline-all" : "enforced";
105
118
  const root = path.resolve(projectRoot);
106
119
  const explicit = unique(explicitTransforms);
@@ -148,19 +161,65 @@ export function createNativeOwnershipPolicy({
148
161
  const externalPatterns = [
149
162
  REACT_NATIVE_PATH,
150
163
  ...reactNativeRootPatterns,
151
- ...nodeTransformPackages.flatMap((name) => packagePatterns(name, root)),
164
+ ...nodeTransformPackages.flatMap((name) => packagePatterns(name, root, dirOf)),
152
165
  ];
153
- const matchesNodeTransformedFile = buildPkgMatcher(nodeTransformPackages, root);
154
- const explicitMatcher = buildPkgMatcher(explicit, root);
155
- const ecosystemMatcher = buildPkgMatcher(ecosystem, root);
156
- const runtimeMatcher = buildPkgMatcher(runtime, root);
166
+ const matchesNodeTransformedFile = buildPkgMatcher(nodeTransformPackages, root, dirOf);
167
+ const explicitMatcher = buildPkgMatcher(explicit, root, dirOf);
168
+ const ecosystemMatcher = buildPkgMatcher(ecosystem, root, dirOf);
169
+ const runtimeMatcher = buildPkgMatcher(runtime, root, dirOf);
157
170
  const normalizedProjectDirs = Object.freeze(unique(projectDirs).map((dir) => path.resolve(dir)));
171
+ const normalizedEntryFiles = Object.freeze(unique(entryFiles).map((file) => path.resolve(file)));
172
+ const entryKey = (file) => {
173
+ const resolved = path.resolve(file);
174
+ return process.platform === "win32" ? resolved.toLowerCase() : resolved;
175
+ };
176
+ const entryKeys = new Set(normalizedEntryFiles.map(entryKey));
158
177
 
159
178
  const decideFile = (rawFile) => {
160
179
  const file = cleanFileId(rawFile);
161
180
  if (TEST_ENTRY_PATTERNS.some((pattern) => pattern.test(file))) {
162
181
  return decision("vite", "source", "vite", "per-file", ["test-entry"], [file]);
163
182
  }
183
+ // A setup file is an entry too: Vitest inlines `test.setupFiles` ahead of every
184
+ // `server.deps.external` pattern (its `inlineFiles`), so Vite evaluates one wherever
185
+ // it lives. The policy has to say the same, or a setup file inside a Node-owned
186
+ // package is refused as MODULE_OWNER_CONFLICT before it runs. The case that showed
187
+ // it: an app listing a sibling workspace library's own `vitest.setup.ts`, where the
188
+ // library declares react-native and is therefore Node-owned (ADR-0004 rule 7).
189
+ //
190
+ // Only the entry changes owner. What it imports is decided file by file, so the
191
+ // library's source stays with Node and the test and the setup file share its one
192
+ // instance. Two broader answers were rejected:
193
+ // - Leaving every workspace package (real path outside node_modules) to Vite.
194
+ // Detected workspace members are Node-owned on purpose (which members are
195
+ // detected is dependencyDirOf's rule, in match.mjs): Vite's
196
+ // compile changes class fields, EXPO_OS and the worklet plugin, and a member that
197
+ // an installed package also requires loads twice when Vite owns it.
198
+ // - Not detecting a package that holds a setup file. A setup file says nothing
199
+ // about how the package's source must be compiled, and it would give one library
200
+ // two owners depending on which app's config runs it.
201
+ // As with test files, a setup file under node_modules is left to the rules below.
202
+ //
203
+ // Only Vite's transform hook (plugin.ts) judges a setup file, so only the main
204
+ // process passes `entryFiles`. Workers judge Node's loads by package matchers;
205
+ // their one call to decideFile is the project-source resolution warning
206
+ // (hooks.mjs checkProjectSourceResolvedByNode), which has no use for entry files,
207
+ // since Vitest's runner imports a setup file through Vite. The manifest carries the
208
+ // list for diagnostics.
209
+ if (
210
+ entryKeys.size > 0 &&
211
+ !NODE_MODULES_PATH.test(file) &&
212
+ entryKeys.has(entryKey(cleanRawFileId(rawFile)))
213
+ ) {
214
+ return decision(
215
+ "vite",
216
+ "source",
217
+ "vite",
218
+ "per-file",
219
+ ["test-entry"],
220
+ ["test.setupFiles", file],
221
+ );
222
+ }
164
223
  const runtimeResident = isRuntimeResidentFile(file);
165
224
  const testRuntimeResident = isTestRuntimeResidentFile(file);
166
225
  if (isReactNativeCore(file, rawFile)) {
@@ -269,6 +328,7 @@ export function createNativeOwnershipPolicy({
269
328
  enforcement,
270
329
  projectRoot: root,
271
330
  projectDirs: normalizedProjectDirs,
331
+ entryFiles: normalizedEntryFiles,
272
332
  reactNativeRoots: normalizedReactNativeRoots,
273
333
  nodeTransformPackages,
274
334
  runtimeTransformAugmentations: runtimeAugmentations,
@@ -320,6 +380,7 @@ export function createNativeOwnershipPolicy({
320
380
  reset: "per-file",
321
381
  reason: "test-entry",
322
382
  patterns: Object.freeze(TEST_ENTRY_PATTERNS.map(String)),
383
+ files: normalizedEntryFiles,
323
384
  }),
324
385
  Object.freeze({
325
386
  effect: "reset-if-external",
@@ -347,6 +408,7 @@ export function createNativeOwnershipPolicy({
347
408
  reactNativePathFor,
348
409
  decideFile,
349
410
  manifest,
411
+ packageDirOf: (name) => dirOf(name, root),
350
412
  });
351
413
  }
352
414
 
@@ -387,7 +449,7 @@ export function findNativeInlineConflicts(policy, inline) {
387
449
  `/project/node_modules/${concrete}/index.js`,
388
450
  `C:\\project\\node_modules\\${concrete.replaceAll("/", "\\")}\\index.js`,
389
451
  ];
390
- const dir = name.includes("*") ? null : packageDirOf(name, policy.projectRoot);
452
+ const dir = name.includes("*") ? null : policy.packageDirOf(name);
391
453
  if (dir) probes.push(`${normalizeFile(dir).replace(/\/$/, "")}/index.js`);
392
454
  const hit = patterns.some((pattern) => {
393
455
  if (typeof pattern === "string") {
@@ -422,6 +484,15 @@ export function parseNativeOwnershipManifest(raw) {
422
484
  return null;
423
485
  }
424
486
  if (typeof value.projectRoot !== "string") return null;
487
+ if (
488
+ value.entryFiles !== undefined &&
489
+ !(
490
+ Array.isArray(value.entryFiles) &&
491
+ value.entryFiles.every((entry) => typeof entry === "string")
492
+ )
493
+ ) {
494
+ return null;
495
+ }
425
496
  for (const key of [
426
497
  "projectDirs",
427
498
  "reactNativeRoots",
@@ -458,7 +529,9 @@ export function formatNativeOwnershipManifest(input) {
458
529
  const list = (values) => (values.length > 0 ? values.join(", ") : "(none)");
459
530
  const lines = [
460
531
  `project: ${manifest.projectRoot}`,
461
- `Vite / reset per file: ${list(manifest.projectDirs)} plus test entries`,
532
+ `Vite / reset per file: ${list(manifest.projectDirs)} plus test entries${
533
+ manifest.entryFiles?.length ? ` and setup files (${manifest.entryFiles.join(", ")})` : ""
534
+ }`,
462
535
  `Node / worker resident: react-native, @react-native/* (${list(manifest.reactNativeRoots)})`,
463
536
  `Node / native transform / reset per file: ${list(manifest.nodeTransformPackages)}`,
464
537
  `worker-time transform augmentations: ${list(manifest.runtimeTransformAugmentations)}`,
@@ -273,7 +273,7 @@ if (runContext.registry) {
273
273
  }
274
274
  // The NitroModules boundary's install() calls this (see nitro.mjs).
275
275
  globalThis.__vitest_native_install_nitro = () => installNitroProxy(projectRoot);
276
- installRequireHooks(
276
+ const nodeCompiles = installRequireHooks(
277
277
  projectRoot,
278
278
  nodeTransformPkgs,
279
279
  platform,
@@ -356,7 +356,7 @@ g.__vitest_native_expo_modules = createExpoNativeModuleResolver({
356
356
  mockFn: (implementation) => vi.fn(implementation),
357
357
  });
358
358
  // Before the project's setup files run, as jest-expo does (see globals.mjs).
359
- installExpoRuntime(projectRoot);
359
+ installExpoRuntime(projectRoot, nodeCompiles);
360
360
  const initialDimensions = {
361
361
  window: { ...RN.Dimensions.get("window") },
362
362
  screen: { ...RN.Dimensions.get("screen") },
@@ -571,8 +571,8 @@ const now = performance.now.bind(performance);
571
571
  // signal[0]: 0 while a request is outstanding, 1 answered, 2 the thread ended.
572
572
  // signal[1]: 1 once the thread has ended.
573
573
  let toolchain = null;
574
- // Internal: the deadline, the worker file and its resource limits, for tests that end a
575
- // thread on purpose (_setToolchainOptions).
574
+ // Internal: the deadline, its clock, the worker file and its resource limits, for tests
575
+ // that end a thread on purpose (_setToolchainOptions).
576
576
  let toolchainOptions = {};
577
577
  // The registry compiler's child process runs no test code, so Babel runs there on the
578
578
  // one thread, as before: that process's heap bound and its out-of-memory retry
@@ -585,8 +585,10 @@ export function compileOnThisThread() {
585
585
  }
586
586
 
587
587
  /**
588
- * Internal test seam: `{ deadlineMs, workerUrl, resourceLimits }` (deadlineMs replaces the
589
- * base, and source still adds to it); stops the current thread.
588
+ * Internal test seam: `{ deadlineMs, workerUrl, resourceLimits, now }` (deadlineMs replaces
589
+ * the base, and source still adds to it; `now` replaces the clock the deadline is read
590
+ * on, so a test can order the deadline after an event instead of racing elapsed time);
591
+ * stops the current thread.
590
592
  */
591
593
  export function _setToolchainOptions(options = {}) {
592
594
  toolchain?.worker.terminate();
@@ -646,11 +648,12 @@ function callToolchain(request) {
646
648
  if (toolchain === null || atomicsLoad(toolchain.signal, 1) === 1) toolchain = startToolchain();
647
649
  const { port, signal, worker } = toolchain;
648
650
  const deadlineMs = toolchainDeadlineMs(request, toolchainOptions.deadlineMs);
651
+ const clock = toolchainOptions.now ?? now;
649
652
  atomicsStore(signal, 0, 0);
650
653
  port.postMessage(request);
651
- const deadline = now() + deadlineMs;
654
+ const deadline = clock() + deadlineMs;
652
655
  for (;;) {
653
- const left = deadline - now();
656
+ const left = deadline - clock();
654
657
  if (left <= 0) break;
655
658
  if (atomicsWait(signal, 0, 0, Math.min(left, 1000)) !== "timed-out") break;
656
659
  if (atomicsLoad(signal, 1) === 1) break;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "vitest-native",
3
- "version": "0.14.0-rc.11",
3
+ "version": "0.14.0-rc.12",
4
4
  "description": "Run real React Native tests under Vitest. One install, zero config.",
5
5
  "keywords": [
6
6
  "expo",
@@ -119,13 +119,14 @@
119
119
  "scripts": {
120
120
  "build": "bunx --bun tsdown && node scripts/copy-static-types.mjs",
121
121
  "test": "vitest run",
122
- "test:native": "vitest run --config tests-native/vitest.config.mts && vitest run --config tests-native/vitest.regex-alias.config.mts && vitest run --config tests-native/vitest.partial-mock-external.config.mts && vitest run --config tests-native/tsconfig-paths/vitest.config.mts && bun run test:native:preset-modules && bun run test:native:shared-root && bun run test:native:context && bun run test:native:one-instance && bun run test:native:rntl-timers && bun run test:native:no-globals",
122
+ "test:native": "vitest run --config tests-native/vitest.config.mts && vitest run --config tests-native/vitest.regex-alias.config.mts && vitest run --config tests-native/vitest.partial-mock-external.config.mts && vitest run --config tests-native/tsconfig-paths/vitest.config.mts && bun run test:native:preset-modules && bun run test:native:shared-root && bun run test:native:context && bun run test:native:one-instance && bun run test:native:rntl-timers && bun run test:native:no-globals && bun run test:native:permissive",
123
123
  "test:native:one-instance": "vitest run --config tests-native/vitest.one-instance.config.mts --mode stock && vitest run --config tests-native/vitest.one-instance.config.mts --mode hot && vitest run --config tests-native/vitest.one-instance.config.mts --mode early && vitest run --config tests-native/vitest.one-instance.config.mts --mode jest-compat",
124
124
  "test:native:rntl-timers": "vitest run --config tests-native/vitest.rntl-timers.config.mts --mode stock && vitest run --config tests-native/vitest.rntl-timers.config.mts --mode hot && vitest run --config tests-native/vitest.rntl-timers.config.mts --mode setup-stock && vitest run --config tests-native/vitest.rntl-timers.config.mts --mode setup-hot",
125
125
  "test:native:context": "vitest run --config tests-native/vitest.context.config.mts && node --conditions=vn-probe node_modules/vitest/vitest.mjs run --config tests-native/vitest.context.config.mts --project threads",
126
126
  "test:native:no-globals": "vitest run --config tests-native/vitest.no-globals.config.mts --mode native && vitest run --config tests-native/vitest.no-globals.config.mts --mode hot && vitest run --config tests-native/vitest.no-globals.config.mts --mode noiso && vitest run --config tests-native/vitest.no-globals.config.mts --mode mock-noiso && vitest run --config tests-native/vitest.no-globals.config.mts --mode noiso-fakes-setup && vitest run --config tests-native/vitest.no-globals.config.mts --mode noiso-fakes-leak && vitest run --config tests-native/vitest.no-globals.config.mts --mode mock-noiso-fakes-setup && vitest run --config tests-native/vitest.no-globals.config.mts --mode mock-noiso-fakes-leak",
127
127
  "test:native:shared-root": "vitest run --config tests-native/vitest.shared-root.config.mts --mode stock && vitest run --config tests-native/vitest.shared-root.config.mts --mode hot && vitest run --config tests-native/vitest.shared-root-extends.config.mts",
128
128
  "test:native:preset-modules": "vitest run --config tests-native/vitest.custom-preset.config.mts --mode native && vitest run --config tests-native/vitest.custom-preset.config.mts --mode hot && vitest run --config tests-native/vitest.custom-preset.config.mts --mode mock",
129
+ "test:native:permissive": "vitest run --config tests-native/vitest.permissive.config.mts --mode stock && vitest run --config tests-native/vitest.permissive.config.mts --mode hot",
129
130
  "test:native:forks": "vitest run --config tests-native/vitest.forks.config.mts",
130
131
  "test:native:navigation": "vitest run --config tests-native/vitest.navigation.config.mts && vitest run --config tests-native/vitest.native-stack.config.mts",
131
132
  "test:native:android": "vitest run --config tests-native/vitest.android.config.mts",
@@ -143,6 +144,7 @@
143
144
  "format:check": "oxfmt --check src/ tests/ consumer-tests/ scripts/",
144
145
  "check-compat": "bun scripts/check-compat.ts",
145
146
  "check:size": "node scripts/check-package-size.mjs",
147
+ "check:structure": "node scripts/structural-scorecard.mjs",
146
148
  "check:exports": "node scripts/check-exports.mjs",
147
149
  "typecheck": "tsc --noEmit",
148
150
  "clean": "rm -rf dist",
@@ -176,6 +178,7 @@
176
178
  "@types/node": "25.9.9",
177
179
  "@types/react": "19.3.0",
178
180
  "@vitest/coverage-v8": "5.0.5",
181
+ "expo": "58.0.20",
179
182
  "expo-constants": "58.0.13",
180
183
  "expo-status-bar": "58.0.4",
181
184
  "ext-platform-lib": "file:./tests-native/fixtures/ext-platform-lib",