Open History to see the last commit
1import { type ChildProcess as ChildProcessHandle, spawn, spawnSync } from "node:child_process";
2
3export interface ProcessRunOptions {
4 cwd?: string | undefined;
5 timeoutMs?: number | undefined;
6 env?: NodeJS.ProcessEnv | undefined;
7 stdin?: string | undefined;
8 allowNonZeroExit?: boolean | undefined;
9 maxBufferBytes?: number | undefined;
10 outputMode?: "error" | "truncate" | undefined;
11}
12
13export interface ProcessRunResult {
14 stdout: string;
15 stderr: string;
16 code: number | null;
17 signal: NodeJS.Signals | null;
18 timedOut: boolean;
19 stdoutTruncated?: boolean | undefined;
20 stderrTruncated?: boolean | undefined;
21}
22
23function commandLabel(command: string, args: readonly string[]): string {
24 return [command, ...args].join(" ");
25}
26
27function normalizeSpawnError(command: string, args: readonly string[], error: unknown): Error {
28 if (!(error instanceof Error)) {
29 return new Error(`Failed to run ${commandLabel(command, args)}.`);
30 }
31
32 const maybeCode = (error as NodeJS.ErrnoException).code;
33 if (maybeCode === "ENOENT") {
34 return new Error(`Command not found: ${command}`);
35 }
36
37 return new Error(`Failed to run ${commandLabel(command, args)}: ${error.message}`);
38}
39
40function isWindowsCommandNotFound(code: number | null, stderr: string): boolean {
41 if (process.platform !== "win32") return false;
42 if (code === 9009) return true;
43 return /is not recognized as an internal or external command/i.test(stderr);
44}
45
46function normalizeExitError(
47 command: string,
48 args: readonly string[],
49 result: ProcessRunResult,
50): Error {
51 if (isWindowsCommandNotFound(result.code, result.stderr)) {
52 return new Error(`Command not found: ${command}`);
53 }
54
55 const reason = result.timedOut
56 ? "timed out"
57 : `failed (code=${result.code ?? "null"}, signal=${result.signal ?? "null"})`;
58 const stderr = result.stderr.trim();
59 const detail = stderr.length > 0 ? ` ${stderr}` : "";
60 return new Error(`${commandLabel(command, args)} ${reason}.${detail}`);
61}
62
63function normalizeStdinError(command: string, args: readonly string[], error: unknown): Error {
64 if (!(error instanceof Error)) {
65 return new Error(`Failed to write stdin for ${commandLabel(command, args)}.`);
66 }
67 return new Error(`Failed to write stdin for ${commandLabel(command, args)}: ${error.message}`);
68}
69
70function normalizeBufferError(
71 command: string,
72 args: readonly string[],
73 stream: "stdout" | "stderr",
74 maxBufferBytes: number,
75): Error {
76 return new Error(
77 `${commandLabel(command, args)} exceeded ${stream} buffer limit (${maxBufferBytes} bytes).`,
78 );
79}
80
81const DEFAULT_MAX_BUFFER_BYTES = 8 * 1024 * 1024;
82
83/**
84 * On Windows with `shell: true`, `child.kill()` only terminates the `cmd.exe`
85 * wrapper, leaving the actual command running. Use `taskkill /T` to kill the
86 * entire process tree instead.
87 */
88function killChild(child: ChildProcessHandle, signal: NodeJS.Signals = "SIGTERM"): void {
89 if (process.platform === "win32" && child.pid !== undefined) {
90 try {
91 spawnSync("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" });
92 return;
93 } catch {
94 // fallback to direct kill
95 }
96 }
97 child.kill(signal);
98}
99
100function appendChunkWithinLimit(
101 target: string,
102 currentBytes: number,
103 chunk: Buffer,
104 maxBytes: number,
105): {
106 next: string;
107 nextBytes: number;
108 truncated: boolean;
109} {
110 const remaining = maxBytes - currentBytes;
111 if (remaining <= 0) {
112 return { next: target, nextBytes: currentBytes, truncated: true };
113 }
114 if (chunk.length <= remaining) {
115 return {
116 next: `${target}${chunk.toString()}`,
117 nextBytes: currentBytes + chunk.length,
118 truncated: false,
119 };
120 }
121 return {
122 next: `${target}${chunk.subarray(0, remaining).toString()}`,
123 nextBytes: currentBytes + remaining,
124 truncated: true,
125 };
126}
127
128export async function runProcess(
129 command: string,
130 args: readonly string[],
131 options: ProcessRunOptions = {},
132): Promise<ProcessRunResult> {
133 const timeoutMs = options.timeoutMs ?? 60_000;
134 const maxBufferBytes = options.maxBufferBytes ?? DEFAULT_MAX_BUFFER_BYTES;
135 const outputMode = options.outputMode ?? "error";
136
137 return new Promise<ProcessRunResult>((resolve, reject) => {
138 const child = spawn(command, args, {
139 cwd: options.cwd,
140 env: options.env,
141 stdio: "pipe",
142 shell: process.platform === "win32",
143 });
144
145 let stdout = "";
146 let stderr = "";
147 let stdoutBytes = 0;
148 let stderrBytes = 0;
149 let stdoutTruncated = false;
150 let stderrTruncated = false;
151 let timedOut = false;
152 let settled = false;
153 let forceKillTimer: ReturnType<typeof setTimeout> | null = null;
154
155 const timeoutTimer = setTimeout(() => {
156 timedOut = true;
157 killChild(child, "SIGTERM");
158 forceKillTimer = setTimeout(() => {
159 killChild(child, "SIGKILL");
160 }, 1_000);
161 }, timeoutMs);
162
163 const finalize = (callback: () => void): void => {
164 if (settled) return;
165 settled = true;
166 clearTimeout(timeoutTimer);
167 if (forceKillTimer) {
168 clearTimeout(forceKillTimer);
169 }
170 callback();
171 };
172
173 const fail = (error: Error): void => {
174 killChild(child, "SIGTERM");
175 finalize(() => {
176 reject(error);
177 });
178 };
179
180 const appendOutput = (stream: "stdout" | "stderr", chunk: Buffer | string): Error | null => {
181 const chunkBuffer = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
182 const text = chunkBuffer.toString();
183 const byteLength = chunkBuffer.length;
184 if (stream === "stdout") {
185 if (outputMode === "truncate") {
186 const appended = appendChunkWithinLimit(stdout, stdoutBytes, chunkBuffer, maxBufferBytes);
187 stdout = appended.next;
188 stdoutBytes = appended.nextBytes;
189 stdoutTruncated = stdoutTruncated || appended.truncated;
190 return null;
191 }
192 stdout += text;
193 stdoutBytes += byteLength;
194 if (stdoutBytes > maxBufferBytes) {
195 return normalizeBufferError(command, args, "stdout", maxBufferBytes);
196 }
197 } else {
198 if (outputMode === "truncate") {
199 const appended = appendChunkWithinLimit(stderr, stderrBytes, chunkBuffer, maxBufferBytes);
200 stderr = appended.next;
201 stderrBytes = appended.nextBytes;
202 stderrTruncated = stderrTruncated || appended.truncated;
203 return null;
204 }
205 stderr += text;
206 stderrBytes += byteLength;
207 if (stderrBytes > maxBufferBytes) {
208 return normalizeBufferError(command, args, "stderr", maxBufferBytes);
209 }
210 }
211 return null;
212 };
213
214 child.stdout.on("data", (chunk: Buffer | string) => {
215 const error = appendOutput("stdout", chunk);
216 if (error) {
217 fail(error);
218 }
219 });
220
221 child.stderr.on("data", (chunk: Buffer | string) => {
222 const error = appendOutput("stderr", chunk);
223 if (error) {
224 fail(error);
225 }
226 });
227
228 child.once("error", (error) => {
229 finalize(() => {
230 reject(normalizeSpawnError(command, args, error));
231 });
232 });
233
234 child.once("close", (code, signal) => {
235 const result: ProcessRunResult = {
236 stdout,
237 stderr,
238 code,
239 signal,
240 timedOut,
241 stdoutTruncated,
242 stderrTruncated,
243 };
244
245 finalize(() => {
246 if (!options.allowNonZeroExit && (timedOut || (code !== null && code !== 0))) {
247 reject(normalizeExitError(command, args, result));
248 return;
249 }
250 resolve(result);
251 });
252 });
253
254 child.stdin.once("error", (error) => {
255 fail(normalizeStdinError(command, args, error));
256 });
257
258 if (options.stdin !== undefined) {
259 child.stdin.write(options.stdin, (error) => {
260 if (error) {
261 fail(normalizeStdinError(command, args, error));
262 return;
263 }
264 child.stdin.end();
265 });
266 return;
267 }
268 child.stdin.end();
269 });
270}