Spawn import {spawn} from '@fuzdev/gro/spawn.js'; The spawn host module's root handle. Import it where authority enters
(a task, a script, an entry module) and hand a narrower spawn.narrow(...)
or a single SpawnProgram down.
The spawn host module: starting programs through handles pinned to one executable.
A SpawnProgram is the capability to run one executable, the shape a spawn grant takes on
the runtime. spawn.program('git') resolves the name once, synchronously, walking the
host's PATH: only absolute entries, the first regular executable. The real path is pinned
for the handle's life, so a later PATH change never changes which binary runs.
The walk skips every entry spelled as a node_modules/.bin directory, which npm run and
deno task put ahead of the rest, so a dependency's bin in one can't shadow git, and a
project's tools are reached only by a name containing /.
A name containing / resolves against the project root instead, and one that's absolute
or climbs above the project through ..
is not_granted, a check of the name as written, since a symlink beneath the project can
lead anywhere. A native binary runs at its pinned real path. A bare name is its own argv[0],
because a multicall binary (~/.cargo/bin/cargo -> rustup) dispatches on it, and a name
containing / passes its lexical project-absolute path, so a tool that finds itself through
argv[0] (a virtualenv's python) still does under another cwd. A #! script runs at the
path it was found at, the PATH entry's or the lexical project-absolute one, symlinks
included, since the kernel hands its interpreter that path as $0 in place of argv[0],
and a script that dispatches on the name it was called through (Debian's psql, a link to
pg_wrapper) needs it. A script is pinned by identity, the device and inode of the descriptor
its first bytes were read from, and each launch stats the found path again and refuses it,
launch_failed, when it leads to another file: a link retargeted, or a file renamed over the
pin. The same file reached by a new real path, a directory above it moved and linked back,
still runs, and a script rewritten in place, or deleted and recreated on a reused inode, still
matches. The check comes before the exec, and the interpreter opens $0 by path after it, so
a link retargeted before the interpreter opens the script runs what it then leads to. In that window, whoever can write
a directory on the found path can redirect a held handle, where a native binary is reached
only through its pin's own path. A native binary runs at its pin, unchecked.
The interpreter a #! line names is never pinned or confined: the kernel finds it at each
exec, so a relative one resolves against the call's cwd, and a script beneath
program_in's handle can name one outside it.
A file this user can't read can't be told apart, so it's taken as native: an unreadable script
pins, and fails at each call when its interpreter can't open it.
A call is argv only, never a shell string, its name and arguments checked strings.
A file is pinned only when its first bytes are #! or the native binary magic of the
host's platform, Mach-O on macOS and ELF elsewhere, since on Linux execvp, which Node's
child start uses, hands any other file the kernel won't run to /bin/sh. A file with execute
permission this user can't read passes, as it can't be inspected, and binfmt_misc
formats are refused. .bat and .cmd are refused,
as what cmd.exe would interpret. A non-zero exit is a result;
SpawnError (spawn_error.ts) means a program couldn't be found or started, a call whose
signal had already aborted included, which starts nothing. Handles come only from
this module, hold their pin, the path they run at, argv[0], and environment in private
fields, and are frozen with their prototypes, so a method called on any other object throws
TypeError. They're null-prototype, so awaiting one adopts no polluted Object.prototype.then.
spawn.narrow(names) keeps only named programs, and narrowing can only shrink.
A narrowed root refuses env, which turns a named program into arbitrary execution
(LD_PRELOAD), and pass_env: 'all' and pass_env globs, so a holder of a narrowed root
can't take the whole environment. Named pass_env stays, forwarding one host value at a
time. To give a library a program with an environment, build the SpawnProgram at the
root and hand that down.
spawn.program_in(dir, name) resolves name beneath the directory of an fs handle instead,
for a program a run builds outside the project, by the rules dir resolves any path with:
an absolute name, a .. above dir, an absolute symlink, or a relative one that climbs out
is not_granted, and a relative symlink that stays inside is followed. The name is pinned as
a name containing / is, its argv[0] and a script's $0 the path it was found at, absolute.
dir must be a handle this copy of fs made, checked through a registry that links no
fs (internal/fs_handles.ts), so a forged object is a TypeError, and a call's cwd is
checked the same way. A narrowed root refuses program_in and find_in, as a set of names
can't grant a directory. To let a library run what it builds, bind the directory at the
root: (name) => spawn.program_in(cache, name).
A child's environment is cleared, the rules of the runtime's grant: PATH, HOME, TMPDIR,
and TERM when the host has them, LC_ALL=C, the host's own NO_COLOR and FORCE_COLOR, then
the names pass_env lists, then the values env gives, all fixed when the handle is made,
never per call. pass_env: 'all' is the hatch that hands over the host's whole environment,
as strong as -A, so use it only where a person chose it, and review it as such.
omit_env beside it leaves out exact names, case-sensitive and never a glob.
start is a long-lived SpawnChild, timeout_ms and signal end a call's child
(SIGTERM, then SIGKILL after a grace period), and a call ended that way resolves to a
result of kind timed_out or aborted, never a rejection. A child with no inherited stdio
is the leader of its own process group, in a new session, so a stop, the cap, and the drain
bound reach what it left behind. A child with an inherited stream stays in the terminal's
session and foreground group, since a new session would lose the terminal: /dev/tty prompts
and Ctrl-C reaching it. Such a child is stopped by pid alone. After the direct child exits,
a call waits a bounded time for its pipes to close, then kills the group and stops reading,
so a background grandchild holding a pipe can't hang it. A reader behind at that bound keeps
what's buffered and can still read the rest. A stop's SIGKILL still reaches the group after
the leader exits. A background process with its pipes redirected holds nothing the call waits
on, so when no stop has begun it outlives the call. A child still running when
the host exits is killed, by one hook installed on the first spawn, and while a child in
a group of its own runs, the signals that end the host, but for SIGQUIT, kill its group first.
A child with an inherited stream is sent a SIGTERM of the host, so a chain of hosts passes it
all the way down.
Option objects are read once, each option's value read once into a null-prototype object
and checked, so a getter can't change one between its check and its use. Only own
properties count as options, so a polluted Object.prototype can't set one on a plain {}.
This is the Node implementation, which runs on the Node Gro. Its gaps against the runtime's builtin, which it documents rather than the API weakening to match:
program_in resolves beneath its handle by fs's walk, a check then a use, so a symlink
swapped in before the pin escapes the handle, as it would an fs op.outside_root, renamed away and a symlink left at the path), a call runs in
what the symlink leads to.cat /dev/stdin, fails with ENXIO.Object.prototype.encoding, highWaterMark, objectMode, or signal makes
Node's spawn throw after the fork, so the call rejects launch_failed with the child untracked
and running, and with stdin data a child reading its stdin never gets EOF and keeps the host
alive.detached, which is setsid: a child with no inherited stdio has no
controlling terminal, so a program prompting on /dev/tty under out or out_bytes without
stdin: 'inherit' can't.
A child with an inherited stream isn't grouped, so a stop reaches it by pid alone and
anything it left behind survives. Node has no PDEATHSIG, so a SIGKILL of the host leaves
every child behind, and a host killed by SIGINT or SIGHUP leaves an inheriting
child to what the terminal delivers. Passing SIGINT on would double a terminal's, which
makes some programs force-quit, and a listener for SIGHUP would end a nohup host.SIGQUIT isn't hooked, as a listener would keep a host stuck in synchronous code from
dumping core, the signal's use, so a SIGQUIT of the host leaves a group running too.SIGHUP a nohup host
would ignore reaches the signal hook, kills the group, and ends the host.signal-exit)
defers to the hook while the hook defers to it, and the signal ends nothing. A once
listener prepended after a group started has removed itself before the hook counts it.Array.isArray, Number.isSafeInteger, the process functions, the timers, Buffer.prototype.copy,
and Object's assign, create, freeze, keys, and hasOwn, and its own objects are null-prototype, but
code that patches Array.prototype, Set.prototype, String.prototype, Promise, Uint8Array,
TextDecoder, Error, EventEmitter.prototype.on, or the stream classes after this module
loads runs inside these ops, and a patched on or stream method holds the raw ChildProcess
or stream.node:child_process, so a narrowed spawn bounds only code
that uses it, a review signal, not a boundary.#! reads only the first bytes, so a file with a native magic
the kernel won't load, or a #! line naming no interpreter or one too long for the kernel's
buffer, still reaches Linux's /bin/sh fallback, and a Java class file passes on macOS,
sharing the fat binary's magic.{kind: 'exited', code: 0},
since Node passes an empty signal name for one.NODE_V8_COVERAGE into every child's environment.14 declarations
Spawn import {spawn} from '@fuzdev/gro/spawn.js'; The spawn host module's root handle. Import it where authority enters
(a task, a script, an entry module) and hand a narrower spawn.narrow(...)
or a single SpawnProgram down.
Spawn import type {Spawn} from '@fuzdev/gro/spawn.js'; The spawn host module's root: makes program handles and narrower roots.
programResolves name and pins it for the handle's life.
A bare name walks the host's PATH, skipping its node_modules/.bin entries,
and a name containing / resolves against the project root.
Options are read and checked before the name resolves.
type (name: string, options?: SpawnProgramOptions | undefined): SpawnProgram
namestringoptions?throws
TypeError - for a name that isn't a non-empty, well-formed string without NUL,
or a malformed optionSpawnError - `not_found`, `not_executable`, `not_granted`, the last also for `env`,
`pass_env: 'all'`, or a `pass_env` glob on a narrowed rootfindLike program, returning null when nothing is found.
type (name: string, options?: SpawnProgramOptions | undefined): SpawnProgram | null
namestringoptions?SpawnProgram | nullthe handle, or null on not_found
throws
TypeError - as `program` doesSpawnError - `not_executable`, `not_granted`program_inResolves name beneath the directory of dir, an fs handle, and pins it for the handle's
life, for a program a run builds outside the project.
name resolves as dir resolves any path: an absolute name, a .. above dir, an
absolute symlink, or a relative one that climbs out of dir is refused, and a relative
symlink that stays inside is followed. The pin, the script rules, and the environment are
program's, and argv[0] is the path the program was found at, absolute.
Options are read and checked before the name resolves.
type (dir: FsReadDir, name: string, options?: SpawnProgramOptions | undefined): SpawnProgram
diran fs handle from this copy of Gro, read-only or not
namea relative path beneath dir
stringoptions?throws
TypeError - for a `dir` that isn't such a handle, a name that isn't a non-empty,
well-formed string without NUL, or a malformed optionSpawnError - `not_found`; `not_executable`, also when resolving the name fails
another way, like a directory on the way this user can't search, the `FsError` as `cause`;
`not_granted` for a name leading outside `dir`, the `FsError` as `cause`, and for any call
on a narrowed root, as a set of names can't grant a directoryfind_inLike program_in, returning null when nothing is found.
A permission error is never read as nothing found.
type (dir: FsReadDir, name: string, options?: SpawnProgramOptions | undefined): SpawnProgram | null
diran fs handle from this copy of Gro, read-only or not
namea relative path beneath dir
stringoptions?SpawnProgram | nullthe handle, or null on not_found
throws
TypeError - as `program_in` doesSpawnError - `not_executable`, `not_granted`narrowA root that resolves only names, each spelled as it will be requested.
It can only shrink: a name this root doesn't allow throws rather than widens.
The root it returns refuses env, pass_env: 'all', and pass_env globs.
type (names: readonly string[]): Spawn
namesreadonly string[]throws
TypeError - for a name that isn't a non-empty, well-formed string without NULSpawnError - `not_granted`SpawnCallOptions import type {SpawnCallOptions} from '@fuzdev/gro/spawn.js'; Options for a call that starts a program.
cwd?The working directory, a handle rather than a path. Defaults to the project root.
A handle this copy of fs made, else a TypeError.
type FsReadDir
timeout_ms?Stops the child this many milliseconds after it starts, SIGTERM then SIGKILL after a
grace period. The call's result is then of kind timed_out.
A positive safe integer of at most 2147483647.
type number
signal?Stops the child when it aborts, as timeout_ms does, its result of kind aborted.
A signal that had aborted before the call starts nothing: the call throws SpawnError.
type AbortSignal
SpawnChild import type {SpawnChild} from '@fuzdev/gro/spawn.js'; A running child. pid is for display, and nothing takes a pid, so no surface here can
signal another process. Awaiting it does nothing, as it has no then.
Disposing it with await using stops it, SIGTERM then SIGKILL after a grace period,
and waits for closed.
AsyncDisposablepidThe child's process id, for display only.
type number
closedResolves when the child has ended and its pipes closed, or the wait for them was bounded after it exited. Never rejects.
type Promise<SpawnResult>
stdoutThe child's stdout, or null unless 'pipe'. Iterating is once only: a
second iteration throws TypeError, and leaving the loop early, or the iterator's
throw, discards the rest, the child still running. Chunks are plain Uint8Array copies. A stream nobody reads
pauses once its buffer fills, so the child can block on a full pipe.
type AsyncIterable<Uint8Array<ArrayBufferLike>, any, any> | null
stderrThe child's stderr, as stdout.
type AsyncIterable<Uint8Array<ArrayBufferLike>, any, any> | null
stdinThe child's stdin, or null unless 'pipe'.
type SpawnStdin | null
killSends signal, SIGTERM by default, to the child, or to its group when it leads
one, once per call, so SIGTERM then SIGKILL works.
type (signal?: SpawnSignal | undefined): boolean
signal?booleanfalse when the child has already ended and no signal was sent
throws
TypeError - for a `signal` that isn't an allowed nameSpawnOutOptions import type {SpawnOutOptions} from '@fuzdev/gro/spawn.js'; Options for a captured call.
max_bytes?The most bytes kept of each of stdout and stderr, a non-negative safe integer.
Past it the child is killed and the result is truncated. Defaults to 64 MiB.
type number
stdin?The child's stdin. 'ignore', the default, is /dev/null, and the child leads its own
process group, in a new session with no terminal, so a stop and the cap reach what it
left behind. 'inherit' shares the host's and keeps the child in the terminal's session,
as for any child with an inherited stream, so a command that may prompt (ssh, a credential
helper, a pinentry) still reaches /dev/tty. Such a child is stopped and capped by pid
alone, so a process it started outlives the call.
A Uint8Array is the data sent to the child's stdin through a pipe, which then closes,
empty data closing it at once. It's copied when the option is read, so changing the array
afterward changes nothing sent, and written while the output is read, so a child can fill
either pipe. Text goes through a TextEncoder, as a string here would collide with the mode
names. The child leads its own process group, as for 'ignore'. A child that exits or
closes its stdin before reading it all ends the write, which is no error, and the result
stands, so a call's result never says whether the data was read.
type "inherit" | "ignore" | Uint8Array<ArrayBufferLike>
SpawnOutput type ({ readonly kind: "exited"; readonly code: number; } & { readonly stdout: string; readonly stderr: string; readonly truncated: boolean; }) | ({ readonly kind: "signaled"; readonly signal: string; } & { readonly stdout: string; readonly stderr: string; readonly truncated: boolean; }) | ({ readonly kind: "timed_out" | "aborted"; readonly code: number | null; readonly signal: string | null; } & { readonly stdout: string; readonly stderr: string; readonly truncated: boolean; })
import type {SpawnOutput} from '@fuzdev/gro/spawn.js'; A captured call's result. stdout and stderr decode as UTF-8, with U+FFFD for
bytes that aren't, each at most max_bytes before decoding.
truncated is true when output passed max_bytes and the child was killed
with SIGKILL, its kind then signaled unless it exited first, or when a process it left
running still held a pipe when the wait for it ended, so output may be missing from the end.
SpawnOutputBytes type ({ readonly kind: "exited"; readonly code: number; } & { readonly stdout: Uint8Array<ArrayBufferLike>; readonly stderr: Uint8Array<ArrayBufferLike>; readonly truncated: boolean; }) | ({ readonly kind: "signaled"; readonly signal: string; } & { readonly stdout: Uint8Array<ArrayBufferLike>; readonly stderr: Uint8Array<ArrayBufferLike>; readonly truncated: boolean; }) | ({ readonly kind: "timed_out" | "aborted"; readonly code: number | null; readonly signal: string | null; } & { readonly stdout: Uint8Array<ArrayBufferLike>; readonly stderr: Uint8Array<ArrayBufferLike>; readonly truncated: boolean; })
import type {SpawnOutputBytes} from '@fuzdev/gro/spawn.js'; A byte-captured call's result. stdout and stderr are exactly the bytes the child wrote,
each at most max_bytes, plain Uint8Arrays holding their own memory. truncated is as for
SpawnOutput.
SpawnProgram import type {SpawnProgram} from '@fuzdev/gro/spawn.js'; One executable, pinned when the handle is made. name and path are for display:
the pin is private, so changing what path says changes nothing that runs.
nameThe name the program was granted. A bare name is also its argv[0],
a name containing / passes its project-absolute path instead,
and a name from program_in the absolute path it was found at beneath its handle.
A #! script's interpreter gets the path the script was found at as $0 in its place.
type string
pathThe pinned executable's real path, for display. A native binary runs at it, and a #!
script runs at the path it was found at, which must still lead to the same file.
type string
runRuns the program with stdio inherited, resolving when it ends. A non-zero exit is a result, not an error. An inheriting child is stopped by pid alone.
type (args: readonly string[], options?: SpawnCallOptions | undefined): Promise<SpawnResult>
argsthe arguments after argv[0]
readonly string[]options?Promise<SpawnResult>throws
TypeError - for an argument that isn't a well-formed string without NUL,
or a malformed optionSpawnError - `launch_failed`, also for a `signal` already aborted or a script
whose found path now leads to another fileoutRuns the program, capturing stdout and stderr as UTF-8 text, with stdin from /dev/null
unless stdin gives data to send or says 'inherit'. Output past max_bytes (64 MiB by
default) on either stream kills the child with SIGKILL, whose result is truncated, a
multi-byte character cut at the end becoming U+FFFD. A child leading its own process group
is killed as the group, and one with stdin inherited by pid alone.
After it exits, a background process still holding a pipe gets a bounded wait, then
the group, if there is one, is killed and reading stops, the result truncated because
output may be missing. A stop, the cap, and the child's exit end a stdin write in progress.
type (args: readonly string[], options?: SpawnOutOptions | undefined): Promise<SpawnOutput>
argsthe arguments after argv[0]
readonly string[]options?Promise<SpawnOutput>throws
TypeError - for an argument that isn't a well-formed string without NUL,
or a malformed optionSpawnError - `launch_failed`, also for a `signal` already aborted or a script
whose found path now leads to another fileRangeError - when memory for a stream can't be allocated, the child killed firstout_bytesCaptures as out does, with the same options, stdin data included, keeping stdout and
stderr as bytes, for output that isn't text, like a git blob.
type (args: readonly string[], options?: SpawnOutOptions | undefined): Promise<SpawnOutputBytes>
argsthe arguments after argv[0]
readonly string[]options?Promise<SpawnOutputBytes>throws
TypeError - for an argument that isn't a well-formed string without NUL,
or a malformed optionSpawnError - `launch_failed`, also for a `signal` already aborted or a script
whose found path now leads to another fileRangeError - when memory for a stream can't be allocated, the child killed firststartStarts the program and returns once it's running, the child held by the SpawnChild.
Stdio defaults to 'inherit'. A child with nothing inherited leads its own group.
type (args: readonly string[], options?: SpawnStartOptions | undefined): Promise<SpawnChild>
argsthe arguments after argv[0]
readonly string[]options?Promise<SpawnChild>throws
TypeError - for an argument that isn't a well-formed string without NUL,
or a malformed optionSpawnError - `launch_failed`, also for a `signal` already aborted or a script
whose found path now leads to another fileSpawnProgramOptions import type {SpawnProgramOptions} from '@fuzdev/gro/spawn.js'; How a program's environment is built, fixed when its handle is made.
pass_env?Host variables to pass by name, beyond the base set: a name or a PREFIX_* glob.
'all' passes the host's whole environment, as strong as -A.
A narrowed root takes names only.
type readonly string[] | "all"
omit_env?Host variables pass_env: 'all' leaves out, each an exact, case-sensitive name, never a glob.
Given with any other pass_env it's a TypeError.
Only what's forwarded changes, so env can still set one of these names, and Node still
adds what it copies itself, like NODE_V8_COVERAGE.
type readonly string[]
env?Explicit values, the last word over the base set and pass_env.
Given only when the handle is made: a call can't change a program's environment.
type Readonly<Record<string, string>>
SpawnResult type { readonly kind: "exited"; readonly code: number; } | { readonly kind: "signaled"; readonly signal: string; } | { readonly kind: "timed_out" | "aborted"; readonly code: number | null; readonly signal: string | null; }
import type {SpawnResult} from '@fuzdev/gro/spawn.js'; How a program ended. code is its exit code, or signal the signal that ended it.
timed_out and aborted are a child the module stopped for timeout_ms or signal, with
the code or signal it then ended by, the other null, so one that exits 0 on SIGTERM
is never mistaken for one that finished.
SpawnSignal type "SIGTERM" | "SIGKILL" | "SIGINT" | "SIGHUP" | "SIGQUIT" | "SIGUSR1" | "SIGUSR2"
import type {SpawnSignal} from '@fuzdev/gro/spawn.js'; A signal a child can be sent, by name. Numbers and other names are a TypeError.
SpawnStartOptions import type {SpawnStartOptions} from '@fuzdev/gro/spawn.js'; Options for start.
stdio?Each of stdin, stdout, and stderr, one value for all or the three in order. Defaults to 'inherit'.
A child with nothing inherited is the leader of its own process group.
type SpawnStdio | readonly [SpawnStdio, SpawnStdio, SpawnStdio]
SpawnStdin import type {SpawnStdin} from '@fuzdev/gro/spawn.js'; A started child's stdin.
writeWrites data, a string as UTF-8, resolving once it's accepted.
type (data: string | Uint8Array<ArrayBufferLike>): Promise<boolean>
datastring | Uint8Array<ArrayBufferLike>Promise<boolean>false when the child closed its stdin or ended, or after close, so the data went nowhere
throws
TypeError - for data that's neither a well-formed string nor a `Uint8Array`closeEnds the stream, resolving once it's flushed. Closing twice is harmless.
type (): Promise<void>
Promise<void>SpawnStdio type "inherit" | "pipe" | "ignore"
import type {SpawnStdio} from '@fuzdev/gro/spawn.js'; One stream of a started child: 'inherit' shares the host's, 'pipe' connects it
to the SpawnChild, and 'ignore' is /dev/null.