vitest-native 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CHANGELOG.md +373 -0
  2. package/README.md +32 -14
  3. package/dist/cli.cjs +506 -0
  4. package/dist/cli.d.cts +4 -0
  5. package/dist/cli.d.mts +4 -0
  6. package/dist/cli.mjs +502 -0
  7. package/dist/ecosystem-BIWaVwYL.cjs +294 -0
  8. package/dist/ecosystem-EFtHnKS9.mjs +256 -0
  9. package/dist/{index-DbfKy_bm.d.mts → index-CEgRDdhd.d.cts} +22 -3
  10. package/dist/{index-BgzErxHj.d.cts → index-j-0tueBr.d.mts} +20 -5
  11. package/dist/index.cjs +345 -200
  12. package/dist/index.d.cts +1 -1
  13. package/dist/index.d.mts +1 -1
  14. package/dist/index.mjs +341 -196
  15. package/dist/jest-compat/setup.mjs +65 -1
  16. package/dist/native/boundary.mjs +108 -30
  17. package/dist/native/compile-cache.mjs +45 -0
  18. package/dist/native/explain.mjs +69 -0
  19. package/dist/native/hooks.mjs +77 -4
  20. package/dist/native/loader.mjs +36 -7
  21. package/dist/native/match.mjs +107 -8
  22. package/dist/native/registry.mjs +471 -0
  23. package/dist/native/reset.mjs +18 -12
  24. package/dist/native/runner.mjs +13 -7
  25. package/dist/native/setup.mjs +44 -0
  26. package/dist/native/transform.mjs +88 -19
  27. package/dist/native/worker.mjs +13 -0
  28. package/dist/pool-CJmjRgsB.mjs +117 -0
  29. package/dist/pool-DzsEo9vv.cjs +121 -0
  30. package/dist/{preset-map-CNBOeqAu.cjs → preset-map-CG4FMtsl.cjs} +5 -1
  31. package/dist/{preset-map-C1UwEald.mjs → preset-map-CNsZKfvu.mjs} +5 -1
  32. package/dist/{presets-BTG8fiNF.cjs → presets-C4faM3ds.cjs} +838 -2
  33. package/dist/{presets-BFuAMwYQ.mjs → presets-CuDrNA_W.mjs} +761 -3
  34. package/dist/presets.cjs +5 -1
  35. package/dist/presets.d.cts +2 -2
  36. package/dist/presets.d.mts +2 -2
  37. package/dist/presets.mjs +2 -2
  38. package/dist/setup.cjs +327 -347
  39. package/dist/setup.mjs +318 -338
  40. package/docs/hot-default-design.md +129 -0
  41. package/docs/migrating-from-jest.md +43 -7
  42. package/docs/migrating-from-vitest-react-native.md +1 -1
  43. package/docs/release-readiness.md +2 -1
  44. package/package.json +23 -7
  45. package/dist/pool-B7LBfcMQ.mjs +0 -67
  46. package/dist/pool-p54QV1dQ.cjs +0 -69
@@ -6,6 +6,8 @@ import path from "node:path";
6
6
  import { expect, vi } from "vitest";
7
7
  import { installGlobals } from "./globals.mjs";
8
8
  import { installRequireHooks } from "./hooks.mjs";
9
+ import { installRegistry } from "./registry.mjs";
10
+ import { enableV8CompileCache } from "./compile-cache.mjs";
9
11
  import * as presetFactories from "../presets.mjs";
10
12
  import { animatedMatchers } from "../matchers.mjs";
11
13
  import { serializer as rnSerializer } from "../serializer.mjs";
@@ -95,6 +97,10 @@ for (const name of presetNames) {
95
97
  }
96
98
  }
97
99
 
100
+ // Enable the V8 compile cache before RN is compiled (it loads when the test file
101
+ // imports react-native, after this setup runs) so its bytecode is cached to disk
102
+ // and reused on the next file/worker/run. Covers the stock (non-hot) path.
103
+ enableV8CompileCache(projectRoot);
98
104
  installGlobals();
99
105
  // RNTL 13+ auto-registers matchers through the global expect when imported.
100
106
  // Expose Vitest's expect only when the consumer has not enabled globals.
@@ -116,6 +122,19 @@ if (!globalThis.__vitest_native_loader_registered) {
116
122
  data: { projectRoot, platform, reactNativeVersion, transformPkgs, presetExports, assetExts },
117
123
  });
118
124
  }
125
+ // Serve React Native from the precompiled registry when the plugin produced one
126
+ // (see registry.mjs). Installed BEFORE the require hooks so their preset-mock
127
+ // redirect wraps this one and keeps precedence. Any module the registry cannot
128
+ // serve — a computed require, a package in `transform` — falls through to the
129
+ // hooks below, so this is purely a faster path to the same modules.
130
+ if (process.env.VITEST_NATIVE_RN_REGISTRY) {
131
+ const installed = installRegistry(process.env.VITEST_NATIVE_RN_REGISTRY, projectRoot);
132
+ if (diagnostics) {
133
+ console.log(
134
+ `[vitest-native] (native) precompiled RN registry ${installed ? "installed" : "unavailable; using per-file module loading"}`,
135
+ );
136
+ }
137
+ }
119
138
  installRequireHooks(projectRoot, transformPkgs, platform, reactNativeVersion, assetExts);
120
139
 
121
140
  // Build the mock objects now that the require hooks are installed (preset
@@ -221,6 +240,31 @@ try {
221
240
  }
222
241
  }
223
242
 
243
+ // --- RNTL 14: register RCTVirtualText as a text host ---
244
+ // RNTL 14 reconciles with `test-renderer`, which enforces that string children
245
+ // live under a "text" host component (the names in RNTL's HOST_TEXT_NAMES) and
246
+ // otherwise throws "Text strings must be rendered within a <Text> component".
247
+ // Real RN renders a NESTED <Text> as the host "RCTVirtualText", which RNTL's list
248
+ // (['Text', 'RCTText']) omits — so any composite/nested <Text> crashes under the
249
+ // native engine. (Jest's preset never hits this: it mocks Text to a single flat
250
+ // "Text" host, hiding the real RCTText/RCTVirtualText split.) Add RCTVirtualText so
251
+ // nested text reconciles and getByText matches across nested <Text>, matching how
252
+ // RN actually renders. The helper is a leaf module (no RNTL main-module init), so
253
+ // requiring it here is free of the evaluation-order hazards noted in the hot-reset
254
+ // block. Gated on the list existing: a no-op for RNTL <=13 and the mock engine.
255
+ try {
256
+ const hcn = req("@testing-library/react-native/dist/helpers/host-component-names");
257
+ if (Array.isArray(hcn?.HOST_TEXT_NAMES) && !hcn.HOST_TEXT_NAMES.includes("RCTVirtualText")) {
258
+ hcn.HOST_TEXT_NAMES.push("RCTVirtualText");
259
+ }
260
+ } catch (e) {
261
+ if (diagnostics) {
262
+ console.log(
263
+ `[vitest-native] (native) could not register RCTVirtualText text host: ${e?.message}`,
264
+ );
265
+ }
266
+ }
267
+
224
268
  expect.extend(animatedMatchers);
225
269
  expect.addSnapshotSerializer(rnSerializer);
226
270
 
@@ -2,27 +2,67 @@
2
2
  // (the only transformer that lowers RN's `component` syntax). Used by BOTH the loader
3
3
  // hook (import) and the require hook, which run in separate threads: each gets its own
4
4
  // instance of this module, so the in-memory `mem` cache below is per-thread (no shared
5
- // mutable state to race on). The disk cache — keyed by path + mtime + size + preset
6
- // version — is the layer shared across them.
5
+ // mutable state to race on). The disk cache — keyed by CONTENT hash + platform, in a
6
+ // directory versioned by preset + @babel/core versions — is the layer shared across
7
+ // threads, workers, runs, and (because content-keyed entries survive fresh installs
8
+ // and mtime normalization) CI cache restores. The path is part of the key too —
9
+ // Babel output embeds the filename — so restores are valid wherever the checkout
10
+ // path is stable (CI runners use a fixed workspace path).
11
+ //
12
+ // @babel/core itself is loaded lazily, only on a cache MISS: on a warm cache the
13
+ // default engine pays this module's init in every isolated worker, and requiring
14
+ // Babel costs ~35ms vs ~0.5ms for resolving versions — pure waste when every file
15
+ // is served from disk.
7
16
  import { createRequire } from "node:module";
8
17
  import path from "node:path";
9
18
  import fs from "node:fs";
10
19
  import os from "node:os";
11
20
  import crypto from "node:crypto";
21
+ import { decorateTransformError } from "./explain.mjs";
12
22
 
23
+ let _req;
13
24
  let _babel;
14
25
  let _preset;
15
26
  let _cacheDir;
16
27
  let _writeSeq = 0;
17
28
  const mem = new Map();
18
- const TRANSFORM_CACHE_VERSION = 2;
29
+ const TRANSFORM_CACHE_VERSION = 3;
30
+
31
+ /**
32
+ * Root directory for vitest-native's on-disk caches. Prefers the project's
33
+ * node_modules/.cache — persistent across runs, per-project, and restorable by
34
+ * standard CI dependency-cache actions (unlike os.tmpdir(), which is ephemeral
35
+ * on CI runners and periodically purged on macOS). Falls back to tmpdir when
36
+ * node_modules is absent or unwritable.
37
+ */
38
+ export function cacheRootFor(projectRoot) {
39
+ const nm = path.join(projectRoot, "node_modules");
40
+ if (fs.existsSync(nm)) {
41
+ try {
42
+ const dir = path.join(nm, ".cache", "vitest-native");
43
+ fs.mkdirSync(dir, { recursive: true });
44
+ return dir;
45
+ } catch {
46
+ // Read-only node_modules (some CI sandboxes) — fall through to tmpdir.
47
+ }
48
+ }
49
+ const dir = path.join(os.tmpdir(), "vitest-native-cache");
50
+ fs.mkdirSync(dir, { recursive: true });
51
+ return dir;
52
+ }
19
53
 
20
54
  function init(projectRoot) {
21
- if (_babel) return;
22
- const req = createRequire(path.join(projectRoot, "package.json"));
55
+ if (_cacheDir) return;
56
+ _req = createRequire(path.join(projectRoot, "package.json"));
57
+ let presetVersion;
58
+ let babelVersion;
23
59
  try {
24
- _babel = req("@babel/core");
25
- _preset = req.resolve("@react-native/babel-preset");
60
+ // Resolve-only here (cheap); the actual require of @babel/core happens
61
+ // lazily on the first cache miss.
62
+ _preset = _req.resolve("@react-native/babel-preset");
63
+ _req.resolve("@babel/core");
64
+ presetVersion = _req("@react-native/babel-preset/package.json").version;
65
+ babelVersion = _req("@babel/core/package.json").version;
26
66
  } catch {
27
67
  throw new Error(
28
68
  "[vitest-native] engine 'native' requires '@react-native/babel-preset' and " +
@@ -30,15 +70,24 @@ function init(projectRoot) {
30
70
  "(they ship with React Native projects by default).",
31
71
  );
32
72
  }
33
- const presetVersion = req("@react-native/babel-preset/package.json").version;
73
+ // Both transformer versions key the directory — a preset or Babel upgrade
74
+ // must never serve output produced by the previous version — and so does the
75
+ // Babel environment: the preset's dev-mode JSX transform produces different
76
+ // output (e.g. _jsxFileName injection) under NODE_ENV=development than under
77
+ // test/production.
78
+ const babelEnv = process.env.BABEL_ENV || process.env.NODE_ENV || "none";
34
79
  _cacheDir = path.join(
35
- os.tmpdir(),
36
- "vitest-native-cache",
37
- `${presetVersion}-v${TRANSFORM_CACHE_VERSION}`,
80
+ cacheRootFor(projectRoot),
81
+ `transform-${presetVersion}-b${babelVersion}-${babelEnv}-v${TRANSFORM_CACHE_VERSION}`,
38
82
  );
39
83
  fs.mkdirSync(_cacheDir, { recursive: true });
40
84
  }
41
85
 
86
+ /** The active transform disk-cache directory (resolved on first use). Test hook. */
87
+ export function transformCacheDir() {
88
+ return _cacheDir ?? null;
89
+ }
90
+
42
91
  /** Returns true if the source contains RN Flow syntax that must be transformed. */
43
92
  export function isFlow(src) {
44
93
  return /@flow|import typeof|\bcomponent\s+\w/.test(src);
@@ -47,6 +96,13 @@ export function isFlow(src) {
47
96
  /** Transform an RN source file to runnable CJS. Cached in-memory + on disk. */
48
97
  export function transformRN(file, src, projectRoot, platform = "ios") {
49
98
  init(projectRoot);
99
+ // The in-memory key uses mtime+size (one statSync) so the hot path skips
100
+ // hashing; the DISK key hashes the actual content, so entries stay valid
101
+ // across fresh installs, Docker mtime normalization, and CI cache restores —
102
+ // and a same-path file with different content can never produce a wrong hit.
103
+ // The FILENAME is part of the key because Babel's output depends on it: the
104
+ // preset embeds the absolute path (_jsxFileName) in transformed JSX, so two
105
+ // identical sources at different paths must not share an entry.
50
106
  const st = fs.statSync(file);
51
107
  const memKey = `${platform}\0${file}\0${st.mtimeMs}\0${st.size}`;
52
108
  const memHit = mem.get(memKey);
@@ -54,7 +110,11 @@ export function transformRN(file, src, projectRoot, platform = "ios") {
54
110
 
55
111
  const key = crypto
56
112
  .createHash("sha1")
57
- .update(platform + ":" + file + ":" + st.mtimeMs + ":" + st.size)
113
+ .update(platform)
114
+ .update("\0")
115
+ .update(file)
116
+ .update("\0")
117
+ .update(src)
58
118
  .digest("hex");
59
119
  const cachePath = path.join(_cacheDir, key + ".js");
60
120
  try {
@@ -63,13 +123,22 @@ export function transformRN(file, src, projectRoot, platform = "ios") {
63
123
  return cached;
64
124
  } catch {}
65
125
 
66
- const out = _babel.transformSync(src, {
67
- filename: file,
68
- presets: [[_preset, { disableStaticViewConfigsCodegen: true }]],
69
- babelrc: false,
70
- configFile: false,
71
- caller: { name: "metro", bundler: "metro", platform, supportsStaticESM: false },
72
- }).code;
126
+ if (!_babel) _babel = _req("@babel/core");
127
+ let out;
128
+ try {
129
+ out = _babel.transformSync(src, {
130
+ filename: file,
131
+ presets: [[_preset, { disableStaticViewConfigsCodegen: true }]],
132
+ babelrc: false,
133
+ configFile: false,
134
+ caller: { name: "metro", bundler: "metro", platform, supportsStaticESM: false },
135
+ }).code;
136
+ } catch (err) {
137
+ // Decorate here, at the single choke point, so every caller — the ESM
138
+ // loader, the CJS require hook, requireActual's .ts handlers — surfaces
139
+ // the file, platform, and owning package instead of a bare Babel stack.
140
+ throw decorateTransformError(err, file, platform);
141
+ }
73
142
  // Atomic write: multiple worker threads may transform the same RN file
74
143
  // concurrently on a cold cache. Write to a unique temp file then rename
75
144
  // (atomic on POSIX same-dir) so a concurrent reader never sees a partial file.
@@ -16,6 +16,8 @@ import { init, runBaseTests, setupEnvironment } from "vitest/worker";
16
16
  import { installGlobals } from "./globals.mjs";
17
17
  import { installRequireHooks } from "./hooks.mjs";
18
18
  import { installHotReset } from "./reset.mjs";
19
+ import { installRegistry } from "./registry.mjs";
20
+ import { enableV8CompileCache } from "./compile-cache.mjs";
19
21
 
20
22
  if (isMainThread || !parentPort) {
21
23
  throw new Error("[vitest-native] hot worker entry must run in node:worker_threads");
@@ -52,7 +54,18 @@ if (diagnostics) {
52
54
  // guarded; doing them at boot lets RN preload BEFORE the globals baseline and
53
55
  // listener tracking in reset.mjs, so RN's own boot state is preserved across
54
56
  // per-file resets rather than wrongly torn down with test pollution.
57
+ // Enable the V8 compile cache before any RN module compiles, so the resident
58
+ // graph's bytecode is cached to disk for the next worker/run.
59
+ enableV8CompileCache(projectRoot);
55
60
  installGlobals();
61
+ // The registry must be installed BEFORE the preload below, not just by the setup
62
+ // file: whichever path first resolves react-native decides which instance the
63
+ // worker keeps resident, and a preload that bypassed the registry would leave the
64
+ // worker holding a second, separate copy of RN's singletons from the one every
65
+ // test file sees.
66
+ if (process.env.VITEST_NATIVE_RN_REGISTRY) {
67
+ installRegistry(process.env.VITEST_NATIVE_RN_REGISTRY, projectRoot);
68
+ }
56
69
  installRequireHooks(projectRoot, transformPkgs, platform, reactNativeVersion, assetExts);
57
70
  try {
58
71
  const req = createRequire(path.join(projectRoot, "package.json"));
@@ -0,0 +1,117 @@
1
+ import { createRequire } from "node:module";
2
+ import path from "node:path";
3
+ import os from "node:os";
4
+ import { ThreadsPoolWorker } from "vitest/node";
5
+ //#region src/native/pool.ts
6
+ function deepEqual(a, b) {
7
+ if (a === b) return true;
8
+ if (a == null || b == null || typeof a !== "object" || typeof b !== "object") return false;
9
+ const ka = Object.keys(a);
10
+ const kb = Object.keys(b);
11
+ if (ka.length !== kb.length) return false;
12
+ return ka.every((k) => kb.includes(k) && deepEqual(a[k], b[k]));
13
+ }
14
+ var NativePoolWorker = class extends ThreadsPoolWorker {
15
+ name = "vitest-native";
16
+ reportMemory;
17
+ entrypoint;
18
+ environment;
19
+ recycleAfterFiles;
20
+ memoryLimit;
21
+ diagnostics;
22
+ filesRun = 0;
23
+ lastHeapUsed = 0;
24
+ memoryListenerAttached = false;
25
+ batchWarningShown = false;
26
+ constructor(options, native) {
27
+ super(options);
28
+ this.entrypoint = path.resolve(native.workerEntry);
29
+ this.environment = options.environment;
30
+ this.recycleAfterFiles = native.recycleAfterFiles ?? 0;
31
+ this.memoryLimit = native.memoryLimit ?? 0;
32
+ this.diagnostics = native.diagnostics ?? false;
33
+ this.reportMemory = this.memoryLimit > 0;
34
+ }
35
+ async start() {
36
+ await super.start();
37
+ if (this.reportMemory && !this.memoryListenerAttached) {
38
+ this.memoryListenerAttached = true;
39
+ this.on("message", (message) => {
40
+ if (message?.__vitest_worker_response__ && typeof message.usedMemory === "number") this.lastHeapUsed = message.usedMemory;
41
+ });
42
+ }
43
+ }
44
+ send(message) {
45
+ if (message.type === "run" || message.type === "collect") {
46
+ if (!this.batchWarningShown && message.context.files.length > 1 && (this.recycleAfterFiles > 0 || this.memoryLimit > 0)) {
47
+ this.batchWarningShown = true;
48
+ console.warn(`[vitest-native] hotRuntime recycling (memoryLimit/recycleAfterFiles) is INACTIVE here: Vitest batched ${message.context.files.length} files into one task, which happens in single-worker mode (maxWorkers: 1) — so a worker can never be retired between files and the memory bound cannot be enforced. Run with maxWorkers >= 2 (or remove maxWorkers/fileParallelism: false) so each file is its own task and recycling can fire.`);
49
+ }
50
+ this.filesRun += message.context.files.length;
51
+ }
52
+ super.send(message);
53
+ }
54
+ canReuse(task) {
55
+ if (this.recycleAfterFiles > 0 && this.filesRun >= this.recycleAfterFiles) return false;
56
+ if (this.memoryLimit > 0 && this.lastHeapUsed >= this.memoryLimit) return false;
57
+ const env = task.context.environment;
58
+ return env.name === this.environment.name && deepEqual(env.options, this.environment.options);
59
+ }
60
+ };
61
+ const HOT_MEMORY_MIN_BYTES = 768 * 1024 * 1024;
62
+ const HOT_MEMORY_MAX_BYTES = 1536 * 1024 * 1024;
63
+ const HOT_MEMORY_FRACTION = .25;
64
+ /**
65
+ * Default per-worker hot `memoryLimit` (bytes): `clamp(totalmem * 0.25, 768MB, 1.5GB)`.
66
+ * Applied only when hot is enabled and neither `memoryLimit` nor
67
+ * `recycleAfterFiles` was set explicitly. `totalmem` is injectable for tests.
68
+ */
69
+ function defaultHotMemoryLimit(totalmem = os.totalmem()) {
70
+ const budget = Math.floor(totalmem * HOT_MEMORY_FRACTION);
71
+ return Math.min(HOT_MEMORY_MAX_BYTES, Math.max(HOT_MEMORY_MIN_BYTES, budget));
72
+ }
73
+ /**
74
+ * Fail fast when the hot worker would load a different Vitest VERSION from the
75
+ * project's.
76
+ *
77
+ * The worker entry ships inside this package, so its `import 'vitest/worker'`
78
+ * resolves from THIS package's location rather than the project's. Where a monorepo
79
+ * has more than one Vitest install — a linked package, a hoisted `node_modules`,
80
+ * mixed versions across workspaces — the two can differ, and a version difference is
81
+ * invisible at runtime: the start handshake succeeds, the run request is accepted,
82
+ * and no result is ever reported. Vitest then prints "No test files found" with no
83
+ * error at all, and on some paths still exits 0 — a green run that tested nothing.
84
+ *
85
+ * Only a VERSION difference is an error. Two installs of the same version are two
86
+ * module registries but identical code, and they talk to each other perfectly well;
87
+ * failing on the paths alone would block working monorepos where the same version is
88
+ * simply installed twice.
89
+ */
90
+ function assertWorkerVitestMatchesProject(workerEntry, projectRoot) {
91
+ const resolveVitest = (from) => {
92
+ try {
93
+ const require_ = createRequire(from);
94
+ const pkgPath = require_.resolve("vitest/package.json");
95
+ return {
96
+ path: pkgPath,
97
+ version: require_(pkgPath).version
98
+ };
99
+ } catch {
100
+ return null;
101
+ }
102
+ };
103
+ const worker = resolveVitest(workerEntry);
104
+ const project = resolveVitest(path.join(projectRoot, "package.json"));
105
+ if (worker === null || project === null || worker.version === project.version) return;
106
+ throw new Error(`[vitest-native] 'hotRuntime' cannot run: its worker would load vitest@${worker.version}, but this run is driven by vitest@${project.version}. They talk over Vitest's worker protocol, and a version mismatch reports no results at all rather than failing.\n worker would load: ${worker.path}\n project resolves: ${project.path}\nThis happens when vitest-native and vitest resolve to different node_modules trees (linked packages, hoisted monorepo installs, mixed Vitest versions). Install one Vitest version reachable from vitest-native, or set 'hotRuntime: false'.`);
107
+ }
108
+ /** Pool initializer for `test.pool` — keeps RN-hot workers alive across files. */
109
+ function nativePool(options) {
110
+ assertWorkerVitestMatchesProject(path.resolve(options.workerEntry), options.projectRoot);
111
+ return {
112
+ name: "vitest-native",
113
+ createPoolWorker: (poolOptions) => new NativePoolWorker(poolOptions, options)
114
+ };
115
+ }
116
+ //#endregion
117
+ export { defaultHotMemoryLimit, nativePool };
@@ -0,0 +1,121 @@
1
+ const require_chunk = require("./chunk-CZWwpsFl.cjs");
2
+ let node_path = require("node:path");
3
+ node_path = require_chunk.__toESM(node_path, 1);
4
+ let node_module = require("node:module");
5
+ let node_os = require("node:os");
6
+ node_os = require_chunk.__toESM(node_os, 1);
7
+ let vitest_node = require("vitest/node");
8
+ //#region src/native/pool.ts
9
+ function deepEqual(a, b) {
10
+ if (a === b) return true;
11
+ if (a == null || b == null || typeof a !== "object" || typeof b !== "object") return false;
12
+ const ka = Object.keys(a);
13
+ const kb = Object.keys(b);
14
+ if (ka.length !== kb.length) return false;
15
+ return ka.every((k) => kb.includes(k) && deepEqual(a[k], b[k]));
16
+ }
17
+ var NativePoolWorker = class extends vitest_node.ThreadsPoolWorker {
18
+ name = "vitest-native";
19
+ reportMemory;
20
+ entrypoint;
21
+ environment;
22
+ recycleAfterFiles;
23
+ memoryLimit;
24
+ diagnostics;
25
+ filesRun = 0;
26
+ lastHeapUsed = 0;
27
+ memoryListenerAttached = false;
28
+ batchWarningShown = false;
29
+ constructor(options, native) {
30
+ super(options);
31
+ this.entrypoint = node_path.default.resolve(native.workerEntry);
32
+ this.environment = options.environment;
33
+ this.recycleAfterFiles = native.recycleAfterFiles ?? 0;
34
+ this.memoryLimit = native.memoryLimit ?? 0;
35
+ this.diagnostics = native.diagnostics ?? false;
36
+ this.reportMemory = this.memoryLimit > 0;
37
+ }
38
+ async start() {
39
+ await super.start();
40
+ if (this.reportMemory && !this.memoryListenerAttached) {
41
+ this.memoryListenerAttached = true;
42
+ this.on("message", (message) => {
43
+ if (message?.__vitest_worker_response__ && typeof message.usedMemory === "number") this.lastHeapUsed = message.usedMemory;
44
+ });
45
+ }
46
+ }
47
+ send(message) {
48
+ if (message.type === "run" || message.type === "collect") {
49
+ if (!this.batchWarningShown && message.context.files.length > 1 && (this.recycleAfterFiles > 0 || this.memoryLimit > 0)) {
50
+ this.batchWarningShown = true;
51
+ console.warn(`[vitest-native] hotRuntime recycling (memoryLimit/recycleAfterFiles) is INACTIVE here: Vitest batched ${message.context.files.length} files into one task, which happens in single-worker mode (maxWorkers: 1) — so a worker can never be retired between files and the memory bound cannot be enforced. Run with maxWorkers >= 2 (or remove maxWorkers/fileParallelism: false) so each file is its own task and recycling can fire.`);
52
+ }
53
+ this.filesRun += message.context.files.length;
54
+ }
55
+ super.send(message);
56
+ }
57
+ canReuse(task) {
58
+ if (this.recycleAfterFiles > 0 && this.filesRun >= this.recycleAfterFiles) return false;
59
+ if (this.memoryLimit > 0 && this.lastHeapUsed >= this.memoryLimit) return false;
60
+ const env = task.context.environment;
61
+ return env.name === this.environment.name && deepEqual(env.options, this.environment.options);
62
+ }
63
+ };
64
+ const HOT_MEMORY_MIN_BYTES = 768 * 1024 * 1024;
65
+ const HOT_MEMORY_MAX_BYTES = 1536 * 1024 * 1024;
66
+ const HOT_MEMORY_FRACTION = .25;
67
+ /**
68
+ * Default per-worker hot `memoryLimit` (bytes): `clamp(totalmem * 0.25, 768MB, 1.5GB)`.
69
+ * Applied only when hot is enabled and neither `memoryLimit` nor
70
+ * `recycleAfterFiles` was set explicitly. `totalmem` is injectable for tests.
71
+ */
72
+ function defaultHotMemoryLimit(totalmem = node_os.default.totalmem()) {
73
+ const budget = Math.floor(totalmem * HOT_MEMORY_FRACTION);
74
+ return Math.min(HOT_MEMORY_MAX_BYTES, Math.max(HOT_MEMORY_MIN_BYTES, budget));
75
+ }
76
+ /**
77
+ * Fail fast when the hot worker would load a different Vitest VERSION from the
78
+ * project's.
79
+ *
80
+ * The worker entry ships inside this package, so its `import 'vitest/worker'`
81
+ * resolves from THIS package's location rather than the project's. Where a monorepo
82
+ * has more than one Vitest install — a linked package, a hoisted `node_modules`,
83
+ * mixed versions across workspaces — the two can differ, and a version difference is
84
+ * invisible at runtime: the start handshake succeeds, the run request is accepted,
85
+ * and no result is ever reported. Vitest then prints "No test files found" with no
86
+ * error at all, and on some paths still exits 0 — a green run that tested nothing.
87
+ *
88
+ * Only a VERSION difference is an error. Two installs of the same version are two
89
+ * module registries but identical code, and they talk to each other perfectly well;
90
+ * failing on the paths alone would block working monorepos where the same version is
91
+ * simply installed twice.
92
+ */
93
+ function assertWorkerVitestMatchesProject(workerEntry, projectRoot) {
94
+ const resolveVitest = (from) => {
95
+ try {
96
+ const require_ = (0, node_module.createRequire)(from);
97
+ const pkgPath = require_.resolve("vitest/package.json");
98
+ return {
99
+ path: pkgPath,
100
+ version: require_(pkgPath).version
101
+ };
102
+ } catch {
103
+ return null;
104
+ }
105
+ };
106
+ const worker = resolveVitest(workerEntry);
107
+ const project = resolveVitest(node_path.default.join(projectRoot, "package.json"));
108
+ if (worker === null || project === null || worker.version === project.version) return;
109
+ throw new Error(`[vitest-native] 'hotRuntime' cannot run: its worker would load vitest@${worker.version}, but this run is driven by vitest@${project.version}. They talk over Vitest's worker protocol, and a version mismatch reports no results at all rather than failing.\n worker would load: ${worker.path}\n project resolves: ${project.path}\nThis happens when vitest-native and vitest resolve to different node_modules trees (linked packages, hoisted monorepo installs, mixed Vitest versions). Install one Vitest version reachable from vitest-native, or set 'hotRuntime: false'.`);
110
+ }
111
+ /** Pool initializer for `test.pool` — keeps RN-hot workers alive across files. */
112
+ function nativePool(options) {
113
+ assertWorkerVitestMatchesProject(node_path.default.resolve(options.workerEntry), options.projectRoot);
114
+ return {
115
+ name: "vitest-native",
116
+ createPoolWorker: (poolOptions) => new NativePoolWorker(poolOptions, options)
117
+ };
118
+ }
119
+ //#endregion
120
+ exports.defaultHotMemoryLimit = defaultHotMemoryLimit;
121
+ exports.nativePool = nativePool;
@@ -5,6 +5,7 @@
5
5
  */
6
6
  const AUTO_DETECT_PRESETS = {
7
7
  "react-native-reanimated": "reanimated",
8
+ "react-native-worklets": "worklets",
8
9
  "react-native-gesture-handler": "gestureHandler",
9
10
  "react-native-safe-area-context": "safeAreaContext",
10
11
  "@react-navigation/native": "navigation",
@@ -20,7 +21,10 @@ const AUTO_DETECT_PRESETS = {
20
21
  "react-native-svg": "svg",
21
22
  "react-native-webview": "webview",
22
23
  "@react-native-vector-icons/common": "vectorIcons",
23
- "react-native-vector-icons": "vectorIcons"
24
+ "react-native-vector-icons": "vectorIcons",
25
+ "@shopify/flash-list": "flashList",
26
+ "@gorhom/bottom-sheet": "bottomSheet",
27
+ "react-native-keyboard-controller": "keyboardController"
24
28
  };
25
29
  //#endregion
26
30
  Object.defineProperty(exports, "AUTO_DETECT_PRESETS", {
@@ -5,6 +5,7 @@
5
5
  */
6
6
  const AUTO_DETECT_PRESETS = {
7
7
  "react-native-reanimated": "reanimated",
8
+ "react-native-worklets": "worklets",
8
9
  "react-native-gesture-handler": "gestureHandler",
9
10
  "react-native-safe-area-context": "safeAreaContext",
10
11
  "@react-navigation/native": "navigation",
@@ -20,7 +21,10 @@ const AUTO_DETECT_PRESETS = {
20
21
  "react-native-svg": "svg",
21
22
  "react-native-webview": "webview",
22
23
  "@react-native-vector-icons/common": "vectorIcons",
23
- "react-native-vector-icons": "vectorIcons"
24
+ "react-native-vector-icons": "vectorIcons",
25
+ "@shopify/flash-list": "flashList",
26
+ "@gorhom/bottom-sheet": "bottomSheet",
27
+ "react-native-keyboard-controller": "keyboardController"
24
28
  };
25
29
  //#endregion
26
30
  export { AUTO_DETECT_PRESETS as t };