@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/dist/lock.js ADDED
@@ -0,0 +1,130 @@
1
+ // Spec: 0001-system FR-015
2
+ /**
3
+ * One run at a time (commons 0005-typescript-runtime FR-039): a lock file made only where none exists (`O_EXCL`, which every file system
4
+ * and operating system gives atomically, where `flock` has no `node:` form), holding who holds it (process id, command, since when). A
5
+ * waiting run polls until it is free, says once who it waits for, and takes over a lock whose holder's process no longer runs. A child of
6
+ * a holder can inherit the lock through an environment variable instead of waiting for its own parent. Taken from Stolos's
7
+ * `src/archon/core/lock.ts`, which locked through the runtime's own file lock.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * import { acquireLock } from "./lock.ts";
12
+ * const held = await acquireLock("/run/app.lock", { wait: true, command: "update", onWait: (h) => console.log(`waiting for ${h?.command}`) });
13
+ * try {
14
+ * // the work
15
+ * } finally {
16
+ * held?.release();
17
+ * }
18
+ * ```
19
+ *
20
+ * @module
21
+ */
22
+ import * as nfs from "node:fs";
23
+ import process from "node:process";
24
+ import { integer, json, object, string } from "@intellectual-frontiers/core";
25
+ import { AlreadyExists, mapError, NotFound } from "./errors.js";
26
+ import { readTextFile, remove, writeTextFile } from "./fs.js";
27
+ import { sleep } from "./proc.js";
28
+ const holderDecoder = object({ pid: integer, command: string, since: string, token: string });
29
+ /** Whether a process runs: a signal of 0 checks without sending one. A process of another account counts as running. */
30
+ export function processRuns(pid) {
31
+ try {
32
+ process.kill(pid, 0);
33
+ return true;
34
+ }
35
+ catch (e) {
36
+ return e instanceof Error && "code" in e && e.code === "EPERM";
37
+ }
38
+ }
39
+ /** Who holds the lock at `path`, where its file can be read; whether that process still runs is not checked here. */
40
+ export async function readHolder(path) {
41
+ try {
42
+ const r = json(await readTextFile(path), holderDecoder);
43
+ return r.kind === "ok" ? r.value : undefined;
44
+ }
45
+ catch {
46
+ return undefined;
47
+ }
48
+ }
49
+ /** A holder as a person reads it: `update (pid 4242, for 3m 12s)`. */
50
+ export function describeHolder(h, now = Date.now()) {
51
+ const secs = Math.max(0, Math.round((now - Date.parse(h.since)) / 1000));
52
+ const age = secs >= 60 ? `${Math.floor(secs / 60)}m ${secs % 60}s` : `${secs}s`;
53
+ return `${h.command} (pid ${h.pid}, for ${age})`;
54
+ }
55
+ /**
56
+ * The lock at `path` taken, or undefined where it is held by a running process and `wait` is false (or `timeoutMs` passed). A lock whose
57
+ * holder no longer runs, or whose file cannot be read, is taken over. Where `inheritEnv` is set in the environment, a parent holds it,
58
+ * and it is given at once (its release does nothing).
59
+ */
60
+ export async function acquireLock(path, options) {
61
+ const holder = {
62
+ pid: process.pid,
63
+ command: options.command ??
64
+ (process.argv
65
+ .slice(2)
66
+ .filter((a) => !a.startsWith("-"))
67
+ .slice(0, 3)
68
+ .join(" ") ||
69
+ "a run"),
70
+ since: new Date().toISOString(),
71
+ token: crypto.randomUUID(),
72
+ };
73
+ const inherit = options.inheritEnv;
74
+ if (inherit !== undefined && process.env[inherit] === "1")
75
+ return { holder, release: () => { } };
76
+ const started = Date.now();
77
+ let told = false;
78
+ for (;;) {
79
+ try {
80
+ await writeTextFile(path, `${JSON.stringify(holder)}\n`, { createNew: true, mode: 0o644 });
81
+ break;
82
+ }
83
+ catch (e) {
84
+ if (!(e instanceof AlreadyExists))
85
+ throw e;
86
+ }
87
+ const current = await readHolder(path);
88
+ if (current === undefined || !processRuns(current.pid)) {
89
+ const again = await readHolder(path);
90
+ if (again?.token === current?.token)
91
+ await remove(path).catch((e) => {
92
+ if (!(e instanceof NotFound))
93
+ throw e;
94
+ });
95
+ continue;
96
+ }
97
+ if (!options.wait)
98
+ return undefined;
99
+ if (options.timeoutMs !== undefined && Date.now() - started >= options.timeoutMs)
100
+ return undefined;
101
+ if (!told) {
102
+ options.onWait?.(current);
103
+ told = true;
104
+ }
105
+ await sleep(options.pollMs ?? 250);
106
+ }
107
+ if (inherit !== undefined)
108
+ process.env[inherit] = "1";
109
+ let released = false;
110
+ const release = () => {
111
+ if (released)
112
+ return;
113
+ released = true;
114
+ if (inherit !== undefined)
115
+ Reflect.deleteProperty(process.env, inherit);
116
+ process.off("exit", release);
117
+ try {
118
+ const text = nfs.readFileSync(path, "utf8");
119
+ if (text.includes(holder.token))
120
+ nfs.unlinkSync(path);
121
+ }
122
+ catch (e) {
123
+ const mapped = mapError(e, path);
124
+ if (!(mapped instanceof NotFound))
125
+ throw mapped;
126
+ }
127
+ };
128
+ process.on("exit", release);
129
+ return { holder, release };
130
+ }
package/dist/mod.d.ts ADDED
@@ -0,0 +1,28 @@
1
+ /**
2
+ * System, the host of Intellectual Frontiers Commons as one typed library (its specification 0001-system): typed errors (as `errors`, with `mapError`, `RuntimeError` and `toError`), files (as `fs`), paths (as `path`),
3
+ * the folders a program keeps its files in (as `dirs`), one run at a time (as `lock`), file watching (as `watch`), programs found by the prefix of their name (as `discover`), the process and the programs it runs
4
+ * (as `proc`), Git read by running it (as `git`), a program built into one binary (as `compile`), the operating system's scheduled jobs installed (as `jobs`) and planned (as `jobPlan`), and the terminal's
5
+ * streams (as `tty` and `stdio`). It names `node:` builtins and no vendor's global, depends on core, formats and crypto, and runs the same on Bun and on Node 26.
6
+ *
7
+ * @example
8
+ * ```ts
9
+ * import { fs, path } from "@intellectual-frontiers/system";
10
+ * const text = await fs.readTextFile(path.join("a", "b.txt"));
11
+ * ```
12
+ *
13
+ * @module
14
+ */
15
+ export * as compile from "./compile.js";
16
+ export * as dirs from "./dirs.js";
17
+ export * as discover from "./discover.js";
18
+ export { errors, mapError, RuntimeError, toError } from "./errors.js";
19
+ export * as fs from "./fs.js";
20
+ export * as git from "./git.js";
21
+ export * as jobPlan from "./job-plan.js";
22
+ export * as jobs from "./schedule.js";
23
+ export * as lock from "./lock.js";
24
+ export * as path from "./path.js";
25
+ export * as proc from "./proc.js";
26
+ export * as stdio from "./stdio.js";
27
+ export * as tty from "./tty.js";
28
+ export * as watch from "./watch.js";
package/dist/mod.js ADDED
@@ -0,0 +1,29 @@
1
+ // Spec: 0001-system FR-020
2
+ /**
3
+ * System, the host of Intellectual Frontiers Commons as one typed library (its specification 0001-system): typed errors (as `errors`, with `mapError`, `RuntimeError` and `toError`), files (as `fs`), paths (as `path`),
4
+ * the folders a program keeps its files in (as `dirs`), one run at a time (as `lock`), file watching (as `watch`), programs found by the prefix of their name (as `discover`), the process and the programs it runs
5
+ * (as `proc`), Git read by running it (as `git`), a program built into one binary (as `compile`), the operating system's scheduled jobs installed (as `jobs`) and planned (as `jobPlan`), and the terminal's
6
+ * streams (as `tty` and `stdio`). It names `node:` builtins and no vendor's global, depends on core, formats and crypto, and runs the same on Bun and on Node 26.
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * import { fs, path } from "@intellectual-frontiers/system";
11
+ * const text = await fs.readTextFile(path.join("a", "b.txt"));
12
+ * ```
13
+ *
14
+ * @module
15
+ */
16
+ export * as compile from "./compile.js";
17
+ export * as dirs from "./dirs.js";
18
+ export * as discover from "./discover.js";
19
+ export { errors, mapError, RuntimeError, toError } from "./errors.js";
20
+ export * as fs from "./fs.js";
21
+ export * as git from "./git.js";
22
+ export * as jobPlan from "./job-plan.js";
23
+ export * as jobs from "./schedule.js";
24
+ export * as lock from "./lock.js";
25
+ export * as path from "./path.js";
26
+ export * as proc from "./proc.js";
27
+ export * as stdio from "./stdio.js";
28
+ export * as tty from "./tty.js";
29
+ export * as watch from "./watch.js";
package/dist/path.d.ts ADDED
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Paths, on `node:path` (commons 0005-typescript-runtime FR-021): the platform's own rules, and `posix` and `win32` for the other's, with
3
+ * `file:` URLs both ways. Taken from Stolos's `src/archon/core/path.ts`, which already used `node:path`; it replaces `@std/path`.
4
+ *
5
+ * @example
6
+ * ```ts
7
+ * import { basename, join } from "./path.js";
8
+ * basename(join("a", "b", "c.txt")); // "c.txt"
9
+ * ```
10
+ *
11
+ * @module
12
+ */
13
+ import * as nodePath from "node:path";
14
+ /** Path segments joined and normalized. */
15
+ export declare const join: (...paths: string[]) => string;
16
+ /** The folder a path is in. */
17
+ export declare const dirname: (path: string) => string;
18
+ /** The last segment of a path, without `suffix` where it ends with it. */
19
+ export declare const basename: (path: string, suffix?: string) => string;
20
+ /** The extension of the last segment, with its dot (`.ts`), or `""`. */
21
+ export declare const extname: (path: string) => string;
22
+ /** The path from one to the other. */
23
+ export declare const relative: (from: string, to: string) => string;
24
+ /** An absolute path, the segments taken from the right until one is absolute, against the working folder. */
25
+ export declare const resolve: (...paths: string[]) => string;
26
+ /** A path with `.` and `..` and repeated separators resolved. */
27
+ export declare const normalize: (path: string) => string;
28
+ /** Whether a path is absolute. */
29
+ export declare const isAbsolute: (path: string) => boolean;
30
+ /** A path's root, folder, base, name and extension. */
31
+ export declare const parse: (path: string) => nodePath.ParsedPath;
32
+ /** A path made from its parts. */
33
+ export declare const format: (parts: nodePath.FormatInputPathObject) => string;
34
+ /** This platform's separator between segments: `/`, or `\` on Windows. */
35
+ export declare const sep: string;
36
+ /** This platform's separator between paths in `PATH`: `:`, or `;` on Windows. */
37
+ export declare const delimiter: string;
38
+ /** The POSIX rules, on any platform. */
39
+ export declare const posix: typeof nodePath.posix;
40
+ /** The Windows rules, on any platform. */
41
+ export declare const win32: typeof nodePath.posix;
42
+ /** A `file:` URL as a path. */
43
+ export declare function fromFileUrl(url: string | URL): string;
44
+ /** A path as a `file:` URL. */
45
+ export declare function toFileUrl(path: string): URL;
46
+ /** A path with `/` between its segments whatever the platform, as archives and URLs write them. */
47
+ export declare function toPosix(path: string): string;
package/dist/path.js ADDED
@@ -0,0 +1,55 @@
1
+ // Spec: 0001-system FR-003
2
+ /**
3
+ * Paths, on `node:path` (commons 0005-typescript-runtime FR-021): the platform's own rules, and `posix` and `win32` for the other's, with
4
+ * `file:` URLs both ways. Taken from Stolos's `src/archon/core/path.ts`, which already used `node:path`; it replaces `@std/path`.
5
+ *
6
+ * @example
7
+ * ```ts
8
+ * import { basename, join } from "./path.ts";
9
+ * basename(join("a", "b", "c.txt")); // "c.txt"
10
+ * ```
11
+ *
12
+ * @module
13
+ */
14
+ import * as nodePath from "node:path";
15
+ import { fileURLToPath, pathToFileURL } from "node:url";
16
+ /** Path segments joined and normalized. */
17
+ export const join = nodePath.join;
18
+ /** The folder a path is in. */
19
+ export const dirname = nodePath.dirname;
20
+ /** The last segment of a path, without `suffix` where it ends with it. */
21
+ export const basename = nodePath.basename;
22
+ /** The extension of the last segment, with its dot (`.ts`), or `""`. */
23
+ export const extname = nodePath.extname;
24
+ /** The path from one to the other. */
25
+ export const relative = nodePath.relative;
26
+ /** An absolute path, the segments taken from the right until one is absolute, against the working folder. */
27
+ export const resolve = nodePath.resolve;
28
+ /** A path with `.` and `..` and repeated separators resolved. */
29
+ export const normalize = nodePath.normalize;
30
+ /** Whether a path is absolute. */
31
+ export const isAbsolute = nodePath.isAbsolute;
32
+ /** A path's root, folder, base, name and extension. */
33
+ export const parse = nodePath.parse;
34
+ /** A path made from its parts. */
35
+ export const format = nodePath.format;
36
+ /** This platform's separator between segments: `/`, or `\` on Windows. */
37
+ export const sep = nodePath.sep;
38
+ /** This platform's separator between paths in `PATH`: `:`, or `;` on Windows. */
39
+ export const delimiter = nodePath.delimiter;
40
+ /** The POSIX rules, on any platform. */
41
+ export const posix = nodePath.posix;
42
+ /** The Windows rules, on any platform. */
43
+ export const win32 = nodePath.win32;
44
+ /** A `file:` URL as a path. */
45
+ export function fromFileUrl(url) {
46
+ return fileURLToPath(url);
47
+ }
48
+ /** A path as a `file:` URL. */
49
+ export function toFileUrl(path) {
50
+ return pathToFileURL(path);
51
+ }
52
+ /** A path with `/` between its segments whatever the platform, as archives and URLs write them. */
53
+ export function toPosix(path) {
54
+ return path.split(nodePath.sep).join("/");
55
+ }
package/dist/proc.d.ts ADDED
@@ -0,0 +1,257 @@
1
+ /**
2
+ * 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
3
+ * 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
4
+ * program is run with nothing added.
5
+ */
6
+ export type ProcessTracer = <T extends {
7
+ readonly code: number;
8
+ }>(argv: readonly string[], run: (env: Readonly<Record<string, string>>) => Promise<T>) => Promise<T>;
9
+ /** 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). */
10
+ export declare function setProcessTracer(t: ProcessTracer | undefined): void;
11
+ /** The process's environment. */
12
+ export declare const env: {
13
+ /** A variable's value, or undefined where it is not set. */
14
+ readonly get: (key: string) => string | undefined;
15
+ /** A variable set for this process and the programs it runs. */
16
+ readonly set: (key: string, value: string) => void;
17
+ /** A variable removed. */
18
+ readonly delete: (key: string) => void;
19
+ /** Whether a variable is set. */
20
+ readonly has: (key: string) => boolean;
21
+ /** Every variable that is set, as a plain object. */
22
+ readonly toObject: () => Record<string, string>;
23
+ };
24
+ /** The arguments the program was given, after the runtime's own and the script's path. */
25
+ export declare const args: readonly string[];
26
+ /** The process ends now with `code` (0 by default). */
27
+ export declare function exit(code?: number): never;
28
+ /** The process's working folder. */
29
+ export declare function cwd(): string;
30
+ /** The process's working folder changed. */
31
+ export declare function chdir(path: string): void;
32
+ /** The process's id. */
33
+ export declare const pid: number;
34
+ /** The id of the process's parent (FR-053); a function, as the parent changes where the first one ends. */
35
+ export declare function ppid(): number;
36
+ /** The path of the runtime's executable (bun or node). */
37
+ export declare function execPath(): string;
38
+ /** The computer's name. */
39
+ export declare function hostname(): string;
40
+ /** The account's home folder. */
41
+ export declare function homeDir(): string;
42
+ /** The account's user id, or undefined on Windows. */
43
+ export declare function uid(): number | undefined;
44
+ /** Whether the process runs as root (never on Windows). */
45
+ export declare function isRoot(): boolean;
46
+ /** An operating system, by the names `build.os` gives. */
47
+ export type Os = "linux" | "darwin" | "windows" | "freebsd" | "netbsd" | "openbsd" | "solaris" | "aix" | "android" | "other";
48
+ /** A processor, by the names `build.arch` gives. */
49
+ export type Arch = "x86_64" | "aarch64" | "arm" | "riscv64" | "s390x" | "ppc64" | "other";
50
+ /** The operating system's name for `node:process`'s `platform`. */
51
+ export declare function osOf(platform: string): Os;
52
+ /** The processor's name for `node:process`'s `arch`. */
53
+ export declare function archOf(arch: string): Arch;
54
+ /**
55
+ * 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`,
56
+ * `x86_64-pc-windows-msvc`, `aarch64-linux-android`, and `<arch>-unknown-<os>` for the rest.
57
+ */
58
+ export declare function tripleOf(os: Os, arch: Arch): string;
59
+ /** The platform this process runs on, with the target triple (FR-053). */
60
+ export declare const build: {
61
+ readonly os: Os;
62
+ readonly arch: Arch;
63
+ readonly target: string;
64
+ };
65
+ /** Which runtime runs this code. */
66
+ export type RuntimeName = "bun" | "node";
67
+ /** Which runtime runs this code, from `process.versions`, which each of them fills: Bun, the default, or Node 26, the backup. */
68
+ export declare function runtimeName(): RuntimeName;
69
+ /** The version of the runtime that runs this code. */
70
+ export declare function runtimeVersion(): string;
71
+ /** Whether a path is a file this account may run (on Windows, any file). */
72
+ export declare function isExecutable(path: string): boolean;
73
+ /** The program `name` on `PATH` (or the path itself where `name` has a separator), as `command -v` finds it; undefined where there is none. */
74
+ export declare function which(name: string, path?: string): string | undefined;
75
+ /** Where a stream of a program goes: kept (`piped`), shared with this process (`inherit`) or thrown away (`null`). */
76
+ export type Stdio = "piped" | "inherit" | "null";
77
+ /** How to run a program. */
78
+ export type RunOptions = {
79
+ /** Its working folder. */
80
+ readonly cwd?: string;
81
+ /** Variables added to its environment (or its whole environment, with `clearEnv`). */
82
+ readonly env?: Readonly<Record<string, string>>;
83
+ /** Start it with no variable but those of `env`. */
84
+ readonly clearEnv?: boolean;
85
+ /** Text or bytes it reads as its standard input; without it, `stdin` says what it gets. */
86
+ readonly input?: string | Uint8Array;
87
+ /** Its standard input where there is no `input`: this process's own (`inherit`), or none (`null`, the default). */
88
+ readonly stdin?: "inherit" | "null";
89
+ /** Its standard output: kept (the default), shared, or thrown away. */
90
+ readonly stdout?: Stdio;
91
+ /** Its standard error: kept (the default), shared, or thrown away. */
92
+ readonly stderr?: Stdio;
93
+ /** Each line it writes, as it writes it, without its line ending; the output is kept as well. */
94
+ readonly onLine?: (stream: "stdout" | "stderr", line: string) => void;
95
+ /** Stopping it: SIGTERM when the signal aborts, then SIGKILL after `killAfterMs`. */
96
+ readonly signal?: AbortSignal;
97
+ /** How long a program stopped by `signal` has between SIGTERM and SIGKILL (5000 ms by default). */
98
+ readonly killAfterMs?: number;
99
+ };
100
+ /** How a program ended. */
101
+ export type Status = {
102
+ /** Its exit status; 128 plus the signal's number where a signal ended it, as a shell reports it. */
103
+ readonly code: number;
104
+ /** Whether its exit status was 0. */
105
+ readonly success: boolean;
106
+ /** The signal that ended it (`SIGTERM`), or null. */
107
+ readonly signal: string | null;
108
+ };
109
+ /** What a program did, with its output as bytes. */
110
+ export type Output = {
111
+ /** Its exit status; 128 plus the signal's number where a signal ended it, as a shell reports it. */
112
+ readonly code: number;
113
+ /** Whether its exit status was 0. */
114
+ readonly success: boolean;
115
+ /** The signal that ended it (`SIGTERM`), or null. */
116
+ readonly signal: string | null;
117
+ /** What it wrote to standard output, where it was kept. */
118
+ readonly stdout: Uint8Array;
119
+ /** What it wrote to standard error, where it was kept. */
120
+ readonly stderr: Uint8Array;
121
+ };
122
+ /** What a program did, with its output as text. */
123
+ export type TextOutput = Omit<Output, "stdout" | "stderr"> & {
124
+ readonly stdout: string;
125
+ readonly stderr: string;
126
+ };
127
+ /** The number of a signal by its name (1 for one it does not know). */
128
+ export declare function signalNumber(name: string): number;
129
+ /**
130
+ * 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.
131
+ * Where a telemetry pipeline is installed, the run is a `process` span and the program is given its `TRACEPARENT` (0006-signals FR-018).
132
+ */
133
+ export declare function output(argv: readonly string[], options?: RunOptions): Promise<Output>;
134
+ /** A program run to its end, with its output as text (UTF-8). `NotFound` where there is no such program. */
135
+ export declare function run(argv: readonly string[], options?: RunOptions): Promise<TextOutput>;
136
+ /** A program's standard output, where it succeeds; an `Error` naming the program, its status and what it said, where it does not. */
137
+ export declare function must(argv: readonly string[], options?: RunOptions): Promise<string>;
138
+ /** The first line a program prints, trimmed; `""` where it fails or cannot be found. */
139
+ export declare function firstLine(argv: readonly string[], options?: RunOptions): Promise<string>;
140
+ /** A signal a program can be sent. */
141
+ export type KillSignal = Signal | "SIGKILL" | "SIGABRT" | "SIGALRM" | "SIGSTOP" | "SIGCONT" | "SIGPIPE";
142
+ /** How to start a program that runs beside this one; each stream is this process's own (`inherit`) unless asked. */
143
+ export type SpawnOptions = {
144
+ /** Its working folder. */
145
+ readonly cwd?: string;
146
+ /** Variables added to its environment (or its whole environment, with `clearEnv`). */
147
+ readonly env?: Readonly<Record<string, string>>;
148
+ /** Start it with no variable but those of `env`. */
149
+ readonly clearEnv?: boolean;
150
+ /** Its standard input: a `WritableStream` (`piped`), this process's own (the default), or none. */
151
+ readonly stdin?: Stdio;
152
+ /** Its standard output: a `ReadableStream` (`piped`), this process's own (the default), or thrown away. */
153
+ readonly stdout?: Stdio;
154
+ /** Its standard error: a `ReadableStream` (`piped`), this process's own (the default), or thrown away. */
155
+ readonly stderr?: Stdio;
156
+ /** Stopping it: SIGTERM when the signal aborts, then SIGKILL after `killAfterMs`. */
157
+ readonly signal?: AbortSignal;
158
+ /** How long a program being stopped has between SIGTERM and SIGKILL (5000 ms by default), by `signal` or by `await using`. */
159
+ readonly killAfterMs?: number;
160
+ };
161
+ /** A program while it runs `await using` stops it (SIGTERM, then SIGKILL) where it still runs, and waits for it. */
162
+ export type Child = AsyncDisposable & {
163
+ /** Its process id. */
164
+ readonly pid: number;
165
+ /** Its standard input, where it is piped; closing the stream closes its input. */
166
+ readonly stdin: WritableStream<Uint8Array> | null;
167
+ /** Its standard output, where it is piped. */
168
+ readonly stdout: ReadableStream<Uint8Array> | null;
169
+ /** Its standard error, where it is piped. */
170
+ readonly stderr: ReadableStream<Uint8Array> | null;
171
+ /** How it ended, once it ends; rejected with the runtime's error where it could not be started. */
172
+ readonly status: Promise<Status>;
173
+ /** Sends it a signal (SIGTERM by default); nothing where it has already ended. */
174
+ kill(signal?: KillSignal): void;
175
+ /** Its whole output and error, read from the piped streams (empty where not piped), and its status, once it ends. */
176
+ output(): Promise<Output>;
177
+ /** It keeps this process alive until it ends (the default). */
178
+ ref(): void;
179
+ /** It no longer keeps this process alive; nor do its pipes. */
180
+ unref(): void;
181
+ };
182
+ /**
183
+ * 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
184
+ * 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
185
+ * program does, and the program is given its `TRACEPARENT` (0006-signals FR-018), as for `output`.
186
+ *
187
+ * @example
188
+ * ```ts
189
+ * import { spawn } from "./proc.js";
190
+ * await using child = spawn(["gzip", "-dc"], { stdin: "piped", stdout: "piped" });
191
+ * ```
192
+ */
193
+ export declare function spawn(argv: readonly string[], options?: SpawnOptions): Child;
194
+ /** A signal this process can listen for. */
195
+ export type Signal = "SIGINT" | "SIGTERM" | "SIGHUP" | "SIGQUIT" | "SIGUSR1" | "SIGUSR2" | "SIGWINCH" | "SIGBREAK";
196
+ /** A function called when the process receives the signal. */
197
+ export declare function addSignalListener(signal: Signal, handler: () => void): void;
198
+ /** A function no longer called for the signal. */
199
+ export declare function removeSignalListener(signal: Signal, handler: () => void): void;
200
+ /** A promise that settles after `ms` milliseconds; an aborted `signal` rejects it early with the signal's reason. */
201
+ export declare function sleep(ms: number, signal?: AbortSignal): Promise<void>;
202
+ /** A timer that can be cleared, by call or by `using`. */
203
+ export type Timer = Disposable & {
204
+ /** The timer cleared: its function is not called. */
205
+ clear(): void;
206
+ };
207
+ /**
208
+ * Calls `callback` after `ms` milliseconds, with a timer that never keeps the process alive (FR-053): where nothing
209
+ * 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
210
+ * runtime.
211
+ */
212
+ export declare function unrefTimer(callback: () => void, ms: number): Timer;
213
+ /** What `selfCommand` reads of the running process: `process.execPath`, `process.argv` and `process.execArgv`, and the runtime. */
214
+ export type SelfFacts = {
215
+ readonly runtime: RuntimeName;
216
+ readonly execPath: string;
217
+ readonly argv: readonly string[];
218
+ readonly execArgv: readonly string[];
219
+ };
220
+ /** The facts of this process, for `selfCommandOf`. */
221
+ export declare function selfFacts(): SelfFacts;
222
+ /**
223
+ * 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:
224
+ * - 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
225
+ * `B:\~BUN\...` on Windows), where it keeps the code it compiled in;
226
+ * - the executable, `process.execPath`, is not named as a runtime is (`bun`, `node`, with any version or `.exe`): the binaries
227
+ * that `bun build --compile` and Node's single executable applications make are named after the program.
228
+ */
229
+ export declare function isCompiled(facts: SelfFacts): boolean;
230
+ /**
231
+ * The argument vector that runs the program again with `args` (FR-053): from a compiled binary,
232
+ * 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.
233
+ */
234
+ export declare function selfCommandOf(facts: SelfFacts, args?: readonly string[]): readonly string[];
235
+ /** The argument vector that runs this program again with `args`, on Bun and Node and from a binary Bun compiled (FR-053). */
236
+ export declare function selfCommand(args?: readonly string[]): readonly string[];
237
+ /** One address of one network interface. */
238
+ export type NetworkInterfaceInfo = {
239
+ /** The interface's name (`lo`, `eth0`, `en0`, `Ethernet`). */
240
+ readonly name: string;
241
+ /** The address's family. */
242
+ readonly family: "IPv4" | "IPv6";
243
+ /** The address. */
244
+ readonly address: string;
245
+ /** Its netmask. */
246
+ readonly netmask: string;
247
+ /** The address with its prefix length (`127.0.0.1/8`), where known. */
248
+ readonly cidr: string | null;
249
+ /** The IPv6 scope, where there is one. */
250
+ readonly scopeid: number | null;
251
+ /** The hardware address (`00:00:00:00:00:00` where there is none). */
252
+ readonly mac: string;
253
+ /** Whether it is internal (a loopback), not reachable from outside. */
254
+ readonly internal: boolean;
255
+ };
256
+ /** Every address of every network interface of this computer (0005-typescript-runtime FR-056). */
257
+ export declare function networkInterfaces(): readonly NetworkInterfaceInfo[];