-
-
Notifications
You must be signed in to change notification settings - Fork 80.7k
Expand file tree
/
Copy pathone-shot-exit.ts
More file actions
70 lines (61 loc) · 1.85 KB
/
Copy pathone-shot-exit.ts
File metadata and controls
70 lines (61 loc) · 1.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import type { RuntimeEnv } from "../runtime.js";
import { defaultRuntime } from "../runtime.js";
type VitestWorkerMarkers = {
tinypoolState?: unknown;
vitestWorker?: unknown;
};
let requestedExitCode: number | undefined;
function resolveVitestWorkerMarkers(): VitestWorkerMarkers {
const processMarkers = process as NodeJS.Process & Record<string, unknown>;
const globalMarkers = globalThis as typeof globalThis & Record<string, unknown>;
return {
tinypoolState: processMarkers["__tinypool_state__"],
vitestWorker: globalMarkers["__vitest_worker__"],
};
}
function isVitestWorker(
env: NodeJS.ProcessEnv,
markers: VitestWorkerMarkers = resolveVitestWorkerMarkers(),
): boolean {
const hasVitestEnv =
env.VITEST === "true" ||
env.VITEST === "1" ||
env.VITEST_POOL_ID !== undefined ||
env.VITEST_WORKER_ID !== undefined;
return (
hasVitestEnv && (markers.tinypoolState !== undefined || markers.vitestWorker !== undefined)
);
}
export function requestExitAfterOneShotOutput(
runtime: RuntimeEnv = defaultRuntime,
exitCode = 0,
): boolean {
if (runtime !== defaultRuntime) {
return false;
}
requestedExitCode = exitCode;
return true;
}
export function flushExitAfterOneShotOutput(
runtime: RuntimeEnv = defaultRuntime,
env: NodeJS.ProcessEnv = process.env,
markers: VitestWorkerMarkers = resolveVitestWorkerMarkers(),
): void {
const exitCode = requestedExitCode;
requestedExitCode = undefined;
if (exitCode === undefined || runtime !== defaultRuntime || isVitestWorker(env, markers)) {
return;
}
const exit = () => runtime.exit(exitCode);
let pendingStreams = 2;
const drain = (stream: NodeJS.WriteStream) => {
stream.write("", () => {
pendingStreams -= 1;
if (pendingStreams === 0) {
setImmediate(exit);
}
});
};
drain(process.stdout);
drain(process.stderr);
}