| 50 | } |
| 51 | |
| 52 | function runCommand(command: string, args: string[], opts: RunWslOptions = {}) { |
| 53 | return new Promise<WslCommandResult>((resolve, reject) => { |
| 54 | const child = spawn(command, args, { |
| 55 | stdio: ["ignore", "pipe", "pipe"], |
| 56 | windowsHide: true, |
| 57 | signal: opts.signal, |
| 58 | }) |
| 59 | |
| 60 | // Guard every wsl.exe invocation with a timeout. When the distro or |
| 61 | // the LXSS service is wedged (Ubuntu first-run state, Windows update |
| 62 | // pending, etc.) wsl.exe produces no output and never exits; without |
| 63 | // this the whole sidecar spawn flow stalls the app forever. |
| 64 | const timeoutMs = opts.timeoutMs ?? DEFAULT_WSL_TIMEOUT_MS |
| 65 | const timeoutId = setTimeout(() => { |
| 66 | try { |
| 67 | child.kill() |
| 68 | } catch { |
| 69 | /* ignore */ |
| 70 | } |
| 71 | reject(new Error(`${command} ${args.join(" ")} timed out after ${timeoutMs}ms`)) |
| 72 | }, timeoutMs) |
| 73 | |
| 74 | let stdout = "" |
| 75 | let stderr = "" |
| 76 | const stdoutDecoder = createOutputDecoder() |
| 77 | const stderrDecoder = createOutputDecoder() |
| 78 | |
| 79 | const append = (stream: WslCommandLine["stream"], chunk: string) => { |
| 80 | if (!chunk) return |
| 81 | if (stream === "stdout") { |
| 82 | stdout += chunk |
| 83 | return |
| 84 | } |
| 85 | stderr += chunk |
| 86 | } |
| 87 | |
| 88 | child.stdout.on("data", (chunk: Buffer) => { |
| 89 | append("stdout", stdoutDecoder.decode(chunk)) |
| 90 | }) |
| 91 | child.stdout.on("end", () => { |
| 92 | append("stdout", stdoutDecoder.flush()) |
| 93 | }) |
| 94 | |
| 95 | child.stderr.on("data", (chunk: Buffer) => { |
| 96 | append("stderr", stderrDecoder.decode(chunk)) |
| 97 | }) |
| 98 | child.stderr.on("end", () => { |
| 99 | append("stderr", stderrDecoder.flush()) |
| 100 | }) |
| 101 | |
| 102 | child.once("error", (error) => { |
| 103 | clearTimeout(timeoutId) |
| 104 | reject(error) |
| 105 | }) |
| 106 | child.once("close", (code, signal) => { |
| 107 | clearTimeout(timeoutId) |
| 108 | resolve({ code, signal, stdout, stderr }) |
| 109 | }) |