Skip to content
VaelJS Blog

Subprocesses, Exe Registry & File Locks (vael:exec)

vael:exec provides argv-only subprocess execution, PATH & fallback executable lookup (which/PathFinder), pre-spawn audit/veto logger hooks (addLogger), and OS advisory file locks (lockFile/lockFileSync).

1. Argv-Only Execution & Shell-Injection Immunity

Section titled “1. Argv-Only Execution & Shell-Injection Immunity”

vael:exec never spawns a shell (sh -c or cmd.exe /c). Every program name, argument, working directory, and environment variable is passed directly to the OS process launcher and checked against embedded NUL bytes (\0). User-supplied filenames containing ;, |, $(), backticks, or spaces are always literal arguments:

import { cmd, execSync } from "vael:exec";
const untrustedBranch = "feature/$(rm -rf /)";
// Form 1: argv array directly
const out1 = execSync(["git", "rev-parse", "--verify", untrustedBranch]);
// Form 2: fluent Command builder via cmd()
const out2 = cmd("git")
.args(["status", "--short"])
.cwd("./repo")
.timeout(10_000)
.execSync()
.validate(); // throws CommandError ("VAEL_EXEC_NON_ZERO") if !success
console.log(out2.lines());
  • exec / execSync (and Command.output() / outputSync()): Defaults to stdin: "null", stdout: "piped", stderr: "piped", capturing bounded bytes (default 16 MiB per stream, hard max 64 MiB) into an Output object with .text(), .lines(), .json<T>(), .errorText(), .errorLines(), and .validate().
  • run / runSync (and Command.status() / statusSync()): Defaults to inherited stdin/stdout/stderr ("inherit") for interactive or streaming terminal commands, returning CommandStatus ({ code, signal, success, timedOut }).
  • Fluent helpers on Command (vjs): await cmd("git").arg("status").text(), .lines(), or .json<T>() execute asynchronously, call .validate(), and decode stdout.
import { cmd, exec } from "vael:exec";
const res = await exec(
cmd("env")
.envClear()
.env("LC_ALL", "C")
.env("APP_MODE", "ci")
.stdin("input payload\n") // writes bytes to stdin and closes EOF
.timeout(5_000)
.killSignal("SIGTERM")
.killGrace(1_500),
);
console.log(res.validate().text());

2. Streaming spawn() & await using (vjs only)

Section titled “2. Streaming spawn() & await using (vjs only)”

For long-running subprocesses where you want to write to stdin incrementally, stream stdout/stderr, or terminate on demand, use spawn() (available in vjs only). ChildProcess implements [Symbol.asyncDispose]() so await using automatically sends SIGTERM and reaps the child if an early return or exception occurs:

import { cmd } from "vael:exec";
const decoder = new TextDecoder();
await using child = cmd("cat")
.stdin("piped")
.stdout("piped")
.stderr("piped")
.spawn();
console.log("Spawned PID:", child.pid);
await child.writeStdin("line 1\nline 2\n");
child.closeStdin();
while (true) {
const chunk = await child.readStdout(4096);
if (chunk.byteLength === 0) break; // EOF
console.log("Chunk:", decoder.decode(chunk));
}
const status = await child.wait();
console.log("Exited:", status.code, status.success);

You can also call child.tryWait() to poll non-blockingly, child.kill("SIGKILL") to terminate immediately, or await child.waitWithOutput({ timeout: 5_000 }) to close stdin and drain both streams concurrently.

3. PathFinder & pathFinder Cross-Platform Exe Registry

Section titled “3. PathFinder & pathFinder Cross-Platform Exe Registry”

Instead of hardcoding OS-specific executable paths or repeating whichSync() fallback chains, register tools in pathFinder (the default singleton consulted automatically whenever a Command runs) or instantiate your own new PathFinder():

import { cmd, execSync, pathFinder } from "vael:exec";
pathFinder.set("tar", {
name: "tar",
envVariable: "ACME_TAR_BIN",
linux: ["/usr/bin/tar", "/bin/tar"],
darwin: ["/opt/homebrew/bin/gtar", "/usr/bin/tar"],
windows: ["${SystemRoot}\\System32\\tar.exe"],
});
// Inspect the resolved path explicitly:
const resolved = pathFinder.findExeSync("tar");
console.log("Using tar:", resolved);
// Or run cmd("tar") directly — Command consults the singleton pathFinder automatically:
const out = cmd("tar").arg("--version").execSync().validate();
console.log(out.lines()[0]);

Resolution order for findExeSync(name) / findExe(name):

  1. envVariable override (if set and non-empty).
  2. cached path (unless noCache: true).
  3. PATH lookup (using executable or name).
  4. OS-specific fallback paths (linux, darwin, windows with ${VAR} / %VAR% expansion).

For simple one-off lookups without fallback arrays, use whichSync("git") / whichAllSync("python3") (or async which / whichAll in vjs).

4. Audit & Veto Loggers (addLogger, Command.log)

Section titled “4. Audit & Veto Loggers (addLogger, Command.log)”

vael:exec supports both global multi-sink loggers (addLogger / clearLoggers) and per-instance hooks (Command.log / Command.addLogger / Command.clearLoggers). Handlers run right before the subprocess spawns with (file, args, event) where event is a frozen object { file, args, cwd, mode }.

  • Audit logging: Record every external binary and argument list before execution.
  • Policy veto: Throwing an error inside a logger aborts the spawn before any OS process is created.
  • Scoped disposal: addLogger() returns a CommandLogSubscription implementing [Symbol.dispose](), so using unregisters the hook cleanly at block exit.
import { addLogger, cmd, execSync } from "vael:exec";
{
using _audit = addLogger((file, args, event) => {
console.log(`[exec:${event.mode}] ${file} ${args.join(" ")}`);
if (file.endsWith("rm") || file === "rm") {
throw new Error("Refusing destructive rm invocation");
}
});
// Logged and allowed
execSync(["echo", "safe"]);
}
// _audit is now disposed (active === false)

You can also attach a single per-command hook via cmd("git").log((file, args) => ...) or { log: ... } in CommandOptions, or multiple disposable per-command hooks via command.addLogger(...).

5. OS Advisory File Locks (lockFile / lockFileSync)

Section titled “5. OS Advisory File Locks (lockFile / lockFileSync)”

Coordinate concurrent scripts accessing shared state files, caches, or SQLite maintenance tasks with OS advisory locks (flock / LockFileEx). lockFile and lockFileSync reject symbolic links to prevent symlink-following lock escapes and return a FileLock implementing both [Symbol.dispose]() (using) and [Symbol.asyncDispose]() (await using):

import { lockFileSync } from "vael:exec";
function withExclusiveLock<T>(lockPath: string, fn: () => T): T {
using lock = lockFileSync(lockPath, {
mode: "exclusive", // or "shared" for concurrent readers
create: true,
timeout: 5_000, // throws VAEL_EXEC_LOCK_TIMEOUT if held > 5s
});
return fn();
}
withExclusiveLock("./state/deploy.lock", () => {
console.log("Running exclusive critical section");
});

Use nonBlocking: true (mutually exclusive with timeout) when you want immediate failure with VAEL_EXEC_LOCK_WOULD_BLOCK instead of waiting.

See the full vael:exec API Reference for every method and error code.