vitest-native 0.14.1 → 0.15.0-rc.2

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 (89) hide show
  1. package/README.md +11 -10
  2. package/dist/cli.d.mts +9 -1
  3. package/dist/cli.mjs +2609 -361
  4. package/dist/context.d.mts +19 -0
  5. package/dist/context.mjs +47 -1
  6. package/dist/docs-url.d.mts +4 -0
  7. package/dist/docs-url.mjs +9 -0
  8. package/dist/errors.d.mts +21 -1
  9. package/dist/hang-watch-setup.mjs +55 -0
  10. package/dist/hang-watch.d.mts +56 -0
  11. package/dist/hang-watch.mjs +343 -0
  12. package/dist/helpers.cjs +24 -53
  13. package/dist/helpers.mjs +22 -1
  14. package/dist/host-D0r3P_T1.mjs +1985 -0
  15. package/dist/{index-aNBCTfA5.d.mts → index-JOR602XU.d.mts} +105 -2
  16. package/dist/index.d.mts +2 -1
  17. package/dist/index.mjs +723 -149
  18. package/dist/jest-compat/aliases.d.mts +1 -0
  19. package/dist/jest-compat/aliases.mjs +11 -0
  20. package/dist/jest-compat/interop.mjs +1 -1
  21. package/dist/jest-compat/jest-object.mjs +23 -5
  22. package/dist/jest-compat/node-registry.mjs +836 -68
  23. package/dist/jest-compat/setup.mjs +205 -12
  24. package/dist/jest-compat.cjs +383 -47
  25. package/dist/jest-compat.d.cts +19 -2
  26. package/dist/jest-compat.d.mts +19 -2
  27. package/dist/jest-compat.mjs +232 -47
  28. package/dist/matchers.d.cts +0 -1
  29. package/dist/matchers.d.mts +0 -1
  30. package/dist/native/assets.mjs +3 -1
  31. package/dist/native/babel-caller.d.mts +13 -0
  32. package/dist/native/babel-caller.mjs +24 -0
  33. package/dist/native/babel-toolchain.mjs +27 -3
  34. package/dist/native/boundary.mjs +45 -8
  35. package/dist/native/bounded-process.mjs +63 -5
  36. package/dist/native/bridge-client.mjs +133 -0
  37. package/dist/native/bridge-server.mjs +215 -0
  38. package/dist/native/bridge-thread.mjs +79 -0
  39. package/dist/native/bridge.mjs +512 -0
  40. package/dist/native/compile-error.mjs +120 -0
  41. package/dist/native/explain.mjs +3 -2
  42. package/dist/native/expo-module-mocks.mjs +2 -0
  43. package/dist/native/export-condition-recovery.mjs +20 -99
  44. package/dist/native/hooks.mjs +256 -133
  45. package/dist/native/jest-resolvers.mjs +94 -0
  46. package/dist/native/library-jest.mjs +352 -0
  47. package/dist/native/loader.mjs +167 -73
  48. package/dist/native/match.mjs +67 -7
  49. package/dist/native/module-reset.mjs +44 -49
  50. package/dist/native/ownership-ledger.d.mts +87 -0
  51. package/dist/native/ownership-ledger.mjs +524 -0
  52. package/dist/native/ownership.d.mts +20 -0
  53. package/dist/native/ownership.mjs +114 -0
  54. package/dist/native/registry-compiler.mjs +39 -5
  55. package/dist/native/registry-process.mjs +327 -28
  56. package/dist/native/registry.mjs +752 -200
  57. package/dist/native/resident-health.mjs +1 -0
  58. package/dist/native/resolve.d.mts +7 -0
  59. package/dist/native/resolve.mjs +119 -4
  60. package/dist/native/rntl-hooks.mjs +9 -5
  61. package/dist/native/rntl-text-host.mjs +5 -15
  62. package/dist/native/root-spelling.d.mts +6 -0
  63. package/dist/native/root-spelling.mjs +77 -0
  64. package/dist/native/runner.mjs +2 -19
  65. package/dist/native/setup.mjs +119 -38
  66. package/dist/native/shared-resolver.d.mts +141 -0
  67. package/dist/native/shared-resolver.mjs +719 -0
  68. package/dist/native/test-runner.mjs +26 -0
  69. package/dist/native/transform.mjs +18 -22
  70. package/dist/native/worker.mjs +9 -4
  71. package/dist/node-dispatch.mjs +293 -0
  72. package/dist/{preset-map-CogjYmSw.mjs → preset-map-DdAexIwz.mjs} +113 -2
  73. package/dist/{presets-CXDyg51l.mjs → presets-_EaSw29m.mjs} +710 -130
  74. package/dist/presets.d.mts +1 -1
  75. package/dist/presets.mjs +1 -1
  76. package/dist/rntl-matchers.d.ts +11 -15
  77. package/dist/rntl-support.mjs +28 -13
  78. package/dist/root-mocks-BNXeosbR.mjs +155 -0
  79. package/dist/serializer.cjs +7 -5
  80. package/dist/serializer.d.cts +7 -5
  81. package/dist/serializer.d.mts +7 -5
  82. package/dist/serializer.mjs +7 -5
  83. package/dist/setup.mjs +26 -27
  84. package/docs/migrating-from-jest.md +9 -232
  85. package/docs/migrating-from-vitest-react-native.md +4 -4
  86. package/docs/release-readiness.md +9 -11
  87. package/docs/versioning.md +38 -9
  88. package/package.json +59 -33
  89. package/dist/host-BAAAlSkO.mjs +0 -1028
@@ -17,19 +17,35 @@ export interface ProjectContextFields {
17
17
  sourceMaps?: boolean;
18
18
  hotReleaseGenerations?: boolean;
19
19
  registry?: string;
20
+ /** A registry compiling in the background on a cache miss (see activeRegistry). */
21
+ registryPending?: { file: string; since: number };
22
+ /** The library registry layered on `registry` (registry.mjs, buildLibraryRegistry). */
23
+ libraryRegistry?: string;
20
24
  ownership?: Record<string, unknown>;
25
+ /** Each Node-transformed package's directory, resolved from `root` at config time. */
26
+ packageDirs?: { root: string; dirs: Record<string, string | null> };
27
+ ownershipGuard?: { mode: "warn" | "error"; allow: { path: string; reason: string }[] };
21
28
  projectDirs?: string[];
22
29
  requireAliases?: [string, string][];
30
+ /** The project sets test.restoreMocks: jest-compat restores jest.replaceProperty() before each test. */
31
+ restoreMocks?: true;
23
32
  requireAliasesSkipped?: string[];
24
33
  presetNames?: string[];
34
+ /** experimental.nodeMocks: a `vi.mock` applies to the modules Node loads. */
35
+ nodeMocks?: true;
25
36
  presetConfig?: Record<string, Record<string, unknown>>;
26
37
  presetExports?: Record<string, string[] | null>;
27
38
  presetModules?: string[];
28
39
  presetDisabled?: string[];
40
+ librarySetupFiles?: string[];
29
41
  mocks?: unknown;
30
42
  knownNativeModules?: string[];
31
43
  nativeModuleSpecs?: Record<string, string[]>;
32
44
  nativeModules?: "permissive";
45
+ /** experimental.ownershipModel (ADR-0004/0005): absent unless the project opts in. */
46
+ ownershipModel?: "resolver" | "resolution";
47
+ resolverInputs?: import("./native/shared-resolver.mjs").ResolverInputs;
48
+ resolverInputsHash?: string;
33
49
  /** The supported Expo SDKs, `[minimum, maximum]` (checkLoadedExpoSdk). */
34
50
  expoSdks?: [number, number];
35
51
  }
@@ -41,5 +57,8 @@ export declare function writeProjectContext(
41
57
  export declare function ensureProjectContext(ref: string, fields: ProjectContextFields): string;
42
58
  export declare function projectContext(ref?: string): Readonly<ProjectContextFields> | null;
43
59
  export declare function requireProjectContext(ref?: string): Readonly<ProjectContextFields>;
60
+ export declare function activeRegistry(
61
+ context: Readonly<ProjectContextFields> | null,
62
+ ): string | null;
44
63
  export declare function markBootContext(ref?: string): void;
45
64
  export declare function assertBootContext(ref?: string): void;
package/dist/context.mjs CHANGED
@@ -14,7 +14,6 @@ export const CONTEXT_VERSION = 1;
14
14
 
15
15
  /** Hand-set diagnostic switches that stay environment variables. */
16
16
  export const ESCAPE_HATCHES = Object.freeze([
17
- "VITEST_NATIVE_LOADER_THREAD",
18
17
  "VITEST_NATIVE_NO_REGISTRY",
19
18
  "VITEST_NATIVE_HOT_ESM_GEN",
20
19
  "VITEST_NATIVE_HOT_STATE_MUTATION",
@@ -38,7 +37,19 @@ const SCHEMA = {
38
37
  sourceMaps: { valid: (v) => typeof v === "boolean" },
39
38
  hotReleaseGenerations: { valid: (v) => typeof v === "boolean" },
40
39
  registry: { valid: absolute },
40
+ registryPending: {
41
+ valid: (v) => object(v) && absolute(v.file) && typeof v.since === "number",
42
+ },
43
+ libraryRegistry: { valid: absolute },
41
44
  ownership: { valid: object },
45
+ packageDirs: {
46
+ valid: (v) =>
47
+ object(v) &&
48
+ absolute(v.root) &&
49
+ object(v.dirs) &&
50
+ Object.values(v.dirs).every((dir) => dir === null || absolute(dir)),
51
+ },
52
+ ownershipGuard: { valid: object },
42
53
  projectDirs: { valid: strings },
43
54
  requireAliases: {
44
55
  valid: (v) =>
@@ -46,14 +57,21 @@ const SCHEMA = {
46
57
  },
47
58
  requireAliasesSkipped: { valid: strings },
48
59
  presetNames: { valid: strings },
60
+ nodeMocks: { valid: (v) => v === true },
61
+ restoreMocks: { valid: (v) => v === true },
49
62
  presetConfig: { valid: object },
50
63
  presetExports: { valid: object },
51
64
  presetModules: { valid: strings },
52
65
  presetDisabled: { valid: strings },
66
+ librarySetupFiles: { valid: strings },
53
67
  mocks: { valid: (v) => v !== undefined },
54
68
  knownNativeModules: { valid: strings },
55
69
  nativeModuleSpecs: { valid: object },
56
70
  nativeModules: { valid: (v) => v === "permissive" },
71
+ // experimental.ownershipModel (ADR-0004/0005): absent unless the project opts in.
72
+ ownershipModel: { valid: (v) => v === "resolver" || v === "resolution" },
73
+ resolverInputs: { valid: object },
74
+ resolverInputsHash: { valid: (v) => typeof v === "string" },
57
75
  expoSdks: {
58
76
  valid: (v) => Array.isArray(v) && v.length === 2 && v.every((n) => Number.isInteger(n)),
59
77
  },
@@ -221,6 +239,34 @@ export function requireProjectContext(ref = process.env[CONTEXT_ENV]) {
221
239
 
222
240
  const HANDLE = Symbol.for("vitest-native");
223
241
 
242
+ /**
243
+ * The precompiled React Native registry this realm uses, or null for per-file loading.
244
+ *
245
+ * `registry` is a registry the plugin found warm. `registryPending` is one it started
246
+ * compiling in the background on a cache miss (registry-process.mjs): a realm that
247
+ * starts after the compiler published it uses it, one that starts before keeps loading
248
+ * React Native file by file. The metadata file is published last, so a change in its
249
+ * mtime from `since` means a complete registry is in place; the worker loads it like
250
+ * any other and falls back to per-file loading if it cannot.
251
+ *
252
+ * Decided once per realm and shared by every module instance in it, so the setup file
253
+ * and the jest-compat registry agree, and a realm that loaded React Native file by file
254
+ * never switches to the registry's second copy of it partway through.
255
+ */
256
+ export function activeRegistry(context) {
257
+ if (!context) return null;
258
+ if (context.registry) return context.registry;
259
+ const pending = context.registryPending;
260
+ if (!pending) return null;
261
+ const decisions = ((globalThis[HANDLE] ??= {}).registryDecisions ??= new Map());
262
+ if (decisions.has(pending.file)) return decisions.get(pending.file);
263
+ const meta = fs.statSync(`${pending.file}.json`, { throwIfNoEntry: false });
264
+ const file =
265
+ meta && meta.mtimeMs !== pending.since && fs.existsSync(pending.file) ? pending.file : null;
266
+ decisions.set(pending.file, file);
267
+ return file;
268
+ }
269
+
224
270
  /** Hot worker boot: record the project this worker serves. */
225
271
  export function markBootContext(ref = process.env[CONTEXT_ENV]) {
226
272
  (globalThis[HANDLE] ??= {}).bootContext = ref;
@@ -0,0 +1,4 @@
1
+ /** The documentation site's address, without a trailing slash. */
2
+ export declare const SITE_URL: string;
3
+ /** An absolute link to a page of the site, from its path: `docsUrl("/guide/errors#INVALID_OPTION")`. */
4
+ export declare function docsUrl(path: string): string;
@@ -0,0 +1,9 @@
1
+ // The documentation site's address. Every link vitest-native prints, and the site's own
2
+ // config, read it from here, so the site can move by changing one line; the old address
3
+ // keeps redirecting, because released versions print it.
4
+ export const SITE_URL = "https://danfry1.github.io/vitest-native";
5
+
6
+ /** An absolute link to a page of the site, from its path: `docsUrl("/guide/errors#INVALID_OPTION")`. */
7
+ export function docsUrl(path) {
8
+ return `${SITE_URL}${path}`;
9
+ }
package/dist/errors.d.mts CHANGED
@@ -11,11 +11,24 @@ export type VitestNativeErrorCode =
11
11
  | "INVALID_OPTION"
12
12
  | "UNKNOWN_OPTION"
13
13
  | "UNSUPPORTED_PEER"
14
+ | "UNSUPPORTED_NODE"
14
15
  | "VITEST_TWIN_INSTANCE"
15
16
  | "CONTEXT_INVALID"
17
+ | "RESOLVER_INPUT_MISMATCH"
18
+ | "RESOLVER_INPUTS_MISSING"
19
+ | "RESOLVER_ERROR"
20
+ | "BRIDGE_UNAVAILABLE"
21
+ | "BRIDGE_FILE_REFUSED"
22
+ | "VITE_FETCH_TIMEOUT"
23
+ | "VITE_FETCH_FAILED"
24
+ | "BRIDGE_CONTRACT_CHANGED"
25
+ | "REQUIRE_OF_ASYNC_VITE_MODULE"
26
+ | "REQUIRE_OF_EVALUATING_VITE_MODULE"
27
+ | "BRIDGED_EVALUATION_FAILED"
16
28
  | "UNSUPPORTED_POOL"
17
29
  | "INLINE_BREAKS_OWNERSHIP"
18
30
  | "MODULE_OWNER_CONFLICT"
31
+ | "SOURCE_EVALUATED_TWICE"
19
32
  | "ENGINE_REQUIRES_BABEL"
20
33
  | "MOCKS_REQUIRE_MOCK_ENGINE"
21
34
  | "METRO_CONFIG_LOAD_FAILED"
@@ -33,6 +46,9 @@ export type VitestNativeErrorCode =
33
46
  | "HOT_STATE_CAPTURE_FAILED"
34
47
  | "HOT_STATE_RESTORE_FAILED"
35
48
  | "HOT_CJS_CACHE_RESET"
49
+ | "HOT_RESIDENT_UNUSABLE"
50
+ | "HOT_FILE_NOT_RUN"
51
+ | "PROJECT_BABEL_COMMONJS"
36
52
  | "PRESET_UNAVAILABLE"
37
53
  | "PRESET_NOT_PREPARED"
38
54
  | "WRONG_ENGINE_FOR_HELPER"
@@ -42,8 +58,12 @@ export type VitestNativeErrorCode =
42
58
  | "JEST_MOCK_FACTORY_CYCLE"
43
59
  | "JEST_COMPAT_SETUP_MISSING"
44
60
  | "BABEL_IGNORES_FILE"
61
+ | "LIBRARY_REGISTRY_FAILED"
62
+ | "UNKNOWN_DISPATCH_STEP"
63
+ | "MOCK_NOT_SEEN_BY_NODE"
45
64
  | "IMPORT_META_IN_NODE_OWNED"
46
- | "MATCHER_BAD_RECEIVER";
65
+ | "MATCHER_BAD_RECEIVER"
66
+ | "COMPARE_REPORT_INVALID";
47
67
 
48
68
  export interface VitestNativeErrorOptions {
49
69
  cause?: unknown;
@@ -0,0 +1,55 @@
1
+ // hangTimeout, the worker side: before each test, record which test is starting and how
2
+ // long it may legitimately take, in a per-worker file the main process reads when it
3
+ // sees no progress (hang-watch.mjs).
4
+ //
5
+ // The record is written synchronously, before the test body runs. A worker reports a
6
+ // test's start to the main process in batches, asynchronously, so one that then sticks in
7
+ // synchronous code never sends it; this file is on disk regardless.
8
+ //
9
+ // The test's own limits come from the test itself: its `timeout` (an `it(name, fn, ms)`
10
+ // or `{ timeout }` option, or `vi.setConfig({ testTimeout })`), and the hook timeout for
11
+ // the hooks around it. Each retry runs this hook again, so each attempt gets its own record.
12
+ //
13
+ // Added to the run's setup files by the plugin only while the watch is on; the records
14
+ // directory and the hook timeout come from the plugin through Vitest's provide/inject.
15
+ import fs from "node:fs";
16
+ import inspector from "node:inspector";
17
+ import path from "node:path";
18
+ import { threadId } from "node:worker_threads";
19
+ import { beforeEach, inject } from "vitest";
20
+
21
+ const watch = inject("vitestNativeHangWatch");
22
+
23
+ /** "outer > inner > test", as Vitest's reporters name a test. */
24
+ function fullName(task) {
25
+ const names = [];
26
+ for (let at = task; at && at.type !== "file" && at.name !== undefined; at = at.suite) {
27
+ if (at.type === "suite" && at.suite === undefined) break; // the file's root suite
28
+ names.unshift(at.name);
29
+ }
30
+ return names.join(" > ");
31
+ }
32
+
33
+ if (watch?.dir) {
34
+ const file = path.join(watch.dir, `${process.pid}-${threadId}.json`);
35
+ beforeEach((context) => {
36
+ const task = context.task;
37
+ try {
38
+ fs.writeFileSync(
39
+ file,
40
+ JSON.stringify({
41
+ file: task.file?.filepath ?? null,
42
+ test: fullName(task),
43
+ at: Date.now(),
44
+ // The runner resolves it at collection: the test's own, its describe's, or testTimeout.
45
+ timeout: task.timeout ?? 5000,
46
+ hookTimeout: watch.hookTimeout,
47
+ debugger: Boolean(inspector.url()),
48
+ }),
49
+ );
50
+ } catch (error) {
51
+ // The watch then names the file only; the test itself is unaffected.
52
+ process.stderr.write(`[vitest-native] hangTimeout could not record a test start: ${error}\n`);
53
+ }
54
+ });
55
+ }
@@ -0,0 +1,56 @@
1
+ export declare const DEFAULT_HANG_TIMEOUT: number;
2
+ export declare const MAX_HANG_TIMEOUT: number;
3
+ export declare function hangTimeoutFor(
4
+ option: number | false | undefined,
5
+ timeouts?: { testTimeout?: number; hookTimeout?: number },
6
+ ): number | null;
7
+ export declare function debugging(
8
+ configs?: readonly (
9
+ | { inspect?: unknown; inspectBrk?: unknown; execArgv?: readonly string[] }
10
+ | undefined
11
+ )[],
12
+ execArgv?: readonly string[],
13
+ inspectorUrl?: string,
14
+ ): boolean;
15
+ export declare function descendantsOf(pid: number): number[];
16
+ export interface HangTestRecord {
17
+ file: string | null;
18
+ test: string;
19
+ at: number;
20
+ timeout?: number;
21
+ hookTimeout?: number;
22
+ debugger?: boolean;
23
+ }
24
+ export declare function testBudget(record: HangTestRecord): number;
25
+ export declare function readTestRecords(dir: string | undefined): Map<string, HangTestRecord>;
26
+ export declare function runByCli(argv?: readonly string[]): boolean;
27
+ export declare function exitKillingDescendants(code: number): never;
28
+ export declare class HangWatch {
29
+ constructor(options: {
30
+ timeoutMs: number | null;
31
+ recordsDir?: string;
32
+ exit?: (code: number) => void;
33
+ write?: (text: string) => void;
34
+ now?: () => number;
35
+ cli?: boolean;
36
+ graceMs?: number;
37
+ });
38
+ timeoutMs: number | null;
39
+ readonly recordsDir: string | undefined;
40
+ active: boolean;
41
+ off: boolean;
42
+ readonly running: Map<string, string | null>;
43
+ contribute(say?: { off?: boolean; active?: boolean; limit?: number | null }): void;
44
+ watching(): boolean;
45
+ onInit(vitest: unknown): void;
46
+ onTestRunStart(): void;
47
+ onTestModuleQueued(testModule: { moduleId: string }): void;
48
+ onTestModuleStart(testModule: { moduleId: string }): void;
49
+ onTestCaseReady(testCase: { module: { moduleId: string }; fullName: string }): void;
50
+ onTestCaseResult(testCase: { module: { moduleId: string }; fullName: string }): void;
51
+ onTestModuleEnd(testModule: { moduleId: string }): void;
52
+ onTestRunEnd(): void;
53
+ check(): void;
54
+ report(records?: Map<string, HangTestRecord>): string[];
55
+ trip(records?: Map<string, HangTestRecord>): Promise<void>;
56
+ }
@@ -0,0 +1,343 @@
1
+ // `hangTimeout`: fail a run whose tests stop making progress, naming what was running.
2
+ //
3
+ // Vitest's `testTimeout` and `hookTimeout` are timers on the test's own worker. A test
4
+ // stuck in synchronous code (a `while` loop that never ends, a wrapper that re-enters the
5
+ // collection it is iterating) never yields to that worker's event loop, so those timers
6
+ // never fire, and the run waits forever with nothing on screen. The worker's thread or
7
+ // process is the only thing stuck: Vitest's main process, where reporters run, stays
8
+ // responsive. This reporter, added by the plugin, notices that while test files are in
9
+ // flight, none has been queued, started or finished, and no test has started or finished,
10
+ // for `hangTimeout` milliseconds. It then prints the files and tests that were running and
11
+ // ends the process with exit code 1.
12
+ //
13
+ // It watches only while files are in flight: from a worker taking a file to the last file
14
+ // ending. Global setup, coverage, and typecheck mode's compiler run send no test events and
15
+ // are outside that window, so a long one is not mistaken for a hang.
16
+ //
17
+ // A stuck worker cannot be stopped politely (Vitest would wait for it), so v1 fails the
18
+ // whole run rather than only that file, and kills this process's descendants on the way
19
+ // out: a forked worker (Vitest's default pool) would otherwise spin on after the run.
20
+ import { spawnSync } from "node:child_process";
21
+ import fs from "node:fs";
22
+ import path from "node:path";
23
+
24
+ /** The default no-progress limit when `hangTimeout` is not set. */
25
+ export const DEFAULT_HANG_TIMEOUT = 60_000;
26
+ /** Node's longest timer: a longer delay fires after 1 ms instead. */
27
+ export const MAX_HANG_TIMEOUT = 2_147_483_647;
28
+
29
+ /**
30
+ * The limit to use: the option if set, otherwise the larger of the default and twice the
31
+ * longest per-test or per-hook timeout, so a project that allows slow tests is not cut
32
+ * short. Null (the watch off) for `false` or 0, and when that limit is not a finite timer
33
+ * delay: `testTimeout: Infinity` means "never time out", and so does the watch.
34
+ */
35
+ export function hangTimeoutFor(option, { testTimeout = 5000, hookTimeout = 10000 } = {}) {
36
+ if (option === false || option === 0) return null;
37
+ const limit =
38
+ typeof option === "number"
39
+ ? option
40
+ : Math.max(DEFAULT_HANG_TIMEOUT, 2 * Math.max(testTimeout ?? 0, hookTimeout ?? 0));
41
+ return Number.isFinite(limit) && limit > 0 && limit <= MAX_HANG_TIMEOUT ? limit : null;
42
+ }
43
+
44
+ const INSPECT_FLAG = /^--inspect(-brk|-wait)?(=|$)/;
45
+
46
+ /**
47
+ * Whether a debugger is (or will be) attached: a test paused at a breakpoint makes no
48
+ * progress either, and must not be failed for it. Checks Vitest's inspect options and the
49
+ * flags it passes to workers (`execArgv`) in each config, this process's flags, and an
50
+ * open inspector.
51
+ */
52
+ export function debugging(configs = [], execArgv = process.execArgv, inspectorUrl) {
53
+ for (const config of configs) {
54
+ if (!config) continue;
55
+ if (config.inspect || config.inspectBrk) return true;
56
+ if ((config.execArgv ?? []).some((arg) => INSPECT_FLAG.test(arg))) return true;
57
+ }
58
+ if (execArgv.some((arg) => INSPECT_FLAG.test(arg))) return true;
59
+ return Boolean(inspectorUrl);
60
+ }
61
+
62
+ /** The direct children of `pid`. */
63
+ function childrenOf(pid) {
64
+ if (process.platform === "win32") {
65
+ const out = spawnSync(
66
+ "powershell.exe",
67
+ [
68
+ "-NoProfile",
69
+ "-Command",
70
+ `(Get-CimInstance Win32_Process -Filter 'ParentProcessId=${pid}').ProcessId`,
71
+ ],
72
+ { encoding: "utf8", windowsHide: true },
73
+ );
74
+ return out.error ? [] : out.stdout.split(/\s+/).filter(Boolean).map(Number);
75
+ }
76
+ const out = spawnSync("pgrep", ["-P", String(pid)], { encoding: "utf8" });
77
+ if (!out.error && (out.status === 0 || out.status === 1)) {
78
+ return out.stdout.split("\n").filter(Boolean).map(Number);
79
+ }
80
+ // No pgrep: read parent ids from /proc (Linux).
81
+ try {
82
+ return fs
83
+ .readdirSync("/proc")
84
+ .filter((entry) => /^\d+$/.test(entry))
85
+ .filter((entry) => {
86
+ try {
87
+ const stat = fs.readFileSync(`/proc/${entry}/stat`, "utf8");
88
+ return Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1]) === pid;
89
+ } catch {
90
+ return false;
91
+ }
92
+ })
93
+ .map(Number);
94
+ } catch {
95
+ return [];
96
+ }
97
+ }
98
+
99
+ /** Every live descendant of `pid`. */
100
+ export function descendantsOf(pid) {
101
+ const found = [];
102
+ const queue = [pid];
103
+ while (queue.length > 0) {
104
+ for (const child of childrenOf(queue.shift())) {
105
+ found.push(child);
106
+ queue.push(child);
107
+ }
108
+ }
109
+ return found;
110
+ }
111
+
112
+ /**
113
+ * Stop every process this one started, then exit with `code`. A forked test worker stuck
114
+ * in a loop does not end with its parent: left alone it spins forever. On Windows each
115
+ * child's tree goes through taskkill and this process then exits normally, so its exit
116
+ * handlers (the terminal renderer's flush among them) still run.
117
+ */
118
+ export function exitKillingDescendants(code) {
119
+ if (process.platform === "win32") {
120
+ for (const pid of childrenOf(process.pid)) {
121
+ spawnSync("taskkill", ["/F", "/T", "/PID", String(pid)], {
122
+ stdio: "ignore",
123
+ windowsHide: true,
124
+ });
125
+ }
126
+ } else {
127
+ for (const pid of descendantsOf(process.pid)) {
128
+ try {
129
+ process.kill(pid, "SIGKILL");
130
+ } catch (error) {
131
+ // ESRCH: it exited on its own meanwhile. Anything else is worth knowing about.
132
+ if (error?.code !== "ESRCH")
133
+ fs.writeSync(2, `[vitest-native] could not stop process ${pid}: ${error}\n`);
134
+ }
135
+ }
136
+ }
137
+ process.exit(code);
138
+ }
139
+
140
+ /** How long a recorded test may legitimately run: its timeout, plus its hooks and slack. */
141
+ export function testBudget(record) {
142
+ return (record.timeout ?? 5000) + 2 * (record.hookTimeout ?? 10000) + 1000;
143
+ }
144
+
145
+ /** The latest record per test file, from the workers' files in `dir` (hang-watch-setup.mjs). */
146
+ export function readTestRecords(dir) {
147
+ const byFile = new Map();
148
+ // Created by the main process before any worker starts (plugin.ts, watchForHangs).
149
+ if (!dir || !fs.existsSync(dir)) return byFile;
150
+ /** Records caught mid-write: the next check reads them whole. */
151
+ const unreadable = [];
152
+ for (const entry of fs.readdirSync(dir)) {
153
+ let record;
154
+ try {
155
+ record = JSON.parse(fs.readFileSync(path.join(dir, entry), "utf8"));
156
+ } catch (error) {
157
+ unreadable.push({ entry, error });
158
+ continue;
159
+ }
160
+ if (!record?.file) continue;
161
+ const seen = byFile.get(record.file);
162
+ if (!seen || seen.at < record.at) byFile.set(record.file, record);
163
+ }
164
+ byFile.unreadable = unreadable;
165
+ return byFile;
166
+ }
167
+
168
+ /** Whether this process is Vitest's own CLI, which may be ended, rather than a host using its API. */
169
+ export function runByCli(argv = process.argv) {
170
+ return /(^|[\\/])vitest(\.m?js)?$/.test(argv[1] ?? "");
171
+ }
172
+
173
+ export class HangWatch {
174
+ constructor({
175
+ timeoutMs,
176
+ recordsDir,
177
+ exit = exitKillingDescendants,
178
+ // Straight to the file descriptor: Vitest's terminal renderer buffers writes to
179
+ // process.stderr, and the process may end right after this.
180
+ write = (text) => fs.writeSync(2, text),
181
+ now = () => Date.now(),
182
+ cli = runByCli(),
183
+ graceMs = 5000,
184
+ }) {
185
+ this.timeoutMs = timeoutMs ?? null;
186
+ this.recordsDir = recordsDir;
187
+ /** On only if some project turned it on and none turned it off (contribute). */
188
+ this.active = timeoutMs !== undefined && timeoutMs !== null;
189
+ this.off = false;
190
+ this.exit = exit;
191
+ this.write = write;
192
+ this.now = now;
193
+ this.cli = cli;
194
+ this.graceMs = graceMs;
195
+ /** Test file → the test running in it, or null if none has reported starting. */
196
+ this.running = new Map();
197
+ this.timer = undefined;
198
+ this.vitest = undefined;
199
+ }
200
+
201
+ onInit(vitest) {
202
+ this.vitest = vitest;
203
+ }
204
+
205
+ /**
206
+ * One project's say for this run, from each project's plugin:
207
+ * - `off` (`hangTimeout: false`) turns the watch off for the whole run;
208
+ * - `active` (a limit was set, or the project runs on the hot runtime) turns it on;
209
+ * - the longest limit wins, so no project is cut shorter than it asked.
210
+ */
211
+ contribute({ off = false, active = false, limit = null } = {}) {
212
+ if (off) this.off = true;
213
+ if (active) this.active = true;
214
+ if (limit !== null) this.timeoutMs = Math.max(this.timeoutMs ?? 0, limit);
215
+ }
216
+
217
+ /** Whether this run is watched at all. */
218
+ watching() {
219
+ return this.active && !this.off && this.timeoutMs !== null;
220
+ }
221
+
222
+ onTestRunStart() {
223
+ this.running.clear();
224
+ this.disarm();
225
+ }
226
+
227
+ onTestModuleQueued(testModule) {
228
+ // A worker took the file: its imports and collection are in flight from here.
229
+ if (!this.running.has(testModule.moduleId)) this.running.set(testModule.moduleId, null);
230
+ this.progress();
231
+ }
232
+
233
+ onTestModuleStart(testModule) {
234
+ if (!this.running.has(testModule.moduleId)) this.running.set(testModule.moduleId, null);
235
+ this.progress();
236
+ }
237
+
238
+ onTestCaseReady(testCase) {
239
+ this.running.set(testCase.module.moduleId, testCase.fullName);
240
+ this.progress();
241
+ }
242
+
243
+ onTestCaseResult(testCase) {
244
+ if (this.running.get(testCase.module.moduleId) === testCase.fullName) {
245
+ this.running.set(testCase.module.moduleId, null);
246
+ }
247
+ this.progress();
248
+ }
249
+
250
+ onTestModuleEnd(testModule) {
251
+ this.running.delete(testModule.moduleId);
252
+ this.progress();
253
+ }
254
+
255
+ onTestRunEnd() {
256
+ // Watch mode waits here for the next change: that is not a hang.
257
+ this.running.clear();
258
+ this.disarm();
259
+ }
260
+
261
+ /** Restart the limit while any file is in flight; otherwise stop watching. */
262
+ progress() {
263
+ this.disarm();
264
+ if (!this.watching() || this.running.size === 0) return;
265
+ this.arm(this.timeoutMs);
266
+ }
267
+
268
+ arm(ms) {
269
+ this.disarm();
270
+ this.timer = setTimeout(() => this.check(), ms);
271
+ this.timer.unref?.();
272
+ }
273
+
274
+ /**
275
+ * The limit passed with no progress. A test still inside its own budget (its timeout,
276
+ * retries counted per attempt, plus its hooks) or paused in a debugger is waited for,
277
+ * until that budget runs out; otherwise the run is stuck.
278
+ */
279
+ check() {
280
+ const records = readTestRecords(this.recordsDir);
281
+ let waitUntil = 0;
282
+ for (const file of this.running.keys()) {
283
+ const record = records.get(file);
284
+ if (!record) continue;
285
+ if (record.debugger) return this.arm(this.timeoutMs);
286
+ waitUntil = Math.max(waitUntil, record.at + testBudget(record));
287
+ }
288
+ const left = waitUntil - this.now();
289
+ if (left > 0) return this.arm(left);
290
+ this.trip(records);
291
+ }
292
+
293
+ disarm() {
294
+ clearTimeout(this.timer);
295
+ this.timer = undefined;
296
+ }
297
+
298
+ /** The message: what was running, and what to do. */
299
+ report(records = new Map()) {
300
+ const seconds = Math.round(this.timeoutMs / 1000);
301
+ const lines = [
302
+ `[vitest-native] No test made progress for ${seconds} s (hangTimeout), and the running tests are past their own timeouts: a test or hook is stuck in synchronous code, which testTimeout cannot interrupt.`,
303
+ ];
304
+ for (const [file, reported] of this.running) {
305
+ const test = records.get(file)?.test ?? reported;
306
+ lines.push(
307
+ test
308
+ ? ` Running: ${file} › ${test}`
309
+ : ` Running: ${file} (no test had started: the file's imports, collection or a beforeAll hook)`,
310
+ );
311
+ }
312
+ lines.push(
313
+ " The run is stopped (global teardown and output reporters such as coverage and junit do not finish). To change the limit, set reactNative({ hangTimeout }); false turns it off.",
314
+ );
315
+ return lines;
316
+ }
317
+
318
+ async trip(records = new Map()) {
319
+ const lines = this.report(records);
320
+ this.write(`${lines.join("\n")}\n`);
321
+ if (process.env.GITHUB_ACTIONS === "true") {
322
+ const where = [...this.running].map(
323
+ ([file, t]) =>
324
+ `${file}${(records.get(file)?.test ?? t) ? ` › ${records.get(file)?.test ?? t}` : ""}`,
325
+ );
326
+ this.write(`::error title=hangTimeout::No test progress; stopped. ${where.join("; ")}\n`);
327
+ }
328
+ process.exitCode = 1;
329
+ // Ask Vitest to close first (it stops its workers and runs what teardown it can),
330
+ // but not for longer than the grace period: a stuck worker can hold close() forever.
331
+ const closed = this.vitest?.close?.();
332
+ if (closed) {
333
+ await Promise.race([
334
+ closed.catch((error) =>
335
+ this.write(`[vitest-native] closing Vitest after the hang failed: ${error}\n`),
336
+ ),
337
+ new Promise((r) => setTimeout(r, this.graceMs).unref?.()),
338
+ ]);
339
+ }
340
+ // A host using Vitest's API keeps its process; only Vitest's own CLI is ended.
341
+ if (this.cli) this.exit(1);
342
+ }
343
+ }