/** * VerifyExecutor — 受控的 npm 脚本执行器。 * * 这是 KCode 中唯一允许执行 "npm run {script}" 的位置。 * 其他模块禁止直接 import child_process,必须通过本模块执行验证命令。 * * 设计决策: * - 集中执行点:所有 npm 脚本执行统一经过此处,便于审计和安全策略。 * - 同步执行:使用 spawnSync 阻塞等待结果,确保验证完成后再继续。 * - 跨平台兼容:Windows 使用 "npm.cmd",其他平台使用 "npm"。 * - 超时控制:默认 120 秒超时,防止长时间阻塞。 */ import { spawnSync } from "node:child_process"; /** 验证脚本执行结果。 */ export interface VerifyExecutionResult { /** 执行的命令(如 "npm run build")。 */ command: string; /** 进程退出码。 */ exitCode: number; /** 标准输出。 */ stdout: string; /** 标准错误。 */ stderr: string; } /** * 同步执行 npm 脚本。仅允许 "npm run {script}" 形式的命令。 * * @param cwd - 工作目录 * @param script - npm 脚本名称(如 "build", "test") * @param timeout - 超时毫秒数(默认 120 秒) * @returns 执行结果,包含退出码和输出 */ export function executeVerifyScript( cwd: string, script: string, timeout = 120_000, ): VerifyExecutionResult { // 跨平台:Windows 需要使用 "npm.cmd",其他平台直接使用 "npm" const npmCommand = process.platform === "win32" ? "npm.cmd" : "npm"; // shell: false 防止命令注入;encoding: "utf8" 确保输出为字符串 const result = spawnSync(npmCommand, ["run", script], { cwd, encoding: "utf8", shell: false, timeout, }); return { command: `npm run ${script}`, exitCode: result.status ?? 1, stdout: result.stdout?.toString() ?? "", stderr: result.stderr?.toString() ?? "", }; }