confirmed-process.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. import { spawn } from "node:child_process";
  2. /** 按真实提示逐次确认;固定 sleep 会拖慢卸载,也可能把两个回答送进同一个 stdin.once。 */
  3. export function runConfirmedProcess(
  4. command: string,
  5. args: string[],
  6. options: { prompts: readonly string[]; answer: string; timeoutMs: number },
  7. ): Promise<{ stdout: string; stderr: string }> {
  8. return new Promise((resolve, reject) => {
  9. const child = spawn(command, args, { stdio: ["pipe", "pipe", "pipe"] });
  10. let stdout = "";
  11. let stderr = "";
  12. let confirmed = 0;
  13. let cursor = 0;
  14. const timeout = setTimeout(() => {
  15. child.kill("SIGTERM");
  16. reject(new Error(`确认进程超时:确认 ${confirmed}/${options.prompts.length}`));
  17. }, options.timeoutMs);
  18. child.stdout.setEncoding("utf8");
  19. child.stderr.setEncoding("utf8");
  20. child.stdout.on("data", (chunk: string) => {
  21. stdout += chunk;
  22. const prompt = options.prompts[confirmed];
  23. if (prompt === undefined) return;
  24. const index = stdout.indexOf(prompt, cursor);
  25. if (index < 0) return;
  26. cursor = index + prompt.length;
  27. confirmed++;
  28. // 最后一次回答后关闭输入,CLI 的 stdin 数据监听器才能自然结束。
  29. if (confirmed === options.prompts.length) child.stdin.end(`${options.answer}\n`);
  30. else child.stdin.write(`${options.answer}\n`);
  31. });
  32. child.stderr.on("data", (chunk: string) => {
  33. stderr += chunk;
  34. });
  35. child.stdin.on("error", reject);
  36. child.once("error", (error) => {
  37. clearTimeout(timeout);
  38. reject(error);
  39. });
  40. child.once("close", (code) => {
  41. clearTimeout(timeout);
  42. if (code !== 0 || confirmed !== options.prompts.length) {
  43. reject(
  44. new Error(`确认进程退出 ${code}:确认 ${confirmed}/${options.prompts.length};${stderr}`),
  45. );
  46. } else resolve({ stdout, stderr });
  47. });
  48. });
  49. }