@intellectual-frontiers/system 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/proc.ts ADDED
@@ -0,0 +1,786 @@
1
+ // Spec: 0001-system FR-009
2
+ /**
3
+ * The process and the programs it runs (commons 0005-typescript-runtime FR-022, FR-052, FR-053), on `node:process`, `node:child_process`
4
+ * and `node:os`, the same on Bun and on Node 26. The names are short and plain (`env.get`, `args`, `exit`, `cwd`, `build.os`, `build.target`,
5
+ * `ppid`, `output`, `spawn`, `unrefTimer`); `selfCommand` gives the argument vector for a program that runs itself again, from a script or
6
+ * from a compiled binary. A program is always run by its argument
7
+ * vector, never through a shell; one that cannot be found throws `NotFound`, and a non-zero exit is an outcome, not an error. Taken
8
+ * from erga's `lib/ts/process`, Stolos's `src/archon/core/exec.ts` and the setup's `proc.ts`.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * import { run } from "./proc.ts";
13
+ * const r = await run(["git", "--version"]);
14
+ * if (r.success) console.log(r.stdout.trim());
15
+ * ```
16
+ *
17
+ * @module
18
+ */
19
+ import { Buffer } from "node:buffer";
20
+ import { spawn as spawn_ } from "node:child_process";
21
+ import { statSync } from "node:fs";
22
+ import * as net from "node:net";
23
+ import * as os from "node:os";
24
+ import { basename, delimiter, join, resolve as resolvePath } from "node:path";
25
+ import process from "node:process";
26
+ import { Readable, Writable } from "node:stream";
27
+ import { setTimeout as nodeSetTimeout } from "node:timers";
28
+ import { absurd } from "@intellectual-frontiers/core";
29
+ import { InvalidData, mapError, NotFound, toError } from "./errors.ts";
30
+
31
+ /**
32
+ * What runs a program inside a trace: it is given the program's argument vector and a function that runs it with the environment to add (`TRACEPARENT` and `TRACESTATE`), and gives that
33
+ * function's outcome. The telemetry of commons installs one when its module is loaded (commons 0032-lifting-libraries: this library does not import the telemetry); with none installed a
34
+ * program is run with nothing added.
35
+ */
36
+ export type ProcessTracer = <T extends { readonly code: number }>(
37
+ argv: readonly string[],
38
+ run: (env: Readonly<Record<string, string>>) => Promise<T>,
39
+ ) => Promise<T>;
40
+
41
+ let tracer: ProcessTracer | undefined;
42
+
43
+ /** Installs the function that traces the programs this module runs (or, with `undefined`, removes it): a program is a `process` span where one is installed (0006-signals FR-018). */
44
+ export function setProcessTracer(t: ProcessTracer | undefined): void {
45
+ tracer = t;
46
+ }
47
+
48
+ function traceProcess<T extends { readonly code: number }>(
49
+ argv: readonly string[],
50
+ run: (env: Readonly<Record<string, string>>) => Promise<T>,
51
+ ): Promise<T> {
52
+ return tracer === undefined ? run({}) : tracer(argv, run);
53
+ }
54
+
55
+ /** The process's environment. */
56
+ export const env = {
57
+ /** A variable's value, or undefined where it is not set. */
58
+ get(key: string): string | undefined {
59
+ return process.env[key];
60
+ },
61
+ /** A variable set for this process and the programs it runs. */
62
+ set(key: string, value: string): void {
63
+ process.env[key] = value;
64
+ },
65
+ /** A variable removed. */
66
+ delete(key: string): void {
67
+ Reflect.deleteProperty(process.env, key);
68
+ },
69
+ /** Whether a variable is set. */
70
+ has(key: string): boolean {
71
+ return process.env[key] !== undefined;
72
+ },
73
+ /** Every variable that is set, as a plain object. */
74
+ toObject(): Record<string, string> {
75
+ const out: Record<string, string> = {};
76
+ for (const [k, v] of Object.entries(process.env)) if (v !== undefined) out[k] = v;
77
+ return out;
78
+ },
79
+ } as const;
80
+
81
+ /** The arguments the program was given, after the runtime's own and the script's path. */
82
+ export const args: readonly string[] = Object.freeze(process.argv.slice(2));
83
+
84
+ /** The process ends now with `code` (0 by default). */
85
+ export function exit(code = 0): never {
86
+ process.exit(code);
87
+ }
88
+
89
+ /** The process's working folder. */
90
+ export function cwd(): string {
91
+ return process.cwd();
92
+ }
93
+
94
+ /** The process's working folder changed. */
95
+ export function chdir(path: string): void {
96
+ try {
97
+ process.chdir(path);
98
+ } catch (e) {
99
+ throw mapError(e, path);
100
+ }
101
+ }
102
+
103
+ /** The process's id. */
104
+ export const pid: number = process.pid;
105
+
106
+ /** The id of the process's parent (FR-053); a function, as the parent changes where the first one ends. */
107
+ export function ppid(): number {
108
+ return process.ppid;
109
+ }
110
+
111
+ /** The path of the runtime's executable (bun or node). */
112
+ export function execPath(): string {
113
+ return process.execPath;
114
+ }
115
+
116
+ /** The computer's name. */
117
+ export function hostname(): string {
118
+ return os.hostname();
119
+ }
120
+
121
+ /** The account's home folder. */
122
+ export function homeDir(): string {
123
+ return os.homedir();
124
+ }
125
+
126
+ /** The account's user id, or undefined on Windows. */
127
+ export function uid(): number | undefined {
128
+ return typeof process.getuid === "function" ? process.getuid() : undefined;
129
+ }
130
+
131
+ /** Whether the process runs as root (never on Windows). */
132
+ export function isRoot(): boolean {
133
+ return uid() === 0;
134
+ }
135
+
136
+ /** An operating system, by the names `build.os` gives. */
137
+ export type Os = "linux" | "darwin" | "windows" | "freebsd" | "netbsd" | "openbsd" | "solaris" | "aix" | "android" | "other";
138
+ /** A processor, by the names `build.arch` gives. */
139
+ export type Arch = "x86_64" | "aarch64" | "arm" | "riscv64" | "s390x" | "ppc64" | "other";
140
+
141
+ /** The operating system's name for `node:process`'s `platform`. */
142
+ export function osOf(platform: string): Os {
143
+ switch (platform) {
144
+ case "linux":
145
+ case "darwin":
146
+ case "freebsd":
147
+ case "netbsd":
148
+ case "openbsd":
149
+ case "aix":
150
+ case "android":
151
+ return platform;
152
+ case "win32":
153
+ return "windows";
154
+ case "sunos":
155
+ return "solaris";
156
+ default:
157
+ return "other";
158
+ }
159
+ }
160
+
161
+ /** The processor's name for `node:process`'s `arch`. */
162
+ export function archOf(arch: string): Arch {
163
+ switch (arch) {
164
+ case "x64":
165
+ return "x86_64";
166
+ case "arm64":
167
+ return "aarch64";
168
+ case "arm":
169
+ case "riscv64":
170
+ case "s390x":
171
+ case "ppc64":
172
+ return arch;
173
+ default:
174
+ return "other";
175
+ }
176
+ }
177
+
178
+ /**
179
+ * The target triple (as Rust and Bun name it) for an operating system and a processor (FR-053): `x86_64-unknown-linux-gnu`, `aarch64-apple-darwin`,
180
+ * `x86_64-pc-windows-msvc`, `aarch64-linux-android`, and `<arch>-unknown-<os>` for the rest.
181
+ */
182
+ export function tripleOf(os: Os, arch: Arch): string {
183
+ switch (os) {
184
+ case "linux":
185
+ return `${arch}-unknown-linux-gnu`;
186
+ case "darwin":
187
+ return `${arch}-apple-darwin`;
188
+ case "windows":
189
+ return `${arch}-pc-windows-msvc`;
190
+ case "android":
191
+ return `${arch}-linux-android`;
192
+ case "freebsd":
193
+ case "netbsd":
194
+ case "openbsd":
195
+ case "solaris":
196
+ case "aix":
197
+ case "other":
198
+ return `${arch}-unknown-${os}`;
199
+ default:
200
+ return absurd(os);
201
+ }
202
+ }
203
+
204
+ /** The platform this process runs on, with the target triple (FR-053). */
205
+ export const build: { readonly os: Os; readonly arch: Arch; readonly target: string } = Object.freeze({
206
+ os: osOf(process.platform),
207
+ arch: archOf(process.arch),
208
+ target: tripleOf(osOf(process.platform), archOf(process.arch)),
209
+ });
210
+
211
+ /** Which runtime runs this code. */
212
+ export type RuntimeName = "bun" | "node";
213
+
214
+ /** Which runtime runs this code, from `process.versions`, which each of them fills: Bun, the default, or Node 26, the backup. */
215
+ export function runtimeName(): RuntimeName {
216
+ const v: Readonly<Record<string, string | undefined>> = process.versions;
217
+ if (v["bun"] !== undefined) return "bun";
218
+ return "node";
219
+ }
220
+
221
+ /** The version of the runtime that runs this code. */
222
+ export function runtimeVersion(): string {
223
+ const v: Readonly<Record<string, string | undefined>> = process.versions;
224
+ return v[runtimeName()] ?? process.version.replace(/^v/, "");
225
+ }
226
+
227
+ /** Whether a path is a file this account may run (on Windows, any file). */
228
+ export function isExecutable(path: string): boolean {
229
+ try {
230
+ const s = statSync(path);
231
+ return s.isFile() && (process.platform === "win32" || (s.mode & 0o111) !== 0);
232
+ } catch {
233
+ return false;
234
+ }
235
+ }
236
+
237
+ /** The program `name` on `PATH` (or the path itself where `name` has a separator), as `command -v` finds it; undefined where there is none. */
238
+ export function which(name: string, path: string = env.get("PATH") ?? ""): string | undefined {
239
+ const windows = process.platform === "win32";
240
+ const exts = windows ? ["", ...(env.get("PATHEXT") ?? ".EXE;.CMD;.BAT;.COM").split(";")] : [""];
241
+ const candidates =
242
+ name.includes("/") || (windows && name.includes("\\"))
243
+ ? [name]
244
+ : path
245
+ .split(delimiter)
246
+ .filter((d) => d !== "")
247
+ .flatMap((d) => exts.map((e) => join(d, `${name}${e}`)));
248
+ return candidates.find(isExecutable);
249
+ }
250
+
251
+ /** Where a stream of a program goes: kept (`piped`), shared with this process (`inherit`) or thrown away (`null`). */
252
+ export type Stdio = "piped" | "inherit" | "null";
253
+
254
+ /** How to run a program. */
255
+ export type RunOptions = {
256
+ /** Its working folder. */
257
+ readonly cwd?: string;
258
+ /** Variables added to its environment (or its whole environment, with `clearEnv`). */
259
+ readonly env?: Readonly<Record<string, string>>;
260
+ /** Start it with no variable but those of `env`. */
261
+ readonly clearEnv?: boolean;
262
+ /** Text or bytes it reads as its standard input; without it, `stdin` says what it gets. */
263
+ readonly input?: string | Uint8Array;
264
+ /** Its standard input where there is no `input`: this process's own (`inherit`), or none (`null`, the default). */
265
+ readonly stdin?: "inherit" | "null";
266
+ /** Its standard output: kept (the default), shared, or thrown away. */
267
+ readonly stdout?: Stdio;
268
+ /** Its standard error: kept (the default), shared, or thrown away. */
269
+ readonly stderr?: Stdio;
270
+ /** Each line it writes, as it writes it, without its line ending; the output is kept as well. */
271
+ readonly onLine?: (stream: "stdout" | "stderr", line: string) => void;
272
+ /** Stopping it: SIGTERM when the signal aborts, then SIGKILL after `killAfterMs`. */
273
+ readonly signal?: AbortSignal;
274
+ /** How long a program stopped by `signal` has between SIGTERM and SIGKILL (5000 ms by default). */
275
+ readonly killAfterMs?: number;
276
+ };
277
+
278
+ /** How a program ended. */
279
+ export type Status = {
280
+ /** Its exit status; 128 plus the signal's number where a signal ended it, as a shell reports it. */
281
+ readonly code: number;
282
+ /** Whether its exit status was 0. */
283
+ readonly success: boolean;
284
+ /** The signal that ended it (`SIGTERM`), or null. */
285
+ readonly signal: string | null;
286
+ };
287
+
288
+ /** What a program did, with its output as bytes. */
289
+ export type Output = {
290
+ /** Its exit status; 128 plus the signal's number where a signal ended it, as a shell reports it. */
291
+ readonly code: number;
292
+ /** Whether its exit status was 0. */
293
+ readonly success: boolean;
294
+ /** The signal that ended it (`SIGTERM`), or null. */
295
+ readonly signal: string | null;
296
+ /** What it wrote to standard output, where it was kept. */
297
+ readonly stdout: Uint8Array;
298
+ /** What it wrote to standard error, where it was kept. */
299
+ readonly stderr: Uint8Array;
300
+ };
301
+
302
+ /** What a program did, with its output as text. */
303
+ export type TextOutput = Omit<Output, "stdout" | "stderr"> & { readonly stdout: string; readonly stderr: string };
304
+
305
+ const SIGNALS: Readonly<Record<string, number>> = {
306
+ SIGHUP: 1,
307
+ SIGINT: 2,
308
+ SIGQUIT: 3,
309
+ SIGABRT: 6,
310
+ SIGKILL: 9,
311
+ SIGPIPE: 13,
312
+ SIGALRM: 14,
313
+ SIGTERM: 15,
314
+ };
315
+
316
+ /** The number of a signal by its name (1 for one it does not know). */
317
+ export function signalNumber(name: string): number {
318
+ return SIGNALS[name] ?? os.constants.signals[name as keyof typeof os.constants.signals] ?? 1;
319
+ }
320
+
321
+ const stdio = (s: Stdio | undefined): "pipe" | "inherit" | "ignore" => (s === "inherit" ? "inherit" : s === "null" ? "ignore" : "pipe");
322
+
323
+ /** The environment a program is given: this process's with `env` added, or `env` alone with `clearEnv`. */
324
+ const childEnv = (options: {
325
+ readonly env?: Readonly<Record<string, string>>;
326
+ readonly clearEnv?: boolean;
327
+ }): Record<string, string | undefined> => (options.clearEnv === true ? { ...options.env } : { ...process.env, ...options.env });
328
+
329
+ /** An exit status as a shell reports it: 128 plus the signal's number where a signal ended the program. */
330
+ function exitStatus(code: number | null, signal: string | null): Status {
331
+ const status = signal !== null ? 128 + signalNumber(signal) : (code ?? 1);
332
+ return { code: status, success: status === 0, signal };
333
+ }
334
+
335
+ /** Byte arrays joined into one. */
336
+ function joined(parts: readonly Uint8Array[]): Uint8Array {
337
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
338
+ let at = 0;
339
+ for (const p of parts) {
340
+ out.set(p, at);
341
+ at += p.length;
342
+ }
343
+ return out;
344
+ }
345
+
346
+ /**
347
+ * A program run to its end, by its argument vector and never through a shell, with what it did. `NotFound` where there is no such program.
348
+ * Where a telemetry pipeline is installed, the run is a `process` span and the program is given its `TRACEPARENT` (0006-signals FR-018).
349
+ */
350
+ export function output(argv: readonly string[], options: RunOptions = {}): Promise<Output> {
351
+ const [cmd, ...rest] = argv;
352
+ if (cmd === undefined || cmd === "") return Promise.reject(new InvalidData("nothing to run: the argument vector is empty", "EINVAL"));
353
+ return traceProcess(argv, (trace) =>
354
+ spawnOutput(cmd, rest, Object.keys(trace).length === 0 ? options : { ...options, env: { ...trace, ...options.env } }),
355
+ );
356
+ }
357
+
358
+ function spawnOutput(cmd: string, rest: readonly string[], options: RunOptions): Promise<Output> {
359
+ const input = options.input;
360
+ const feeds = input !== undefined;
361
+ return new Promise<Output>((resolve, reject) => {
362
+ let settled = false;
363
+ const child = spawn_(cmd, rest, {
364
+ ...(options.cwd === undefined ? {} : { cwd: options.cwd }),
365
+ env: childEnv(options),
366
+ stdio: [feeds ? "pipe" : options.stdin === "inherit" ? "inherit" : "ignore", stdio(options.stdout), stdio(options.stderr)],
367
+ windowsHide: true,
368
+ });
369
+ const kept = { stdout: [] as Uint8Array[], stderr: [] as Uint8Array[] };
370
+ const collect = (name: "stdout" | "stderr", stream: Readable | null): void => {
371
+ if (stream === null) return;
372
+ const dec = new TextDecoder();
373
+ let rest = "";
374
+ stream.on("data", (chunk: Uint8Array) => {
375
+ kept[name].push(chunk);
376
+ if (options.onLine === undefined) return;
377
+ rest += dec.decode(chunk, { stream: true });
378
+ const lines = rest.split("\n");
379
+ rest = lines.pop() ?? "";
380
+ for (const l of lines) options.onLine(name, l.replace(/\r$/, ""));
381
+ });
382
+ stream.on("end", () => {
383
+ rest += dec.decode();
384
+ if (options.onLine !== undefined && rest !== "") options.onLine(name, rest.replace(/\r$/, ""));
385
+ });
386
+ };
387
+ collect("stdout", child.stdout);
388
+ collect("stderr", child.stderr);
389
+ let killer: ReturnType<typeof setTimeout> | undefined;
390
+ const stop = (): void => {
391
+ child.kill("SIGTERM");
392
+ killer = setTimeout(() => child.kill("SIGKILL"), options.killAfterMs ?? 5000);
393
+ };
394
+ options.signal?.addEventListener("abort", stop, { once: true });
395
+ if (options.signal?.aborted === true) stop();
396
+ child.on("error", (e) => {
397
+ if (settled) return;
398
+ settled = true;
399
+ options.signal?.removeEventListener("abort", stop);
400
+ if (killer !== undefined) clearTimeout(killer);
401
+ reject(mapError(e, cmd));
402
+ });
403
+ child.on("close", (code, signal) => {
404
+ if (settled) return;
405
+ settled = true;
406
+ options.signal?.removeEventListener("abort", stop);
407
+ if (killer !== undefined) clearTimeout(killer);
408
+ resolve({ ...exitStatus(code, signal), stdout: joined(kept.stdout), stderr: joined(kept.stderr) });
409
+ });
410
+ if (input !== undefined && child.stdin !== null) {
411
+ child.stdin.on("error", () => {
412
+ /* the program closed its input early; what it did is still reported */
413
+ });
414
+ child.stdin.end(typeof input === "string" ? input : Buffer.from(input.buffer, input.byteOffset, input.byteLength));
415
+ }
416
+ });
417
+ }
418
+
419
+ /** A program run to its end, with its output as text (UTF-8). `NotFound` where there is no such program. */
420
+ export async function run(argv: readonly string[], options: RunOptions = {}): Promise<TextOutput> {
421
+ const r = await output(argv, options);
422
+ const dec = new TextDecoder();
423
+ return { code: r.code, success: r.success, signal: r.signal, stdout: dec.decode(r.stdout), stderr: dec.decode(r.stderr) };
424
+ }
425
+
426
+ /** A program's standard output, where it succeeds; an `Error` naming the program, its status and what it said, where it does not. */
427
+ export async function must(argv: readonly string[], options: RunOptions = {}): Promise<string> {
428
+ const r = await run(argv, options);
429
+ if (!r.success) throw new Error(`${argv.join(" ")} failed (${r.code}): ${r.stderr.trim() || r.stdout.trim()}`);
430
+ return r.stdout;
431
+ }
432
+
433
+ /** The first line a program prints, trimmed; `""` where it fails or cannot be found. */
434
+ export async function firstLine(argv: readonly string[], options: RunOptions = {}): Promise<string> {
435
+ try {
436
+ const r = await run(argv, options);
437
+ return r.success ? (r.stdout.split("\n")[0] ?? "").trim() : "";
438
+ } catch {
439
+ return "";
440
+ }
441
+ }
442
+
443
+ // ---------------------------------------------------------------------------------------------------------------------------------
444
+ // A program that runs beside this one (FR-052)
445
+ // ---------------------------------------------------------------------------------------------------------------------------------
446
+
447
+ /** A signal a program can be sent. */
448
+ export type KillSignal = Signal | "SIGKILL" | "SIGABRT" | "SIGALRM" | "SIGSTOP" | "SIGCONT" | "SIGPIPE";
449
+
450
+ /** How to start a program that runs beside this one; each stream is this process's own (`inherit`) unless asked. */
451
+ export type SpawnOptions = {
452
+ /** Its working folder. */
453
+ readonly cwd?: string;
454
+ /** Variables added to its environment (or its whole environment, with `clearEnv`). */
455
+ readonly env?: Readonly<Record<string, string>>;
456
+ /** Start it with no variable but those of `env`. */
457
+ readonly clearEnv?: boolean;
458
+ /** Its standard input: a `WritableStream` (`piped`), this process's own (the default), or none. */
459
+ readonly stdin?: Stdio;
460
+ /** Its standard output: a `ReadableStream` (`piped`), this process's own (the default), or thrown away. */
461
+ readonly stdout?: Stdio;
462
+ /** Its standard error: a `ReadableStream` (`piped`), this process's own (the default), or thrown away. */
463
+ readonly stderr?: Stdio;
464
+ /** Stopping it: SIGTERM when the signal aborts, then SIGKILL after `killAfterMs`. */
465
+ readonly signal?: AbortSignal;
466
+ /** How long a program being stopped has between SIGTERM and SIGKILL (5000 ms by default), by `signal` or by `await using`. */
467
+ readonly killAfterMs?: number;
468
+ };
469
+
470
+ /** A program while it runs `await using` stops it (SIGTERM, then SIGKILL) where it still runs, and waits for it. */
471
+ export type Child = AsyncDisposable & {
472
+ /** Its process id. */
473
+ readonly pid: number;
474
+ /** Its standard input, where it is piped; closing the stream closes its input. */
475
+ readonly stdin: WritableStream<Uint8Array> | null;
476
+ /** Its standard output, where it is piped. */
477
+ readonly stdout: ReadableStream<Uint8Array> | null;
478
+ /** Its standard error, where it is piped. */
479
+ readonly stderr: ReadableStream<Uint8Array> | null;
480
+ /** How it ended, once it ends; rejected with the runtime's error where it could not be started. */
481
+ readonly status: Promise<Status>;
482
+ /** Sends it a signal (SIGTERM by default); nothing where it has already ended. */
483
+ kill(signal?: KillSignal): void;
484
+ /** Its whole output and error, read from the piped streams (empty where not piped), and its status, once it ends. */
485
+ output(): Promise<Output>;
486
+ /** It keeps this process alive until it ends (the default). */
487
+ ref(): void;
488
+ /** It no longer keeps this process alive; nor do its pipes. */
489
+ unref(): void;
490
+ };
491
+
492
+ /** The value of `PATH` in an environment, whatever its case on Windows. */
493
+ function pathIn(environment: Readonly<Record<string, string | undefined>>): string {
494
+ const direct = environment["PATH"];
495
+ if (direct !== undefined) return direct;
496
+ const key = Object.keys(environment).find((k) => k.toUpperCase() === "PATH");
497
+ return key === undefined ? "" : (environment[key] ?? "");
498
+ }
499
+
500
+ /** Whether a program exists to run: a path (from `cwd`) that is executable, or a name found on the environment's `PATH`. */
501
+ function findable(cmd: string, environment: Readonly<Record<string, string | undefined>>, cwd: string | undefined): boolean {
502
+ const pathLike = cmd.includes("/") || (process.platform === "win32" && cmd.includes("\\"));
503
+ return pathLike ? isExecutable(resolvePath(cwd ?? process.cwd(), cmd)) : which(cmd, pathIn(environment)) !== undefined;
504
+ }
505
+
506
+ /** A Node stream that may be referenced and unreferenced (a pipe's socket). */
507
+ type Refable = { ref?: () => unknown; unref?: () => unknown };
508
+
509
+ /** Bytes to read to the end, joined; nothing where there is no stream. */
510
+ async function readAll(stream: ReadableStream<Uint8Array> | null): Promise<Uint8Array> {
511
+ if (stream === null) return new Uint8Array(0);
512
+ const parts: Uint8Array[] = [];
513
+ const reader = stream.getReader();
514
+ try {
515
+ for (;;) {
516
+ const r = await reader.read();
517
+ if (r.done) break;
518
+ parts.push(r.value);
519
+ }
520
+ } finally {
521
+ reader.releaseLock();
522
+ }
523
+ return joined(parts);
524
+ }
525
+
526
+ /**
527
+ * Starts a program by its argument vector, never through a shell, and gives its handle while it runs (FR-052). A program that cannot be found throws `NotFound` at once: a path that is not an executable file, or a name not
528
+ * on the `PATH` of the environment it is given. Where a telemetry pipeline is installed, the run is a `process` span that ends when the
529
+ * program does, and the program is given its `TRACEPARENT` (0006-signals FR-018), as for `output`.
530
+ *
531
+ * @example
532
+ * ```ts
533
+ * import { spawn } from "./proc.ts";
534
+ * await using child = spawn(["gzip", "-dc"], { stdin: "piped", stdout: "piped" });
535
+ * ```
536
+ */
537
+ export function spawn(argv: readonly string[], options: SpawnOptions = {}): Child {
538
+ const [cmd, ...rest] = argv;
539
+ if (cmd === undefined || cmd === "") throw new InvalidData("nothing to run: the argument vector is empty", "EINVAL");
540
+ if (!findable(cmd, childEnv(options), options.cwd)) throw new NotFound(`no such program: ${cmd}`, "ENOENT", cmd);
541
+ const box: { started?: Started } = {};
542
+ const status = traceProcess(argv, (trace) => {
543
+ const started = startChild(cmd, rest, Object.keys(trace).length === 0 ? options : { ...options, env: { ...trace, ...options.env } });
544
+ box.started = started;
545
+ return started.exited;
546
+ });
547
+ // A program that could not be started rejects `status`; that is the caller's to see, never an unhandled rejection of its own.
548
+ status.catch(() => undefined);
549
+ const started = box.started;
550
+ // The span's function runs at once (kernel/signals.ts `span`), so the handle is there; this guards against a change to that.
551
+ if (started === undefined) throw new Error("the program's handle was not made");
552
+ const { pipes } = started;
553
+ return {
554
+ ...pipes,
555
+ status,
556
+ output: async (): Promise<Output> => {
557
+ const [stdout, stderr, st] = await Promise.all([readAll(pipes.stdout), readAll(pipes.stderr), status]);
558
+ return { ...st, stdout, stderr };
559
+ },
560
+ kill: started.kill,
561
+ ref: started.ref,
562
+ unref: started.unref,
563
+ [Symbol.asyncDispose]: started.dispose,
564
+ };
565
+ }
566
+
567
+ /** A started program, before its status is traced. */
568
+ type Started = {
569
+ readonly pipes: Pick<Child, "pid" | "stdin" | "stdout" | "stderr">;
570
+ readonly exited: Promise<Status>;
571
+ readonly kill: Child["kill"];
572
+ readonly ref: () => void;
573
+ readonly unref: () => void;
574
+ readonly dispose: () => Promise<void>;
575
+ };
576
+
577
+ function startChild(cmd: string, rest: readonly string[], options: SpawnOptions): Started {
578
+ const node = spawn_(cmd, rest, {
579
+ ...(options.cwd === undefined ? {} : { cwd: options.cwd }),
580
+ env: childEnv(options),
581
+ stdio: [stdio(options.stdin ?? "inherit"), stdio(options.stdout ?? "inherit"), stdio(options.stderr ?? "inherit")],
582
+ windowsHide: true,
583
+ });
584
+ let ended = false;
585
+ let killer: ReturnType<typeof setTimeout> | undefined;
586
+ const stop = (): void => {
587
+ if (ended) return;
588
+ node.kill("SIGTERM");
589
+ killer ??= setTimeout(() => {
590
+ if (!ended) node.kill("SIGKILL");
591
+ }, options.killAfterMs ?? 5000);
592
+ };
593
+ const exited = new Promise<Status>((resolve, reject) => {
594
+ const done = (): void => {
595
+ ended = true;
596
+ options.signal?.removeEventListener("abort", stop);
597
+ if (killer !== undefined) clearTimeout(killer);
598
+ };
599
+ node.once("error", (e) => {
600
+ if (ended) return;
601
+ done();
602
+ reject(mapError(e, cmd));
603
+ });
604
+ node.once("exit", (code, signal) => {
605
+ if (ended) return;
606
+ done();
607
+ resolve(exitStatus(code, signal));
608
+ });
609
+ });
610
+ options.signal?.addEventListener("abort", stop, { once: true });
611
+ if (options.signal?.aborted === true) stop();
612
+ node.stdin?.on("error", () => {
613
+ /* the program closed its input early; the writer sees the error, and the program's status says what it did */
614
+ });
615
+ // Node's streams become web streams; their types are `node:stream/web`'s, which are the same classes as the global ones.
616
+ const stdin = node.stdin === null ? null : (Writable.toWeb(node.stdin) as WritableStream<Uint8Array>);
617
+ const stdout = node.stdout === null ? null : (Readable.toWeb(node.stdout) as ReadableStream<Uint8Array>);
618
+ const stderr = node.stderr === null ? null : (Readable.toWeb(node.stderr) as ReadableStream<Uint8Array>);
619
+ // A pipe is a `net.Socket`, which can be unreferenced; the stream types do not say so.
620
+ const pipes = (): Refable[] => [node.stdin, node.stdout, node.stderr].flatMap((s): Refable[] => (s === null ? [] : [s as Refable]));
621
+ return {
622
+ pipes: { pid: node.pid ?? 0, stdin, stdout, stderr },
623
+ exited,
624
+ kill: (signal: KillSignal = "SIGTERM"): void => {
625
+ if (!ended) node.kill(signal);
626
+ },
627
+ ref: (): void => {
628
+ node.ref();
629
+ for (const p of pipes()) p.ref?.();
630
+ },
631
+ unref: (): void => {
632
+ node.unref();
633
+ for (const p of pipes()) p.unref?.();
634
+ },
635
+ dispose: async (): Promise<void> => {
636
+ stop();
637
+ await exited.catch(() => undefined);
638
+ for (const p of [node.stdin, node.stdout, node.stderr]) p?.destroy();
639
+ },
640
+ };
641
+ }
642
+
643
+ /** A signal this process can listen for. */
644
+ export type Signal = "SIGINT" | "SIGTERM" | "SIGHUP" | "SIGQUIT" | "SIGUSR1" | "SIGUSR2" | "SIGWINCH" | "SIGBREAK";
645
+
646
+ /** A function called when the process receives the signal. */
647
+ export function addSignalListener(signal: Signal, handler: () => void): void {
648
+ process.on(signal, handler);
649
+ }
650
+
651
+ /** A function no longer called for the signal. */
652
+ export function removeSignalListener(signal: Signal, handler: () => void): void {
653
+ process.off(signal, handler);
654
+ }
655
+
656
+ /** A promise that settles after `ms` milliseconds; an aborted `signal` rejects it early with the signal's reason. */
657
+ export function sleep(ms: number, signal?: AbortSignal): Promise<void> {
658
+ return new Promise((resolve, reject) => {
659
+ if (signal?.aborted === true) {
660
+ reject(toError(signal.reason, "aborted"));
661
+ return;
662
+ }
663
+ const t = setTimeout(() => {
664
+ signal?.removeEventListener("abort", onAbort);
665
+ resolve();
666
+ }, ms);
667
+ const onAbort = (): void => {
668
+ clearTimeout(t);
669
+ reject(toError(signal?.reason, "aborted"));
670
+ };
671
+ signal?.addEventListener("abort", onAbort, { once: true });
672
+ });
673
+ }
674
+
675
+ // ---------------------------------------------------------------------------------------------------------------------------------
676
+ // Timers that never keep the process alive, and the program running itself again (FR-053)
677
+ // ---------------------------------------------------------------------------------------------------------------------------------
678
+
679
+ /** A timer that can be cleared, by call or by `using`. */
680
+ export type Timer = Disposable & {
681
+ /** The timer cleared: its function is not called. */
682
+ clear(): void;
683
+ };
684
+
685
+ /**
686
+ * Calls `callback` after `ms` milliseconds, with a timer that never keeps the process alive (FR-053): where nothing
687
+ * else is left to do, the process ends without waiting for it. It is made on `node:timers`, whose timers can be unreferenced on each
688
+ * runtime.
689
+ */
690
+ export function unrefTimer(callback: () => void, ms: number): Timer {
691
+ const t = nodeSetTimeout(callback, ms);
692
+ t.unref();
693
+ const clear = (): void => clearTimeout(t);
694
+ return { clear, [Symbol.dispose]: clear };
695
+ }
696
+
697
+ /** What `selfCommand` reads of the running process: `process.execPath`, `process.argv` and `process.execArgv`, and the runtime. */
698
+ export type SelfFacts = {
699
+ readonly runtime: RuntimeName;
700
+ readonly execPath: string;
701
+ readonly argv: readonly string[];
702
+ readonly execArgv: readonly string[];
703
+ };
704
+
705
+ /** The facts of this process, for `selfCommandOf`. */
706
+ export function selfFacts(): SelfFacts {
707
+ return { runtime: runtimeName(), execPath: process.execPath, argv: [...process.argv], execArgv: [...process.execArgv] };
708
+ }
709
+
710
+ /** The names a runtime's own executable starts with (`bun`, `bun-debug`, `node`, `nodejs`, `node26`, `node.exe`, ...). */
711
+ const RUNTIME_EXECUTABLE = /^(?:bun|node)(?:[-._\d]|js|$)/i;
712
+
713
+ /**
714
+ * Whether the running program is a binary that holds its own code (FR-053), so that running it again needs no script. Either is enough:
715
+ * - Bun's own mark of a binary it compiled: the script's path, `process.argv[1]`, is in Bun's embedded file system (`/$bunfs/...`, or
716
+ * `B:\~BUN\...` on Windows), where it keeps the code it compiled in;
717
+ * - the executable, `process.execPath`, is not named as a runtime is (`bun`, `node`, with any version or `.exe`): the binaries
718
+ * that `bun build --compile` and Node's single executable applications make are named after the program.
719
+ */
720
+ export function isCompiled(facts: SelfFacts): boolean {
721
+ const script = facts.argv[1] ?? "";
722
+ if (script.startsWith("/$bunfs/") || /^[A-Za-z]:[\\/]~BUN[\\/]/.test(script)) return true;
723
+ return !RUNTIME_EXECUTABLE.test(basename(facts.execPath.replace(/\\/g, "/")));
724
+ }
725
+
726
+ /**
727
+ * The argument vector that runs the program again with `args` (FR-053): from a compiled binary,
728
+ * the binary alone; on Bun and Node, the runtime with its own options (`process.execArgv`) and the script. With no script (code given on the command line), the runtime alone.
729
+ */
730
+ export function selfCommandOf(facts: SelfFacts, args: readonly string[] = []): readonly string[] {
731
+ if (isCompiled(facts)) return [facts.execPath, ...args];
732
+ const script = facts.argv[1];
733
+ const scriptArgs = script === undefined ? [] : [script];
734
+ switch (facts.runtime) {
735
+ case "bun":
736
+ case "node":
737
+ return [facts.execPath, ...facts.execArgv, ...scriptArgs, ...args];
738
+ default:
739
+ return absurd(facts.runtime);
740
+ }
741
+ }
742
+
743
+ /** The argument vector that runs this program again with `args`, on Bun and Node and from a binary Bun compiled (FR-053). */
744
+ export function selfCommand(args: readonly string[] = []): readonly string[] {
745
+ return selfCommandOf(selfFacts(), args);
746
+ }
747
+
748
+ /** One address of one network interface. */
749
+ export type NetworkInterfaceInfo = {
750
+ /** The interface's name (`lo`, `eth0`, `en0`, `Ethernet`). */
751
+ readonly name: string;
752
+ /** The address's family. */
753
+ readonly family: "IPv4" | "IPv6";
754
+ /** The address. */
755
+ readonly address: string;
756
+ /** Its netmask. */
757
+ readonly netmask: string;
758
+ /** The address with its prefix length (`127.0.0.1/8`), where known. */
759
+ readonly cidr: string | null;
760
+ /** The IPv6 scope, where there is one. */
761
+ readonly scopeid: number | null;
762
+ /** The hardware address (`00:00:00:00:00:00` where there is none). */
763
+ readonly mac: string;
764
+ /** Whether it is internal (a loopback), not reachable from outside. */
765
+ readonly internal: boolean;
766
+ };
767
+
768
+ /** Every address of every network interface of this computer (0005-typescript-runtime FR-056). */
769
+ export function networkInterfaces(): readonly NetworkInterfaceInfo[] {
770
+ const out: NetworkInterfaceInfo[] = [];
771
+ for (const [name, infos] of Object.entries(os.networkInterfaces())) {
772
+ for (const i of infos ?? []) {
773
+ out.push({
774
+ name,
775
+ family: net.isIPv6(i.address) ? "IPv6" : "IPv4",
776
+ address: i.address,
777
+ netmask: i.netmask,
778
+ cidr: i.cidr,
779
+ scopeid: i.family === "IPv6" ? i.scopeid : null,
780
+ mac: i.mac,
781
+ internal: i.internal,
782
+ });
783
+ }
784
+ }
785
+ return out;
786
+ }