windows-shell.mjs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. import { spawn, execFile } from 'node:child_process'
  2. import { join } from 'node:path'
  3. export function powershellArguments(command) {
  4. const script = `[Console]::InputEncoding = [Console]::OutputEncoding = $OutputEncoding = New-Object System.Text.UTF8Encoding($false)\n$global:LASTEXITCODE = 0\ntry {\n& {\n${command}\n}\n$ok = $?\nif ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }\nif (-not $ok) { exit 1 }\n} catch { [Console]::Error.WriteLine($_.ToString()); exit 1 }`
  5. return ['-NoLogo', '-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')]
  6. }
  7. /** Bound both output streams, and terminate the owned process tree before
  8. * resolving a timeout or authorization cancellation. Never spawn a shell. */
  9. export function windowsShell(shell, command, { cwd, timeout, signal, limit = 512 * 1024 }) {
  10. return new Promise(resolve => {
  11. let child, timer, stopping, timedOut = false, cancelled = false, finished = false
  12. const output = { stdout: [], stderr: [] }, sizes = { stdout: 0, stderr: 0 }
  13. const capture = (key, bytes) => {
  14. const kept = bytes.subarray(0, Math.max(0, limit - sizes[key]))
  15. output[key].push(kept); sizes[key] += kept.length
  16. }
  17. const finish = async (code, error) => {
  18. if (finished) return
  19. finished = true; clearTimeout(timer); signal?.removeEventListener('abort', abort)
  20. await stopping
  21. if (error) capture('stderr', Buffer.from(error.message))
  22. resolve({ command, exitCode: timedOut || cancelled || error ? 1 : code ?? 1, timedOut,
  23. ...(cancelled ? { cancelled: true } : {}),
  24. stdout: Buffer.concat(output.stdout).toString('utf8'), stderr: Buffer.concat(output.stderr).toString('utf8') })
  25. }
  26. const stop = () => {
  27. if (stopping || finished || !child?.pid) return
  28. stopping = new Promise(done => {
  29. execFile(join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'taskkill.exe'),
  30. ['/PID', String(child.pid), '/T', '/F'], { windowsHide: true, timeout: 10000 }, () => {
  31. // The process may already have exited while taskkill was starting.
  32. if (child.exitCode === null) child.kill()
  33. done()
  34. })
  35. })
  36. }
  37. const abort = () => { cancelled = true; stop() }
  38. if (signal?.aborted) { cancelled = true; void finish(1); return }
  39. try {
  40. child = spawn(shell, powershellArguments(command), { cwd, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, TERM: 'dumb' } })
  41. child.stdout.on('data', bytes => capture('stdout', bytes))
  42. child.stderr.on('data', bytes => capture('stderr', bytes))
  43. child.once('error', error => { void finish(1, error) })
  44. child.once('close', code => { void finish(code) })
  45. signal?.addEventListener('abort', abort, { once: true })
  46. timer = setTimeout(() => { timedOut = true; stop() }, timeout)
  47. } catch (error) { void finish(1, error) }
  48. })
  49. }