import { spawn } from 'node:child_process' export type CommandResult = { code: number | null signal: NodeJS.Signals | null stdout: string stderr: string durationMs: number timedOut: boolean } export function runCommand( command: string, args: string[], options: { cwd: string env?: Record timeoutMs: number stdinText?: string }, ): Promise { return new Promise(resolve => { const startedAt = performance.now() const child = spawn(command, args, { cwd: options.cwd, env: { ...process.env, ...options.env, }, stdio: 'pipe', windowsHide: true, }) let stdout = '' let stderr = '' let timedOut = false child.stdout.on('data', chunk => { stdout += String(chunk) }) child.stderr.on('data', chunk => { stderr += String(chunk) }) if (options.stdinText !== undefined) { child.stdin.write(options.stdinText) } child.stdin.end() const timer = setTimeout(() => { timedOut = true child.kill() }, options.timeoutMs) child.on('close', (code, signal) => { clearTimeout(timer) resolve({ code, signal, stdout, stderr, durationMs: performance.now() - startedAt, timedOut, }) }) }) }