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