import { assert } from "../../_util/assert.ts";import { EventEmitter } from "../events.ts";import { os } from "../internal_binding/constants.ts";import { notImplemented } from "../_utils.ts";import { Readable, Stream, Writable } from "../stream.ts";import { deferred } from "../../async/deferred.ts";import { isWindows } from "../../_util/os.ts";import { nextTick } from "../_next_tick.ts";import { AbortError, ERR_INVALID_ARG_TYPE, ERR_INVALID_ARG_VALUE, ERR_UNKNOWN_SIGNAL,} from "./errors.ts";import { mapValues } from "../../collections/map_values.ts";import { Buffer } from "../buffer.ts";import { errnoException } from "./errors.ts";import { ErrnoException } from "../_global.d.ts";import { codeMap } from "../internal_binding/uv.ts";import { isInt32, validateBoolean, validateObject, validateString,} from "./validators.mjs";import { ArrayIsArray, ArrayPrototypeFilter, ArrayPrototypeJoin, ArrayPrototypePush, ArrayPrototypeSlice, ArrayPrototypeSort, ArrayPrototypeUnshift, ObjectPrototypeHasOwnProperty, StringPrototypeToUpperCase,} from "./primordials.mjs";import { kEmptyObject } from "./util.mjs";import { getValidatedPath } from "./fs/utils.mjs";import process from "../process.ts";
type NodeStdio = "pipe" | "overlapped" | "ignore" | "inherit" | "ipc";type DenoStdio = "inherit" | "piped" | "null";
export function stdioStringToArray( stdio: NodeStdio, channel: NodeStdio | number,) { const options: (NodeStdio | number)[] = [];
switch (stdio) { case "ignore": case "overlapped": case "pipe": options.push(stdio, stdio, stdio); break; case "inherit": options.push(stdio, stdio, stdio); break; default: throw new ERR_INVALID_ARG_VALUE("stdio", stdio); }
if (channel) options.push(channel);
return options;}
export class ChildProcess extends EventEmitter { exitCode: number | null = null;
killed = false;
pid!: number;
signalCode: string | null = null;
spawnargs: string[];
spawnfile: string;
stdin: Writable | null = null;
stdout: Readable | null = null;
stderr: Readable | null = null;
stdio: [Writable | null, Readable | null, Readable | null] = [ null, null, null, ];
#process!: Deno.Child; #spawned = deferred<void>();
constructor( command: string, args?: string[], options?: ChildProcessOptions, ) { super();
const { env = {}, stdio = ["pipe", "pipe", "pipe"], cwd, shell = false, signal, } = options || {}; const [ stdin = "pipe", stdout = "pipe", stderr = "pipe", _channel, ] = normalizeStdioOption(stdio); const [cmd, cmdArgs] = buildCommand( command, args || [], shell, ); this.spawnfile = cmd; this.spawnargs = [cmd, ...cmdArgs];
const stringEnv = mapValues(env, (value) => value.toString());
try { this.#process = Deno.spawnChild(cmd, { args: cmdArgs, cwd, env: stringEnv, stdin: toDenoStdio(stdin as NodeStdio | number), stdout: toDenoStdio(stdout as NodeStdio | number), stderr: toDenoStdio(stderr as NodeStdio | number), }); this.pid = this.#process.pid;
if (stdin === "pipe") { assert(this.#process.stdin); this.stdin = Writable.fromWeb(this.#process.stdin); }
if (stdout === "pipe") { assert(this.#process.stdout); this.stdout = Readable.fromWeb(this.#process.stdout); }
if (stderr === "pipe") { assert(this.#process.stderr); this.stderr = Readable.fromWeb(this.#process.stderr); }
this.stdio[0] = this.stdin; this.stdio[1] = this.stdout; this.stdio[2] = this.stderr;
nextTick(() => { this.emit("spawn"); this.#spawned.resolve(); });
if (signal) { const onAbortListener = () => { try { if (this.kill("SIGKILL")) { this.emit("error", new AbortError()); } } catch (err) { this.emit("error", err); } }; if (signal.aborted) { nextTick(onAbortListener); } else { signal.addEventListener("abort", onAbortListener, { once: true }); this.addListener( "exit", () => signal.removeEventListener("abort", onAbortListener), ); } }
(async () => { const status = await this.#process.status; this.exitCode = status.code; this.#spawned.then(async () => { const exitCode = this.signalCode == null ? this.exitCode : null; const signalCode = this.signalCode == null ? null : this.signalCode; this.emit("exit", exitCode, signalCode); await this.#_waitForChildStreamsToClose(); this.#closePipes(); this.emit("close", exitCode, signalCode); }); })(); } catch (err) { this.#_handleError(err); } }
kill(signal?: number | string): boolean { if (this.killed) { return this.killed; }
const denoSignal = signal == null ? "SIGTERM" : toDenoSignal(signal); this.#closePipes(); try { this.#process.kill(denoSignal); } catch (err) { const alreadyClosed = err instanceof TypeError || err instanceof Deno.errors.PermissionDenied; if (!alreadyClosed) { throw err; } } this.killed = true; this.signalCode = denoSignal; return this.killed; }
ref() { this.#process.ref(); }
unref() { this.#process.unref(); }
async #_waitForChildStreamsToClose() { const promises = [] as Array<Promise<void>>; if (this.stdin && !this.stdin.destroyed) { assert(this.stdin); this.stdin.destroy(); promises.push(waitForStreamToClose(this.stdin)); } if (this.stdout && !this.stdout.destroyed) { promises.push(waitForReadableToClose(this.stdout)); } if (this.stderr && !this.stderr.destroyed) { promises.push(waitForReadableToClose(this.stderr)); } await Promise.all(promises); }
#_handleError(err: unknown) { nextTick(() => { this.emit("error", err); }); }
#closePipes() { if (this.stdin) { assert(this.stdin); this.stdin.destroy(); } }}
const supportedNodeStdioTypes: NodeStdio[] = ["pipe", "ignore", "inherit"];function toDenoStdio( pipe: NodeStdio | number | Stream | null | undefined,): DenoStdio { if ( !supportedNodeStdioTypes.includes(pipe as NodeStdio) || typeof pipe === "number" || pipe instanceof Stream ) { notImplemented(`toDenoStdio pipe=${typeof pipe} (${pipe})`); } switch (pipe) { case "pipe": case undefined: case null: return "piped"; case "ignore": return "null"; case "inherit": return "inherit"; default: notImplemented(`toDenoStdio pipe=${typeof pipe} (${pipe})`); }}
function toDenoSignal(signal: number | string): Deno.Signal { if (typeof signal === "number") { for (const name of keys(os.signals)) { if (os.signals[name] === signal) { return name as Deno.Signal; } } throw new ERR_UNKNOWN_SIGNAL(String(signal)); }
const denoSignal = signal as Deno.Signal; if (os.signals[denoSignal] != null) { return denoSignal; } throw new ERR_UNKNOWN_SIGNAL(signal);}
function keys<T extends Record<string, unknown>>(object: T): Array<keyof T> { return Object.keys(object);}
export interface ChildProcessOptions { cwd?: string;
env?: Record<string, string | number | boolean>;
stdio?: Array<NodeStdio | number | Stream | null | undefined> | NodeStdio;
detached?: boolean;
uid?: number;
gid?: number;
argv0?: string;
shell?: string | boolean;
signal?: AbortSignal;
serialization?: "json" | "advanced";
windowsVerbatimArguments?: boolean;
windowsHide?: boolean;}
function copyProcessEnvToEnv( env: Record<string, string | undefined>, name: string, optionEnv?: Record<string, string>,) { if ( Deno.env.get(name) && (!optionEnv || !ObjectPrototypeHasOwnProperty(optionEnv, name)) ) { env[name] = Deno.env.get(name); }}
function normalizeStdioOption( stdio: Array<NodeStdio | number | null | undefined | Stream> | NodeStdio = [ "pipe", "pipe", "pipe", ],) { if (Array.isArray(stdio)) { return stdio; } else { switch (stdio) { case "overlapped": if (isWindows) { notImplemented("normalizeStdioOption overlapped (on windows)"); } return ["pipe", "pipe", "pipe"]; case "pipe": return ["pipe", "pipe", "pipe"]; case "inherit": return ["inherit", "inherit", "inherit"]; case "ignore": return ["ignore", "ignore", "ignore"]; default: notImplemented(`normalizeStdioOption stdio=${typeof stdio} (${stdio})`); } }}
export function normalizeSpawnArguments( file: string, args: string[], options: SpawnSyncOptions,) { validateString(file, "file");
if (file.length === 0) { throw new ERR_INVALID_ARG_VALUE("file", file, "cannot be empty"); }
if (ArrayIsArray(args)) { args = ArrayPrototypeSlice(args); } else if (args == null) { args = []; } else if (typeof args !== "object") { throw new ERR_INVALID_ARG_TYPE("args", "object", args); } else { options = args; args = []; }
if (options === undefined) { options = kEmptyObject; } else { validateObject(options, "options"); }
let cwd = options.cwd;
if (cwd != null) { cwd = getValidatedPath(cwd, "options.cwd") as string; }
if (options.detached != null) { validateBoolean(options.detached, "options.detached"); }
if (options.uid != null && !isInt32(options.uid)) { throw new ERR_INVALID_ARG_TYPE("options.uid", "int32", options.uid); }
if (options.gid != null && !isInt32(options.gid)) { throw new ERR_INVALID_ARG_TYPE("options.gid", "int32", options.gid); }
if ( options.shell != null && typeof options.shell !== "boolean" && typeof options.shell !== "string" ) { throw new ERR_INVALID_ARG_TYPE( "options.shell", ["boolean", "string"], options.shell, ); }
if (options.argv0 != null) { validateString(options.argv0, "options.argv0"); }
if (options.windowsHide != null) { validateBoolean(options.windowsHide, "options.windowsHide"); }
let { windowsVerbatimArguments } = options; if (windowsVerbatimArguments != null) { validateBoolean( windowsVerbatimArguments, "options.windowsVerbatimArguments", ); }
if (options.shell) { const command = ArrayPrototypeJoin([file, ...args], " "); if (process.platform === "win32") { if (typeof options.shell === "string") { file = options.shell; } else { file = Deno.env.get("comspec") || "cmd.exe"; } if (/^(?:.*\\)?cmd(?:\.exe)?$/i.exec(file) !== null) { args = ["/d", "/s", "/c", `"${command}"`]; windowsVerbatimArguments = true; } else { args = ["-c", command]; } } else { if (typeof options.shell === "string") { file = options.shell; } else { file = "/bin/sh"; } args = ["-c", command]; } }
if (typeof options.argv0 === "string") { ArrayPrototypeUnshift(args, options.argv0); } else { ArrayPrototypeUnshift(args, file); }
const env = options.env || Deno.env.toObject(); const envPairs: string[][] = [];
copyProcessEnvToEnv(env, "NODE_V8_COVERAGE", options.env);
let envKeys: string[] = []; for (const key in env) { ArrayPrototypePush(envKeys, key); }
if (process.platform === "win32") { const sawKey = new Set(); envKeys = ArrayPrototypeFilter( ArrayPrototypeSort(envKeys), (key: string) => { const uppercaseKey = StringPrototypeToUpperCase(key); if (sawKey.has(uppercaseKey)) { return false; } sawKey.add(uppercaseKey); return true; }, ); }
for (const key of envKeys) { const value = env[key]; if (value !== undefined) { ArrayPrototypePush(envPairs, `${key}=${value}`); } }
return { ...options, args, cwd, detached: !!options.detached, envPairs, file, windowsHide: !!options.windowsHide, windowsVerbatimArguments: !!windowsVerbatimArguments, };}
function waitForReadableToClose(readable: Readable) { readable.resume(); return waitForStreamToClose(readable as unknown as Stream);}
function waitForStreamToClose(stream: Stream) { const promise = deferred<void>(); const cleanup = () => { stream.removeListener("close", onClose); stream.removeListener("error", onError); }; const onClose = () => { cleanup(); promise.resolve(); }; const onError = (err: Error) => { cleanup(); promise.reject(err); }; stream.once("close", onClose); stream.once("error", onError); return promise;}
function buildCommand( file: string, args: string[], shell: string | boolean,): [string, string[]] { if (file === Deno.execPath()) { args = toDenoArgs(args); }
if (shell) { const command = [file, ...args].join(" ");
if (isWindows) { if (typeof shell === "string") { file = shell; } else { file = Deno.env.get("comspec") || "cmd.exe"; } if (/^(?:.*\\)?cmd(?:\.exe)?$/i.test(file)) { args = ["/d", "/s", "/c", `"${command}"`]; } else { args = ["-c", command]; } } else { if (typeof shell === "string") { file = shell; } else { file = "/bin/sh"; } args = ["-c", command]; } } return [file, args];}
function _createSpawnSyncError( status: string, command: string, args: string[] = [],): ErrnoException { const error = errnoException( codeMap.get(status), "spawnSync " + command, ); error.path = command; error.spawnargs = args; return error;}
export interface SpawnSyncOptions { cwd?: string | URL; input?: string | Buffer | DataView; argv0?: string; stdio?: Array<NodeStdio | number | null | undefined | Stream> | NodeStdio; env?: Record<string, string>; uid?: number; gid?: number; timeout?: number; maxBuffer?: number; encoding?: string; shell?: boolean | string; windowsVerbatimArguments?: boolean; windowsHide?: boolean; killSignal?: string; detached?: boolean;}
export interface SpawnSyncResult { pid?: number; output?: [string | null, string | Buffer, string | Buffer]; stdout?: Buffer | string; stderr?: Buffer | string; status?: number | null; signal?: string | null; error?: Error;}
export function spawnSync( command: string, args: string[], options: SpawnSyncOptions,): SpawnSyncResult { const { env = Deno.env.toObject(), stdio = ["pipe", "pipe", "pipe"], shell = false, cwd, encoding, uid, gid, maxBuffer, } = options; const normalizedStdio = normalizeStdioOption(stdio); [command, args] = buildCommand(command, args ?? [], shell);
const result: SpawnSyncResult = {}; try { const output = Deno.spawnSync(command, { args, cwd, env, stdout: toDenoStdio(normalizedStdio[1] as NodeStdio | number), stderr: toDenoStdio(normalizedStdio[2] as NodeStdio | number), uid, gid, });
const { signal } = output; const status = signal ? null : 0; let stdout = Buffer.from(output.stdout) as string | Buffer; let stderr = Buffer.from(output.stderr) as string | Buffer;
if (stdout.length > maxBuffer! || stderr.length > maxBuffer!) { result.error = _createSpawnSyncError("ENOBUFS", command, args); }
if (encoding && encoding !== "buffer") { stdout = stdout.toString(encoding); stderr = stderr.toString(encoding); }
result.status = status; result.signal = signal; result.stdout = stdout; result.stderr = stderr; result.output = [signal, stdout, stderr]; } catch (err) { if (err instanceof Deno.errors.NotFound) { result.error = _createSpawnSyncError("ENOENT", command, args); } } return result;}
const kLongArgType = 1;const kShortArgType = 2;const kLongArg = { type: kLongArgType };const kShortArg = { type: kShortArgType };const kNodeFlagsMap = new Map([ ["--build-snapshot", kLongArg], ["-c", kShortArg], ["--check", kLongArg], ["-C", kShortArg], ["--conditions", kLongArg], ["--cpu-prof-dir", kLongArg], ["--cpu-prof-interval", kLongArg], ["--cpu-prof-name", kLongArg], ["--diagnostic-dir", kLongArg], ["--disable-proto", kLongArg], ["--dns-result-order", kLongArg], ["-e", kShortArg], ["--eval", kLongArg], ["--experimental-loader", kLongArg], ["--experimental-policy", kLongArg], ["--experimental-specifier-resolution", kLongArg], ["--heapsnapshot-near-heap-limit", kLongArg], ["--heapsnapshot-signal", kLongArg], ["--heap-prof-dir", kLongArg], ["--heap-prof-interval", kLongArg], ["--heap-prof-name", kLongArg], ["--icu-data-dir", kLongArg], ["--input-type", kLongArg], ["--inspect-publish-uid", kLongArg], ["--max-http-header-size", kLongArg], ["--openssl-config", kLongArg], ["-p", kShortArg], ["--print", kLongArg], ["--policy-integrity", kLongArg], ["--prof-process", kLongArg], ["-r", kShortArg], ["--require", kLongArg], ["--redirect-warnings", kLongArg], ["--report-dir", kLongArg], ["--report-directory", kLongArg], ["--report-filename", kLongArg], ["--report-signal", kLongArg], ["--secure-heap", kLongArg], ["--secure-heap-min", kLongArg], ["--snapshot-blob", kLongArg], ["--title", kLongArg], ["--tls-cipher-list", kLongArg], ["--tls-keylog", kLongArg], ["--unhandled-rejections", kLongArg], ["--use-largepages", kLongArg], ["--v8-pool-size", kLongArg],]);const kDenoSubcommands = new Set([ "bench", "bundle", "cache", "check", "compile", "completions", "coverage", "doc", "eval", "fmt", "help", "info", "init", "install", "lint", "lsp", "repl", "run", "tasks", "test", "types", "uninstall", "upgrade", "vendor",]);
function toDenoArgs(args: string[]): string[] { if (args.length === 0) { return args; }
const denoArgs: string[] = []; let useRunArgs = true;
for (let i = 0; i < args.length; i++) { const arg = args[i];
if (arg.charAt(0) !== "-" || arg === "--") {
if (kDenoSubcommands.has(arg)) { return args; }
for (let j = i; j < args.length; j++) { denoArgs.push(args[j]); }
break; }
let flag = arg; let flagInfo = kNodeFlagsMap.get(arg); let isLongWithValue = false; let flagValue;
if (flagInfo === undefined) { const splitAt = arg.indexOf("=");
if (splitAt !== -1) { flag = arg.slice(0, splitAt); flagInfo = kNodeFlagsMap.get(flag); flagValue = arg.slice(splitAt + 1); isLongWithValue = true; } }
if (flagInfo === undefined) { denoArgs.push(arg); continue; }
if (flagValue === undefined) { i++;
if (i >= args.length) { denoArgs.push(arg); continue; }
flagValue = args[i]; }
if (flag === "-e" || flag === "--eval") { denoArgs.push("eval", flagValue); useRunArgs = false; } else if (isLongWithValue) { denoArgs.push(arg); } else { denoArgs.push(flag, flagValue); } }
if (useRunArgs) { denoArgs.unshift("run", "-A", "--unstable"); }
return denoArgs;}
export default { ChildProcess, stdioStringToArray, spawnSync,};