vitest-native 0.15.0 → 0.16.0-rc.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 (54) hide show
  1. package/dist/cli.mjs +177 -31
  2. package/dist/context.d.mts +6 -0
  3. package/dist/context.mjs +5 -0
  4. package/dist/errors.d.mts +5 -0
  5. package/dist/hang-watch.d.mts +2 -0
  6. package/dist/hang-watch.mjs +60 -3
  7. package/dist/{host-TAGjG56H.mjs → host-X6VHF-a4.mjs} +456 -15
  8. package/dist/{index-BpZ0E2eJ.d.mts → index-X3wuvaqa.d.mts} +25 -13
  9. package/dist/index.d.mts +3 -3
  10. package/dist/index.mjs +220 -117
  11. package/dist/jest-compat/jest-object.mjs +62 -17
  12. package/dist/jest-compat/node-registry.mjs +496 -126
  13. package/dist/jest-compat/setup.mjs +32 -4
  14. package/dist/jest-compat.cjs +277 -33
  15. package/dist/jest-compat.d.cts +1 -1
  16. package/dist/jest-compat.d.mts +1 -1
  17. package/dist/jest-compat.mjs +257 -33
  18. package/dist/native/assets.mjs +41 -10
  19. package/dist/native/babel-worker.mjs +4 -2
  20. package/dist/native/boundary.mjs +52 -14
  21. package/dist/native/bounded-process.mjs +110 -27
  22. package/dist/native/explain.mjs +101 -5
  23. package/dist/native/expo-module-mocks.mjs +3 -0
  24. package/dist/native/gesture-handler-buttons.mjs +148 -0
  25. package/dist/native/hooks.mjs +8 -2
  26. package/dist/native/hot-diagnostic.mjs +7 -0
  27. package/dist/native/library-jest.mjs +16 -8
  28. package/dist/native/loader.mjs +159 -2
  29. package/dist/native/metro-profile-compiler.mjs +2 -1
  30. package/dist/native/metro-profile.mjs +2 -0
  31. package/dist/native/ownership-ledger.d.mts +2 -0
  32. package/dist/native/ownership-ledger.mjs +3 -2
  33. package/dist/native/react-dedupe.d.mts +7 -0
  34. package/dist/native/react-dedupe.mjs +191 -0
  35. package/dist/native/registry-compiler.mjs +3 -2
  36. package/dist/native/registry-process.mjs +90 -12
  37. package/dist/native/registry.mjs +9 -4
  38. package/dist/native/reset.mjs +51 -26
  39. package/dist/native/resolve.mjs +5 -1
  40. package/dist/native/setup.mjs +15 -7
  41. package/dist/native/state-manifest.mjs +2 -3
  42. package/dist/native/transform.mjs +125 -3
  43. package/dist/native/worker.mjs +3 -12
  44. package/dist/node-dispatch.mjs +2 -0
  45. package/dist/preset-react.d.mts +11 -0
  46. package/dist/preset-react.mjs +121 -0
  47. package/dist/{presets-DLH7uRGA.mjs → presets-Dw0Sz9O6.mjs} +1352 -567
  48. package/dist/presets.d.mts +1 -1
  49. package/dist/presets.mjs +1 -1
  50. package/dist/setup-files-C6-77IIs.mjs +22 -0
  51. package/dist/setup.mjs +15 -13
  52. package/package.json +15 -5
  53. package/dist/memory-Couw0Esx.mjs +0 -151
  54. package/dist/native/compile-cache.mjs +0 -57
@@ -1,15 +1,19 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-D70C1uOS.mjs";
1
2
  import { t as AUTO_DETECT_PRESETS } from "./preset-map-DdAexIwz.mjs";
2
3
  import { createRequire } from "node:module";
3
4
  import path from "node:path";
4
5
  import fs from "node:fs";
6
+ import os from "node:os";
5
7
  import { VitestNativeError, VitestNativeTypeError } from "./errors.mjs";
6
8
  import { mainFieldFile } from "./native/shared-resolver.mjs";
7
9
  import crypto, { createHash } from "node:crypto";
10
+ import { REACT_DEDUPE } from "./native/react-dedupe.mjs";
8
11
  import { AsyncLocalStorage } from "node:async_hooks";
9
12
  import { projectBabelCaller } from "./native/babel-caller.mjs";
10
13
  import { relativeToRoot, rootSpellingOf } from "./native/root-spelling.mjs";
11
14
  import { resolveTransformPreset } from "./native/babel-preset.mjs";
12
15
  import { containsPath, dependencyDirOf } from "./native/match.mjs";
16
+ import childProcess from "node:child_process";
13
17
  // src/peer-requirements.ts
14
18
  const PEER_REQUIREMENTS = [
15
19
  {
@@ -595,7 +599,7 @@ const KNOWN_PLUGINS = [
595
599
  {
596
600
  names: ["babel-plugin-react-compiler"],
597
601
  verdict: "unneeded",
598
- reason: () => "React Compiler only adds memoization to components that follow the Rules of React (react.dev/learn/react-compiler); they render the same without it."
602
+ reason: () => "tests run without it. It applies to the files projectBabel compiles with Babel ('auto': those another entry needs; 'always': all). There a memoized child given the same props skips re-rendering, so a test reading a value React does not track during render (a shared value, a ref) can see it keep its earlier value. Other files run without it, so a test that counts renders can see more than under babel-jest."
599
603
  }
600
604
  ];
601
605
  const unknownReason = (e) => `${e.written} ran on every file under babel-jest and does not run under vitest-native; check whether tests depend on what it does.`;
@@ -1403,8 +1407,7 @@ const NEVER_INLINE = /* @__PURE__ */ new Set([
1403
1407
  "react-test-renderer",
1404
1408
  "test-renderer",
1405
1409
  "react-native",
1406
- "react",
1407
- "react-is"
1410
+ ...REACT_DEDUPE
1408
1411
  ]);
1409
1412
  /** Does this manifest offer a React Native build, by legacy field or export condition? */
1410
1413
  function hasReactNativeBuild(manifest) {
@@ -1536,6 +1539,173 @@ function runtimeImports(dir, manifest) {
1536
1539
  runtimeMemo.set(dir, names);
1537
1540
  return names;
1538
1541
  }
1542
+ /**
1543
+ * The packages installed directly in each directory's node_modules, scoped ones included
1544
+ * (`@scope/name`), whose manifest mentions `react-native`, by name. Hidden entries
1545
+ * (`.bin`, `.pnpm`, `.bun`) are not packages. A hoisted install holds thousands, and
1546
+ * reading every manifest cost about 170 ms on 2,700, so each node_modules' answer is kept
1547
+ * in its `.cache/vitest-native`, keyed by the lockfile and the modification times of
1548
+ * node_modules and its scope directories: an install, an upgrade or a new package changes
1549
+ * the key. A hit costs one directory read and a stat per scope.
1550
+ */
1551
+ function installedReactNativeCandidates(dirs) {
1552
+ const found = /* @__PURE__ */ new Set();
1553
+ const list = (dir) => {
1554
+ try {
1555
+ return fs.readdirSync(dir);
1556
+ } catch {
1557
+ return [];
1558
+ }
1559
+ };
1560
+ const mtime = (dir) => fs.statSync(dir, { throwIfNoEntry: false })?.mtimeMs ?? 0;
1561
+ const manifestText = (dir) => {
1562
+ try {
1563
+ return fs.readFileSync(path.join(dir, "package.json"), "utf8");
1564
+ } catch {
1565
+ return "";
1566
+ }
1567
+ };
1568
+ for (const dir of dirs) {
1569
+ const modules = path.join(dir, "node_modules");
1570
+ const entries = list(modules).filter((entry) => !entry.startsWith("."));
1571
+ if (entries.length === 0) continue;
1572
+ const scopes = entries.filter((entry) => entry.startsWith("@"));
1573
+ const cacheDir = path.join(modules, ".cache", "vitest-native");
1574
+ ensureDir(cacheDir);
1575
+ const key = createHash("sha1").update(INSTALLED_SCAN_VERSION).update(dependencyFingerprint(dir)).update(String(mtime(modules))).update(scopes.map((scope) => `${scope}:${mtime(path.join(modules, scope))}`).join("\0")).digest("hex");
1576
+ const cacheFile = path.join(cacheDir, `installed-rn-${key}.json`);
1577
+ const cached = readNames(cacheFile);
1578
+ if (cached) {
1579
+ for (const name of cached) found.add(name);
1580
+ continue;
1581
+ }
1582
+ const names = [];
1583
+ const consider = (name, at) => {
1584
+ if (manifestText(at).includes("\"react-native\"")) names.push(name);
1585
+ };
1586
+ for (const entry of entries) if (!entry.startsWith("@")) consider(entry, path.join(modules, entry));
1587
+ else for (const scoped of list(path.join(modules, entry))) if (!scoped.startsWith(".")) consider(`${entry}/${scoped}`, path.join(modules, entry, scoped));
1588
+ writeNames(cacheFile, names);
1589
+ for (const name of names) found.add(name);
1590
+ }
1591
+ return found;
1592
+ }
1593
+ /** Packages whose detection does more than pick an owner; detected only when declared. */
1594
+ const UNDECLARED_SCAN_EXEMPT = /* @__PURE__ */ new Set(["expo"]);
1595
+ /** Bumped when installedReactNativeCandidates' answer changes for the same install. */
1596
+ const INSTALLED_SCAN_VERSION = "installed-rn-1";
1597
+ function readNames(file) {
1598
+ try {
1599
+ const names = JSON.parse(fs.readFileSync(file, "utf8"));
1600
+ return Array.isArray(names) ? names : null;
1601
+ } catch {
1602
+ return null;
1603
+ }
1604
+ }
1605
+ function ensureDir(dir) {
1606
+ try {
1607
+ fs.mkdirSync(dir, { recursive: true });
1608
+ return true;
1609
+ } catch {
1610
+ return false;
1611
+ }
1612
+ }
1613
+ /** Written to a temporary name and renamed, so a concurrent reader never sees half. */
1614
+ function writeNames(file, names) {
1615
+ try {
1616
+ const tmp = `${file}.${process.pid}.tmp`;
1617
+ fs.writeFileSync(tmp, JSON.stringify(names));
1618
+ fs.renameSync(tmp, file);
1619
+ return true;
1620
+ } catch {
1621
+ return false;
1622
+ }
1623
+ }
1624
+ /** Every string target of a manifest's `exports`: each subpath, each condition. */
1625
+ function allExportTargets(exportsField) {
1626
+ const out = [];
1627
+ const collect = (value) => {
1628
+ if (typeof value === "string") out.push(value);
1629
+ else if (value && typeof value === "object") Object.values(value).forEach(collect);
1630
+ };
1631
+ collect(exportsField);
1632
+ return out.filter((target) => !/\.d\.[cm]?ts$/.test(target) && !target.includes("*"));
1633
+ }
1634
+ /**
1635
+ * The packages a package's modules import unconditionally, by name: from the files its
1636
+ * runtime entries reach (its `react-native` field, `main`, and every `exports` subpath)
1637
+ * through relative imports, the source of each top-level `import` and `export … from`
1638
+ * that is not type-only, and each top-level `require("…")` statement or declaration. Parsed with the
1639
+ * project's Babel parser, so a `require` inside a condition (`if (__DEV__)`) or a function
1640
+ * and a specifier inside a string are not imports. `truncated` when the file limit cut
1641
+ * the scan short. For the undeclared workspace edge of the closure walk (#692), which
1642
+ * decides a package's owner alone and so needs no false hits; the peer edge keeps
1643
+ * runtimeImports.
1644
+ */
1645
+ function staticImports(dir, manifest, parse, memo, limit) {
1646
+ const memoized = memo.get(dir);
1647
+ if (memoized) return memoized;
1648
+ const result = {
1649
+ names: /* @__PURE__ */ new Set(),
1650
+ truncated: false
1651
+ };
1652
+ memo.set(dir, result);
1653
+ if (!parse) return result;
1654
+ const entries = [
1655
+ typeof manifest["react-native"] === "string" ? manifest["react-native"] : null,
1656
+ typeof manifest.main === "string" ? manifest.main : null,
1657
+ ...allExportTargets(manifest.exports)
1658
+ ].filter((entry) => entry !== null);
1659
+ if (entries.length === 0) entries.push("index");
1660
+ const pending = entries.map((entry) => runtimeFile(path.resolve(dir, entry))).filter((file) => file !== null && containsPath(dir, file));
1661
+ const seen = /* @__PURE__ */ new Set();
1662
+ const specifiers = (file) => {
1663
+ const typescript = /\.[cm]?tsx?$/.test(file);
1664
+ let program;
1665
+ try {
1666
+ program = parse(fs.readFileSync(file, "utf8"), {
1667
+ sourceType: "unambiguous",
1668
+ allowReturnOutsideFunction: true,
1669
+ errorRecovery: true,
1670
+ plugins: typescript ? ["typescript", ...file.endsWith("x") ? ["jsx"] : []] : ["jsx", "flow"]
1671
+ }).program;
1672
+ } catch {
1673
+ return [];
1674
+ }
1675
+ const found = [];
1676
+ const requireOf = (node) => node?.type === "CallExpression" && node.callee?.type === "Identifier" && node.callee.name === "require" && node.arguments?.length === 1 && node.arguments[0].type === "StringLiteral" ? node.arguments[0].value : null;
1677
+ for (const node of program.body) if (node.type === "ImportDeclaration") {
1678
+ if (!(node.importKind === "type" || node.specifiers.length > 0 && node.specifiers.every((spec) => spec.importKind === "type"))) found.push(node.source.value);
1679
+ } else if ((node.type === "ExportNamedDeclaration" || node.type === "ExportAllDeclaration") && node.source && node.exportKind !== "type") found.push(node.source.value);
1680
+ else if (node.type === "ExpressionStatement") {
1681
+ const spec = requireOf(node.expression);
1682
+ if (spec) found.push(spec);
1683
+ } else if (node.type === "VariableDeclaration") for (const declaration of node.declarations) {
1684
+ let init = declaration.init;
1685
+ while (init?.type === "MemberExpression") init = init.object;
1686
+ const spec = requireOf(init);
1687
+ if (spec) found.push(spec);
1688
+ }
1689
+ return found;
1690
+ };
1691
+ while (pending.length > 0) {
1692
+ if (seen.size >= limit) {
1693
+ result.truncated = true;
1694
+ break;
1695
+ }
1696
+ const file = pending.pop();
1697
+ if (seen.has(file) || file.endsWith(".json")) continue;
1698
+ seen.add(file);
1699
+ for (const specifier of specifiers(file)) if (specifier.startsWith(".")) {
1700
+ const target = runtimeFile(path.resolve(path.dirname(file), specifier));
1701
+ if (target && containsPath(dir, target) && !NODE_MODULES_DIR.test(relativeToRoot(dir, target))) pending.push(target);
1702
+ } else if (PACKAGE_SPECIFIER.test(specifier)) {
1703
+ const parts = specifier.split("/");
1704
+ result.names.add(specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0]);
1705
+ }
1706
+ }
1707
+ return result;
1708
+ }
1539
1709
  /** Manifest fields that make a package part of the React Native ecosystem. */
1540
1710
  function dependsOnReactNative(manifest) {
1541
1711
  for (const field of ["dependencies", "peerDependencies"]) {
@@ -1704,7 +1874,7 @@ function fixedReplacement(replacement, regExp) {
1704
1874
  *
1705
1875
  * `reachedPaths` adds the workspace members an alias reaches; see ReachedPackages.
1706
1876
  */
1707
- function detectEcosystemPackages(projectRoot, explicit = [], testRoots = [], neverTransform = [], activePresets, dirOf = dependencyDirOf, { reachedPaths = [], onReachedUndeclared, compileReactNativeFieldSource } = {}) {
1877
+ function detectEcosystemPackages(projectRoot, explicit = [], testRoots = [], neverTransform = [], activePresets, dirOf = dependencyDirOf, { reachedPaths = [], onReachedUndeclared, onImportedUndeclared, onImportScanTruncated, onScanFoundDependency, importScanLimit = MAX_RUNTIME_FILES, compileReactNativeFieldSource } = {}) {
1708
1878
  runtimeMemo.clear();
1709
1879
  const roots = (Array.isArray(projectRoot) ? projectRoot : [projectRoot]).filter(Boolean);
1710
1880
  const shadowed = Object.entries(AUTO_DETECT_PRESETS).filter(([, presetName]) => activePresets === void 0 || activePresets.includes(presetName)).map(([pkg]) => pkg);
@@ -1819,14 +1989,23 @@ function detectEcosystemPackages(projectRoot, explicit = [], testRoots = [], nev
1819
1989
  if (deps && typeof deps === "object") for (const name of Object.keys(deps)) projectDeclared.add(name);
1820
1990
  }
1821
1991
  }
1992
+ const held = closureOf([...shadowed, ...neverTransform].map((name) => [name, installedOf(name)]));
1993
+ for (const name of installedReactNativeCandidates(declaringDirs)) {
1994
+ if (candidates.has(name) || held.has(name) || skip.has(name)) continue;
1995
+ if (UNDECLARED_SCAN_EXEMPT.has(name)) continue;
1996
+ if (name.startsWith("@react-native/") || rnOwned.has(name) || toolchain.has(name)) continue;
1997
+ const installed = installedOf(name);
1998
+ if (!installed || !NODE_MODULES_DIR.test(installed.dir) || ownsTheRun(name)) continue;
1999
+ if (dependsOnReactNative(installed.manifest)) detected.push(name);
2000
+ }
1822
2001
  const detectedSet = new Set(detected);
1823
2002
  const inClosure = new Set(detected);
1824
2003
  const walked = /* @__PURE__ */ new Set();
1825
2004
  const queue = [];
1826
2005
  const reach = (name, installed) => {
1827
2006
  inClosure.add(name);
1828
- if (walked.has(name)) return;
1829
- walked.add(name);
2007
+ if (walked.has(installed.dir)) return;
2008
+ walked.add(installed.dir);
1830
2009
  queue.push(installed);
1831
2010
  };
1832
2011
  for (const name of detected) {
@@ -1838,8 +2017,8 @@ function detectEcosystemPackages(projectRoot, explicit = [], testRoots = [], nev
1838
2017
  for (const name of explicit) {
1839
2018
  if (neverSeeded.has(name)) continue;
1840
2019
  const installed = installedOf(name);
1841
- if (!installed || walked.has(name)) continue;
1842
- walked.add(name);
2020
+ if (!installed || walked.has(installed.dir)) continue;
2021
+ walked.add(installed.dir);
1843
2022
  queue.push(installed);
1844
2023
  }
1845
2024
  /** A dependency or peer the walk may not take, whatever its manifest says. */
@@ -1848,27 +2027,47 @@ function detectEcosystemPackages(projectRoot, explicit = [], testRoots = [], nev
1848
2027
  * Walk the queue. With `installedOnly`, only installed packages (a real path inside a
1849
2028
  * node_modules directory) are added: see "Workspace members the run reaches" below.
1850
2029
  */
2030
+ let parser;
2031
+ const staticMemo = /* @__PURE__ */ new Map();
1851
2032
  const walk = (installedOnly) => {
1852
2033
  const admits = (installed) => !installedOnly || NODE_MODULES_DIR.test(installed.dir);
1853
2034
  while (queue.length > 0) {
1854
2035
  const pkg = queue.pop();
1855
2036
  const deps = pkg.manifest.dependencies;
1856
2037
  for (const dep of deps && typeof deps === "object" ? Object.keys(deps) : []) {
1857
- if (walked.has(dep) || excluded(dep)) continue;
2038
+ if (excluded(dep)) continue;
1858
2039
  const installed = dependencyOf(pkg, dep);
1859
2040
  if (!installed) continue;
2041
+ if (walked.has(installed.dir)) continue;
1860
2042
  if (!inClosure.has(dep) && publishesOnlyEsm(installed.manifest)) continue;
1861
2043
  if (admits(installed)) reach(dep, installed);
1862
2044
  }
1863
2045
  const peers = pkg.manifest.peerDependencies;
1864
2046
  const peersMeta = pkg.manifest.peerDependenciesMeta;
1865
2047
  for (const peer of peers && typeof peers === "object" ? Object.keys(peers) : []) {
1866
- if (walked.has(peer) || excluded(peer)) continue;
2048
+ if (peersMeta?.[peer]?.optional === true || excluded(peer)) continue;
1867
2049
  const installed = dependencyOf(pkg, peer);
1868
- if (!installed || !admits(installed)) continue;
1869
- const loadedReactNativePeer = !detectedSet.has(peer) && peersMeta?.[peer]?.optional !== true && dependsOnReactNative(installed.manifest) && runtimeImports(pkg.dir, pkg.manifest).has(peer);
2050
+ if (!installed || !admits(installed) || walked.has(installed.dir)) continue;
2051
+ const loadedReactNativePeer = !detectedSet.has(peer) && dependsOnReactNative(installed.manifest) && runtimeImports(pkg.dir, pkg.manifest).has(peer);
1870
2052
  if (detectedSet.has(peer) || loadedReactNativePeer) reach(peer, installed);
1871
2053
  }
2054
+ if (!NODE_MODULES_DIR.test(pkg.dir)) {
2055
+ const listed = (field) => Object.keys(pkg.manifest[field] ?? {});
2056
+ const declared = /* @__PURE__ */ new Set([...listed("dependencies"), ...listed("peerDependencies")]);
2057
+ const devOnly = new Set(listed("devDependencies"));
2058
+ parser ??= babelParser(roots[0]) ?? babelParser(process.cwd()) ?? false;
2059
+ const scanned = staticImports(pkg.dir, pkg.manifest, parser || null, staticMemo, importScanLimit);
2060
+ if (scanned.truncated) onImportScanTruncated?.(pkg.manifest.name, importScanLimit);
2061
+ for (const name of scanned.names) {
2062
+ if (declared.has(name) || excluded(name)) continue;
2063
+ const installed = dependencyOf(pkg, name);
2064
+ if (!installed || NODE_MODULES_DIR.test(installed.dir) || !admits(installed)) continue;
2065
+ if (walked.has(installed.dir)) continue;
2066
+ if (!inClosure.has(name) && publishesOnlyEsm(installed.manifest)) continue;
2067
+ onImportedUndeclared?.(pkg.manifest.name, name, installed.dir, devOnly.has(name) ? "devDependency" : "undeclared");
2068
+ reach(name, installed);
2069
+ }
2070
+ }
1872
2071
  }
1873
2072
  };
1874
2073
  walk(false);
@@ -1897,9 +2096,9 @@ function detectEcosystemPackages(projectRoot, explicit = [], testRoots = [], nev
1897
2096
  for (const member of reachedMembers.values()) {
1898
2097
  const deps = member.manifest.dependencies;
1899
2098
  for (const dep of deps && typeof deps === "object" ? Object.keys(deps) : []) {
1900
- if (walked.has(dep) || excluded(dep) || !detectedSet.has(dep)) continue;
2099
+ if (excluded(dep) || !detectedSet.has(dep)) continue;
1901
2100
  const installed = installedFrom(member.dir, dep);
1902
- if (installed) reach(dep, installed);
2101
+ if (installed && !walked.has(installed.dir)) reach(dep, installed);
1903
2102
  }
1904
2103
  }
1905
2104
  walk(true);
@@ -1918,8 +2117,250 @@ function detectEcosystemPackages(projectRoot, explicit = [], testRoots = [], nev
1918
2117
  if (file && PLAIN_SOURCE.includes(path.extname(file)) && parse && !isPlainJavaScript(parse, file)) inClosure.add(name);
1919
2118
  }
1920
2119
  }
2120
+ if (onScanFoundDependency) {
2121
+ const reported = /* @__PURE__ */ new Set();
2122
+ const pending = [];
2123
+ for (const name of detected) {
2124
+ const installed = installedOf(name);
2125
+ if (installed && !walked.has(installed.dir)) pending.push([installed, name]);
2126
+ }
2127
+ while (pending.length > 0) {
2128
+ const [pkg, parent] = pending.pop();
2129
+ const deps = pkg.manifest.dependencies;
2130
+ for (const dep of deps && typeof deps === "object" ? Object.keys(deps) : []) {
2131
+ if (excluded(dep)) continue;
2132
+ const installed = dependencyOf(pkg, dep);
2133
+ if (!installed || walked.has(installed.dir) || reported.has(installed.dir)) continue;
2134
+ reported.add(installed.dir);
2135
+ if (!inClosure.has(dep)) onScanFoundDependency(installed.dir, dep, parent);
2136
+ pending.push([installed, parent]);
2137
+ }
2138
+ }
2139
+ }
1921
2140
  return [...inClosure].sort();
1922
2141
  }
2142
+ // src/native/memory.mjs
2143
+ var memory_exports = /* @__PURE__ */ __exportAll({
2144
+ createHotMemoryPlan: () => createHotMemoryPlan,
2145
+ defaultRequestedWorkers: () => defaultRequestedWorkers,
2146
+ effectiveMemoryLimit: () => effectiveMemoryLimit,
2147
+ formatBytes: () => formatBytes,
2148
+ formatHotMemoryPlan: () => formatHotMemoryPlan,
2149
+ formatHotWorkerDecision: () => formatHotWorkerDecision,
2150
+ hostAutoWorkers: () => hostAutoWorkers,
2151
+ hostPerformanceCores: () => hostPerformanceCores,
2152
+ memoryLoweredWorkers: () => memoryLoweredWorkers,
2153
+ resolveRequestedWorkers: () => resolveRequestedWorkers
2154
+ });
2155
+ const MIB = 1048576;
2156
+ const MIN_WORKER_HEAP = 96 * MIB;
2157
+ const MAX_WORKER_HEAP = 512 * MIB;
2158
+ const MAIN_PROCESS_RESERVE = 256 * MIB;
2159
+ const REPLACEMENT_OVERLAP_RESERVE = 192 * MIB;
2160
+ const WORKER_RSS_ADMISSION_COST = 256 * MIB;
2161
+ const DEFAULT_AUTO_WORKERS = 4;
2162
+ const MAX_AUTO_WORKERS = 6;
2163
+ function finitePositive(value) {
2164
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : null;
2165
+ }
2166
+ function effectiveMemoryLimit({ totalMemory, constrainedMemory }) {
2167
+ const total = finitePositive(totalMemory);
2168
+ const constrained = finitePositive(constrainedMemory);
2169
+ if (total === null && constrained === null) return {
2170
+ bytes: null,
2171
+ source: "unknown"
2172
+ };
2173
+ if (total === null) return {
2174
+ bytes: constrained,
2175
+ source: "constrained"
2176
+ };
2177
+ if (constrained === null || total <= constrained) return {
2178
+ bytes: total,
2179
+ source: "host"
2180
+ };
2181
+ return {
2182
+ bytes: constrained,
2183
+ source: "constrained"
2184
+ };
2185
+ }
2186
+ /**
2187
+ * `sysctl -n` for each name, one value per line, or null when any name is unknown (an
2188
+ * Intel Mac has no `hw.perflevel*`) or sysctl cannot run. Called through the
2189
+ * child_process object so tests can stand in for the host.
2190
+ */
2191
+ function readSysctl(names) {
2192
+ const result = childProcess.spawnSync("/usr/sbin/sysctl", ["-n", ...names], {
2193
+ encoding: "utf8",
2194
+ timeout: 2e3
2195
+ });
2196
+ if (result.status !== 0 || typeof result.stdout !== "string") return null;
2197
+ const lines = result.stdout.trim().split("\n");
2198
+ return lines.length === names.length ? lines : null;
2199
+ }
2200
+ /**
2201
+ * The host's performance cores, where the OS reports core classes, else null. macOS on
2202
+ * Apple silicon reports them as `hw.perflevel0.physicalcpu` with `hw.nperflevels` of 2
2203
+ * or more; a single level (a virtual machine, say) is no split. Linux reports no core
2204
+ * classes inside the containers tests run in, so it takes the fallback.
2205
+ */
2206
+ function hostPerformanceCores({ platform = process.platform, sysctl = readSysctl } = {}) {
2207
+ if (platform !== "darwin") return null;
2208
+ const values = sysctl(["hw.nperflevels", "hw.perflevel0.physicalcpu"]);
2209
+ if (values === null) return null;
2210
+ const [levels, performance] = values.map((value) => Number(value));
2211
+ if (!Number.isInteger(levels) || levels < 2) return null;
2212
+ return Number.isInteger(performance) && performance > 0 ? performance : null;
2213
+ }
2214
+ /**
2215
+ * The worker count the hot runtime chooses when nobody set one: one per performance
2216
+ * core, where the OS reports them, at most MAX_AUTO_WORKERS; else four. On the suites
2217
+ * measured for #906 the fastest count equalled the performance cores (6 on 6P+6E, 4 on
2218
+ * 4P+6E); more workers spill onto efficiency cores and cost CPU for no time. Never
2219
+ * below two, the fewest the hot runtime can recycle with. The memory plan still bounds
2220
+ * it.
2221
+ */
2222
+ function hostAutoWorkers(input) {
2223
+ const cores = hostPerformanceCores(input);
2224
+ return cores === null ? {
2225
+ count: DEFAULT_AUTO_WORKERS,
2226
+ source: "default"
2227
+ } : {
2228
+ count: Math.min(MAX_AUTO_WORKERS, Math.max(2, cores)),
2229
+ source: "performance-cores"
2230
+ };
2231
+ }
2232
+ function defaultRequestedWorkers(parallelism = os.availableParallelism?.() ?? os.cpus().length) {
2233
+ return Math.max(1, Math.floor(parallelism) - 1);
2234
+ }
2235
+ /** Resolve Vitest's number/percentage worker option without importing Vitest internals. */
2236
+ function resolveRequestedWorkers(value, { parallelism, fileParallelism = true } = {}) {
2237
+ if (fileParallelism === false) return 1;
2238
+ const cpus = Math.max(1, Math.floor(parallelism ?? os.availableParallelism?.() ?? os.cpus().length));
2239
+ if (typeof value === "number" && Number.isFinite(value)) return Math.max(1, Math.floor(value));
2240
+ if (typeof value === "string") {
2241
+ const trimmed = value.trim();
2242
+ if (/^\d+(?:\.\d+)?%$/.test(trimmed)) return Math.max(1, Math.floor(cpus * Number.parseFloat(trimmed) / 100));
2243
+ if (/^\d+$/.test(trimmed)) return Math.max(1, Number.parseInt(trimmed, 10));
2244
+ }
2245
+ return Math.max(1, cpus - 1);
2246
+ }
2247
+ /**
2248
+ * Compute the hot-runtime envelope.
2249
+ *
2250
+ * The reserves were earned by the packed 406-file RNTL experiment. They are
2251
+ * conservative defaults, not portable benchmark claims.
2252
+ *
2253
+ * The automatic count (hostAutoWorkers: the performance cores up to six, else four) bounds the
2254
+ * AUTOMATIC choice only. It is where a default stops paying for its memory and CPU, not
2255
+ * a safety limit (validation/module-isolation/README.md, "Worker-count curve"; #906).
2256
+ * A worker count the user set (`maxWorkers` in config, `--maxWorkers`,
2257
+ * `VITEST_MAX_WORKERS`) is therefore admitted up to what the memory envelope holds, the
2258
+ * bound that does protect the process. With no known memory limit nothing can admit
2259
+ * more than the automatic count, so it applies there either way.
2260
+ */
2261
+ function createHotMemoryPlan({ totalMemory = os.totalmem(), constrainedMemory = process.constrainedMemory?.() ?? 0, requestedWorkers = defaultRequestedWorkers(), explicitWorkers = false, autoWorkers } = {}) {
2262
+ const effective = effectiveMemoryLimit({
2263
+ totalMemory,
2264
+ constrainedMemory
2265
+ });
2266
+ const requested = Math.max(1, Math.floor(requestedWorkers));
2267
+ const auto = autoWorkers ?? (explicitWorkers && effective.bytes !== null ? {
2268
+ count: null,
2269
+ source: "not-used"
2270
+ } : hostAutoWorkers());
2271
+ if (effective.bytes === null) return Object.freeze({
2272
+ version: 1,
2273
+ source: effective.source,
2274
+ effectiveLimit: null,
2275
+ softRssLimit: null,
2276
+ hardRssLimit: null,
2277
+ requestedWorkers: requested,
2278
+ autoWorkers: auto.count,
2279
+ autoWorkersSource: auto.source,
2280
+ admittedWorkers: Math.min(auto.count, requested),
2281
+ maxWorkers: Math.min(auto.count, requested),
2282
+ workerHeapLimit: 256 * MIB,
2283
+ mainProcessReserve: MAIN_PROCESS_RESERVE,
2284
+ replacementOverlapReserve: REPLACEMENT_OVERLAP_RESERVE
2285
+ });
2286
+ const softRssLimit = Math.floor(effective.bytes * .8);
2287
+ const hardRssLimit = Math.floor(effective.bytes * .9);
2288
+ const workerEnvelope = Math.max(0, softRssLimit - MAIN_PROCESS_RESERVE - REPLACEMENT_OVERLAP_RESERVE);
2289
+ const memoryAdmits = Math.floor(workerEnvelope / WORKER_RSS_ADMISSION_COST);
2290
+ const admittedWorkers = Math.max(1, explicitWorkers ? memoryAdmits : Math.min(auto.count, memoryAdmits));
2291
+ const maxWorkers = Math.min(requested, admittedWorkers);
2292
+ const perWorkerEnvelope = workerEnvelope / maxWorkers;
2293
+ const workerHeapLimit = Math.min(MAX_WORKER_HEAP, Math.max(MIN_WORKER_HEAP, Math.floor(perWorkerEnvelope * .65)));
2294
+ return Object.freeze({
2295
+ version: 1,
2296
+ source: effective.source,
2297
+ effectiveLimit: effective.bytes,
2298
+ softRssLimit,
2299
+ hardRssLimit,
2300
+ requestedWorkers: requested,
2301
+ autoWorkers: auto.count,
2302
+ autoWorkersSource: auto.source,
2303
+ admittedWorkers,
2304
+ maxWorkers,
2305
+ workerHeapLimit,
2306
+ mainProcessReserve: MAIN_PROCESS_RESERVE,
2307
+ replacementOverlapReserve: REPLACEMENT_OVERLAP_RESERVE
2308
+ });
2309
+ }
2310
+ function formatBytes(bytes) {
2311
+ if (bytes == null) return "unknown";
2312
+ return `${Math.round(bytes / MIB)} MiB`;
2313
+ }
2314
+ /**
2315
+ * The count the plan runs when memory is what held it below the count requested, else
2316
+ * null: the plan runs what was requested, or the automatic count chose, which a count
2317
+ * the user sets lifts and which is not about memory. What memory alone admits
2318
+ * comes from the plan's own figures (createHotMemoryPlan).
2319
+ */
2320
+ function memoryLoweredWorkers(plan) {
2321
+ if (plan.maxWorkers >= plan.requestedWorkers || plan.softRssLimit == null) return null;
2322
+ const memoryAdmits = Math.max(1, Math.floor(Math.max(0, plan.softRssLimit - plan.mainProcessReserve - plan.replacementOverlapReserve) / WORKER_RSS_ADMISSION_COST));
2323
+ return plan.admittedWorkers < memoryAdmits ? null : plan.maxWorkers;
2324
+ }
2325
+ /**
2326
+ * The hot runtime's worker decision as one line of the startup log, so a user can tune
2327
+ * `maxWorkers` or report a run without turning diagnostics on (formatHotMemoryPlan has
2328
+ * the full envelope).
2329
+ */
2330
+ function formatHotWorkerDecision(plan) {
2331
+ const memory = plan.effectiveLimit == null ? "memory unknown" : `${formatBytes(plan.effectiveLimit)} ${plan.source === "constrained" ? "memory limit" : "host memory"}`;
2332
+ if (plan.maxWorkers < plan.requestedWorkers) {
2333
+ if (memoryLoweredWorkers(plan) === null) return `workers: ${plan.maxWorkers} (automatic: ${describeAutoWorkers(plan)}; ${plan.requestedWorkers} available, set maxWorkers to run more; ${memory})`;
2334
+ return `workers: ${plan.maxWorkers} (memory plan admitted ${plan.admittedWorkers} of ${plan.requestedWorkers} requested, ${memory})`;
2335
+ }
2336
+ return `workers: ${plan.maxWorkers} (as requested; memory plan admits up to ${plan.admittedWorkers}, ${memory})`;
2337
+ }
2338
+ /** How the automatic count was chosen, for the startup line and the full plan. */
2339
+ function describeAutoWorkers(plan) {
2340
+ if (plan.autoWorkersSource === "performance-cores") return `${plan.autoWorkers}, one per performance core, at most ${MAX_AUTO_WORKERS}`;
2341
+ if (plan.autoWorkersSource === "default") return `${plan.autoWorkers}, the default where the OS reports no performance cores`;
2342
+ return "not used, the worker count was set";
2343
+ }
2344
+ function formatHotMemoryPlan(plan) {
2345
+ return [
2346
+ `effective limit: ${formatBytes(plan.effectiveLimit)} (${plan.source})`,
2347
+ `RSS soft/hard: ${formatBytes(plan.softRssLimit)} / ${formatBytes(plan.hardRssLimit)}`,
2348
+ `workers requested/admitted/selected: ${plan.requestedWorkers} / ${plan.admittedWorkers} / ${plan.maxWorkers}`,
2349
+ `automatic worker count: ${describeAutoWorkers(plan)}`,
2350
+ `worker heap recycle threshold: ${formatBytes(plan.workerHeapLimit)}`,
2351
+ `reserves main/replacement: ${formatBytes(plan.mainProcessReserve)} / ${formatBytes(plan.replacementOverlapReserve)}`
2352
+ ];
2353
+ }
2354
+ Object.freeze({
2355
+ MIB,
2356
+ MIN_WORKER_HEAP,
2357
+ MAX_WORKER_HEAP,
2358
+ MAIN_PROCESS_RESERVE,
2359
+ REPLACEMENT_OVERLAP_RESERVE,
2360
+ WORKER_RSS_ADMISSION_COST,
2361
+ DEFAULT_AUTO_WORKERS,
2362
+ MAX_AUTO_WORKERS
2363
+ });
1923
2364
  // src/host.ts
1924
2365
  /** The running Vite's version, and where it was read, for messages that name it. */
1925
2366
  async function runningVite(context) {
@@ -2037,4 +2478,4 @@ function assertHotWorkerLoadsRunningVitest(running, workerEntry) {
2037
2478
  version: running.version
2038
2479
  }, 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.");
2039
2480
  }
2040
- export { PEER_REQUIREMENTS as A, SUPPORTED_NODE as C, validateOptions as D, unsupportedNodeMessage as E, unsupportedExpoSdkMessage as F, unsupportedReactNativeMessage as I, belowRecommendedMessage as M, installedExpoVersion as N, validatePeerDependency as O, isBelowSupportedReactNative as P, shouldDefaultFsModuleCache as S, satisfiesNodeRange as T, isKnownPlugin as _, runningVite as a, readProjectSource as b, detectEcosystemPackages as c, detectEngine as d, createProjectBabel as f, classifyBabelPlugins as g, projectBabelTrigger as h, ownVitestPackage as i, SUPPORTED_EXPO_SDKS as j, warnUnknownOptions as k, babelParser as l, missingBabelCoreNotice as m, assertHotWorkerLoadsRunningVitest as n, usesVitePlus as o, isProjectSourceFile as p, installedViteVersion as r, aliasReachedPaths as s, assertHostResolvesRunningVitest as t, isPlainJavaScript as u, normalizeBabelName as v, assertSupportedNode as w, fsModuleCacheKey as x, installedManifest as y };
2481
+ export { unsupportedNodeMessage as A, unsupportedReactNativeMessage as B, installedManifest as C, SUPPORTED_NODE as D, shouldDefaultFsModuleCache as E, SUPPORTED_EXPO_SDKS as F, belowRecommendedMessage as I, installedExpoVersion as L, validatePeerDependency as M, warnUnknownOptions as N, assertSupportedNode as O, PEER_REQUIREMENTS as P, isBelowSupportedReactNative as R, normalizeBabelName as S, fsModuleCacheKey as T, isProjectSourceFile as _, runningVite as a, classifyBabelPlugins as b, formatHotMemoryPlan as c, aliasReachedPaths as d, detectEcosystemPackages as f, createProjectBabel as g, detectEngine as h, ownVitestPackage as i, validateOptions as j, satisfiesNodeRange as k, memoryLoweredWorkers as l, isPlainJavaScript as m, assertHotWorkerLoadsRunningVitest as n, usesVitePlus as o, babelParser as p, installedViteVersion as r, createHotMemoryPlan as s, assertHostResolvesRunningVitest as t, memory_exports as u, missingBabelCoreNotice as v, readProjectSource as w, isKnownPlugin as x, projectBabelTrigger as y, unsupportedExpoSdkMessage as z };
@@ -193,9 +193,23 @@ interface ReactNativeMock {
193
193
  usePressability: Mock;
194
194
  default: ReactNativeMock;
195
195
  }
196
+ /** What a preset module's factory is given when it builds its mock. */
197
+ interface PresetFactoryContext {
198
+ /**
199
+ * The React the test file renders with: the copy `react-native` resolves (the
200
+ * project's, where `react-native` is not installed). A mock that creates components,
201
+ * contexts or hooks uses this one rather than a React it imported itself: under the
202
+ * hot runtime's `freshRuntime` each file has its own React, and a hook or context from
203
+ * another file's React fails there.
204
+ */
205
+ React: typeof import("react");
206
+ }
196
207
  interface PresetModule {
197
- /** Factory that builds the mock object. Only called in Vitest worker processes. */
198
- factory: () => Record<string, any>;
208
+ /**
209
+ * Factory that builds the mock object, once per test file that imports the module.
210
+ * Only called in Vitest worker processes.
211
+ */
212
+ factory: (context: PresetFactoryContext) => Record<string, any>;
199
213
  /** Static list of named exports for virtual ESM module generation. Read at Vite config time (no vitest available). */
200
214
  exports: string[];
201
215
  /**
@@ -447,10 +461,7 @@ interface VitestNativeOptions {
447
461
  * re-execution: a suite whose files import many externalized (non-React
448
462
  * Native) packages measured 55% more wall clock at the extreme — still 9x
449
463
  * stock isolation, against 13.9x with it off. Set false to trade that back,
450
- * accepting that a package holding state across files will keep it. While it
451
- * is on, hot workers leave Node's V8 compile cache off, because every file
452
- * would add an entry per re-evaluated module (unless `NODE_COMPILE_CACHE` is
453
- * set, which turns the cache on before vitest-native runs).
464
+ * accepting that a package holding state across files will keep it.
454
465
  * - `freshRuntime` (experimental, off by default): React, its renderers, `scheduler`
455
466
  * and React Native Testing Library run again for every test file, as React Native
456
467
  * does, instead of staying loaded for the worker's life. State they hold at module
@@ -501,12 +512,13 @@ interface VitestNativeOptions {
501
512
  * is not in the cache yet (first install, an upgrade of React Native or
502
513
  * vitest-native, a Babel toolchain change, a cleared cache).
503
514
  *
504
- * - `'background'` *(default)*: the run starts at once and the registry compiles in
505
- * a low-priority background process. Test files that start before it is ready
506
- * load React Native file by file; files that start after use it. When Vitest
507
- * closes, a build still running gets up to half of `teardownTimeout` to finish,
508
- * so the next run starts warm.
509
- * - `'wait'`: compile the registry before the run starts, as in earlier versions.
515
+ * - `'wait'` *(default)*: compile the registry before the first test file starts.
516
+ * - `'background'`: the run starts at once and the registry compiles in a
517
+ * low-priority background process. Test files that start before it is ready load
518
+ * React Native file by file, compiling it inside their tests, so on a cold cache
519
+ * their tests run slower and can reach `testTimeout`; files that start after use
520
+ * it. When Vitest closes, a build still running gets up to half of
521
+ * `teardownTimeout` to finish, so the next run starts warm.
510
522
  *
511
523
  * The hot runtime, CI runs and `experimental.ownershipModel` always wait.
512
524
  */
@@ -572,4 +584,4 @@ declare function skia(): Preset;
572
584
  declare namespace index_d_exports {
573
585
  export { asyncStorage, bottomSheet, deviceInfo, expo, flashList, gestureHandler, keyboardController, mmkv, navigation, netInfo, reanimated, safeAreaContext, screens, skia, svg, unistyles, vectorIcons, webview, worklets };
574
586
  }
575
- export { VitestNativeOptions as C, ReactNativeMock as S, navigation as _, keyboardController as a, reanimated as b, vectorIcons as c, netInfo as d, mmkv as f, asyncStorage as g, screens as h, worklets as i, webview as l, expo as m, skia as n, bottomSheet as o, deviceInfo as p, unistyles as r, flashList as s, index_d_exports as t, svg as u, safeAreaContext as v, Preset as x, gestureHandler as y };
587
+ export { ReactNativeMock as C, PresetFactoryContext as S, navigation as _, keyboardController as a, reanimated as b, vectorIcons as c, netInfo as d, mmkv as f, asyncStorage as g, screens as h, worklets as i, webview as l, expo as m, skia as n, bottomSheet as o, deviceInfo as p, unistyles as r, flashList as s, index_d_exports as t, svg as u, safeAreaContext as v, VitestNativeOptions as w, Preset as x, gestureHandler as y };
package/dist/index.d.mts CHANGED
@@ -1,6 +1,6 @@
1
- import { C as VitestNativeOptions, S as ReactNativeMock, t as index_d_exports, x as Preset } from "./index-BpZ0E2eJ.mjs";
2
- import "./context.mjs";
1
+ import { C as ReactNativeMock, S as PresetFactoryContext, t as index_d_exports, w as VitestNativeOptions, x as Preset } from "./index-X3wuvaqa.mjs";
3
2
  import { Plugin } from "vite";
3
+ import "./context.mjs";
4
4
  /**
5
5
  * Preset names switched off by the object form of the `presets` option.
6
6
  *
@@ -11,4 +11,4 @@ import { Plugin } from "vite";
11
11
  */
12
12
  export declare function disabledPresetNames(presets: unknown): Set<string>;
13
13
  export declare function reactNative(options?: VitestNativeOptions): Plugin;
14
- export { type Preset, type ReactNativeMock, type VitestNativeOptions, index_d_exports as presets };
14
+ export { type Preset, type PresetFactoryContext, type ReactNativeMock, type VitestNativeOptions, index_d_exports as presets };