UEA-Prodem
This commit is contained in:
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2024 Tinylibs
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+323
@@ -0,0 +1,323 @@
|
||||
# tinyexec 📟
|
||||
|
||||
> A minimal package for executing commands
|
||||
|
||||
This package was created to provide a minimal way of interacting with child
|
||||
processes without having to manually deal with streams, piping, etc.
|
||||
|
||||
## Installing
|
||||
|
||||
```sh
|
||||
$ npm i -S tinyexec
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
A process can be spawned and awaited like so:
|
||||
|
||||
```ts
|
||||
import {x} from 'tinyexec';
|
||||
|
||||
const result = await x('ls', ['-l']);
|
||||
|
||||
// result.stdout - the stdout as a string
|
||||
// result.stderr - the stderr as a string
|
||||
// result.exitCode - the process exit code as a number
|
||||
```
|
||||
|
||||
By default, tinyexec does not throw on non‑zero exit codes. Check `result.exitCode` or pass `{throwOnError: true}`.
|
||||
|
||||
Output is returned exactly as produced; trailing newlines are not trimmed. If you need trimming, do it explicitly:
|
||||
|
||||
```ts
|
||||
const clean = result.stdout.replace(/\r?\n$/, '');
|
||||
```
|
||||
|
||||
You may also iterate over the lines of output via an async loop:
|
||||
|
||||
```ts
|
||||
import {x} from 'tinyexec';
|
||||
|
||||
const proc = x('ls', ['-l']);
|
||||
|
||||
for await (const line of proc) {
|
||||
// line will be from stderr/stdout in the order you'd see it in a term
|
||||
}
|
||||
```
|
||||
|
||||
### Options
|
||||
|
||||
Options can be passed to have finer control over spawning of the process:
|
||||
|
||||
```ts
|
||||
await x('ls', [], {
|
||||
timeout: 1000
|
||||
});
|
||||
```
|
||||
|
||||
The options object can have the following properties:
|
||||
|
||||
- `signal` - an `AbortSignal` to allow aborting of the execution
|
||||
- `timeout` - time in milliseconds at which the process will be forcibly killed
|
||||
- `persist` - if `true`, the process will continue after the host exits
|
||||
- `stdin` - `string` or another `Result` that will be used as the input to the process
|
||||
- `nodeOptions` - any valid options to node's underlying `spawn` function
|
||||
- `throwOnError` - if true, non-zero exit codes will throw an error
|
||||
- `nodePath` - if `false`, `node_modules/.bin` directories and the current node executable's directory will not be prepended to `PATH` (defaults to `true`)
|
||||
|
||||
### Passing a string to stdin
|
||||
|
||||
You can pass a string to `stdin`, which is useful for whitespace-sensitive values and for secrets that shouldn’t be exposed in shell history:
|
||||
|
||||
```ts
|
||||
const result = await x('gh', ['auth', 'login', '--with-token'], {
|
||||
stdin: process.env.GITHUB_TOKEN
|
||||
});
|
||||
|
||||
console.log(result.exitCode);
|
||||
```
|
||||
|
||||
### Piping to another process
|
||||
|
||||
You can pipe a process to another via the `pipe` method:
|
||||
|
||||
```ts
|
||||
const proc1 = x('ls', ['-l']);
|
||||
const proc2 = proc1.pipe('grep', ['.js']);
|
||||
const result = await proc2;
|
||||
|
||||
console.log(result.stdout);
|
||||
```
|
||||
|
||||
`pipe` takes the same options as a regular execution. For example, you can
|
||||
pass a timeout to the pipe call:
|
||||
|
||||
```ts
|
||||
proc1.pipe('grep', ['.js'], {
|
||||
timeout: 2000
|
||||
});
|
||||
```
|
||||
|
||||
### Killing a process
|
||||
|
||||
You can kill the process via the `kill` method:
|
||||
|
||||
```ts
|
||||
const proc = x('ls');
|
||||
|
||||
proc.kill();
|
||||
|
||||
// or with a signal
|
||||
proc.kill('SIGHUP');
|
||||
```
|
||||
|
||||
### Node modules/binaries
|
||||
|
||||
By default, node's available binaries from `node_modules` will be accessible
|
||||
in your command.
|
||||
|
||||
For example, in a repo which has `eslint` installed:
|
||||
|
||||
```ts
|
||||
await x('eslint', ['.']);
|
||||
```
|
||||
|
||||
In this example, `eslint` will come from the locally installed `node_modules`.
|
||||
|
||||
If you'd rather not have `node_modules/.bin` (or the directory of the current
|
||||
`node` executable) prepended to `PATH`, pass `nodePath: false`:
|
||||
|
||||
```ts
|
||||
await x('eslint', ['.'], {nodePath: false});
|
||||
```
|
||||
|
||||
### Using an abort signal
|
||||
|
||||
An abort signal can be passed to a process in order to abort it at a later
|
||||
time. This will result in the process being killed and `aborted` being set
|
||||
to `true`.
|
||||
|
||||
```ts
|
||||
const aborter = new AbortController();
|
||||
const proc = x('node', ['./foo.mjs'], {
|
||||
signal: aborter.signal
|
||||
});
|
||||
|
||||
// elsewhere...
|
||||
aborter.abort();
|
||||
|
||||
await proc;
|
||||
|
||||
proc.aborted; // true
|
||||
proc.killed; // true
|
||||
```
|
||||
|
||||
### Using with command strings
|
||||
|
||||
If you need to continue supporting commands as strings (e.g. "command arg0 arg1"),
|
||||
you can use [args-tokenizer](https://github.com/TrySound/args-tokenizer),
|
||||
a lightweight library for parsing shell command strings into an array.
|
||||
|
||||
```ts
|
||||
import {x} from 'tinyexec';
|
||||
import {tokenizeArgs} from 'args-tokenizer';
|
||||
|
||||
const commandString = 'echo "Hello, World!"';
|
||||
const [command, ...args] = tokenizeArgs(commandString);
|
||||
const result = await x(command, args);
|
||||
|
||||
result.stdout; // Hello, World!
|
||||
```
|
||||
|
||||
### Synchronous
|
||||
|
||||
You can use `xSync` for synchronous (blocking) execution:
|
||||
|
||||
```ts
|
||||
import {xSync} from 'tinyexec';
|
||||
|
||||
const result = xSync('ls', ['-l']);
|
||||
|
||||
// result.stdout - the stdout as a string
|
||||
// result.stderr - the stderr as a string
|
||||
// result.exitCode - the process exit code as a number
|
||||
```
|
||||
|
||||
Like the async API, you can iterate over lines:
|
||||
|
||||
```ts
|
||||
const result = xSync('ls', ['-l']);
|
||||
|
||||
for (const line of result) {
|
||||
// line will be from stdout then stderr
|
||||
}
|
||||
```
|
||||
|
||||
Since the synchronous API blocks the event loop, there are some features that are supported in the async API that the sync API does not support:
|
||||
|
||||
- `signal`
|
||||
- `persist`
|
||||
- `kill()` method
|
||||
- `stdin` piping
|
||||
- `pipe()` method
|
||||
|
||||
Other options like `timeout`, `throwOnError`, and `nodeOptions` work the same way.
|
||||
|
||||
## API
|
||||
|
||||
Calling `x(command[, args])` returns an awaitable `Result` which has the
|
||||
following API methods and properties available:
|
||||
|
||||
### `pipe(command[, args[, options]])`
|
||||
|
||||
Pipes the current command to another. For example:
|
||||
|
||||
```ts
|
||||
x('ls', ['-l'])
|
||||
.pipe('grep', ['js']);
|
||||
```
|
||||
|
||||
The parameters are as follows:
|
||||
|
||||
- `command` - the command to execute (_without any arguments_)
|
||||
- `args` - an array of arguments
|
||||
- `options` - options object
|
||||
|
||||
### `process`
|
||||
|
||||
The underlying Node.js `ChildProcess`. tinyexec keeps the surface minimal and does not re‑expose every child_process method/event. Use `proc.process` for advanced access (streams, events, etc.).
|
||||
|
||||
```ts
|
||||
const proc = x('node', ['./foo.mjs']);
|
||||
|
||||
proc.process?.stdout?.on('data', (chunk) => {
|
||||
// ...
|
||||
});
|
||||
proc.process?.once('close', (code) => {
|
||||
// ...
|
||||
});
|
||||
```
|
||||
|
||||
### `kill([signal])`
|
||||
|
||||
Kills the current process with the specified signal. By default, this will
|
||||
use the `SIGTERM` signal.
|
||||
|
||||
For example:
|
||||
|
||||
```ts
|
||||
const proc = x('ls');
|
||||
|
||||
proc.kill();
|
||||
```
|
||||
|
||||
### `pid`
|
||||
|
||||
The current process ID. For example:
|
||||
|
||||
```ts
|
||||
const proc = x('ls');
|
||||
|
||||
proc.pid; // number
|
||||
```
|
||||
|
||||
### `aborted`
|
||||
|
||||
Whether the process has been aborted or not (via the `signal` originally
|
||||
passed in the options object).
|
||||
|
||||
For example:
|
||||
|
||||
```ts
|
||||
const proc = x('ls');
|
||||
|
||||
proc.aborted; // bool
|
||||
```
|
||||
|
||||
### `killed`
|
||||
|
||||
Whether the process has been killed or not (e.g. via `kill()` or an abort
|
||||
signal).
|
||||
|
||||
For example:
|
||||
|
||||
```ts
|
||||
const proc = x('ls');
|
||||
|
||||
proc.killed; // bool
|
||||
```
|
||||
|
||||
### `exitCode`
|
||||
|
||||
The exit code received when the process completed execution.
|
||||
|
||||
For example:
|
||||
|
||||
```ts
|
||||
const proc = x('ls');
|
||||
|
||||
proc.exitCode; // number (e.g. 1)
|
||||
```
|
||||
|
||||
## Comparison with other libraries
|
||||
|
||||
`tinyexec` aims to provide a lightweight layer on top of Node's own
|
||||
`child_process` API.
|
||||
|
||||
Some clear benefits compared to other libraries are that `tinyexec` will be much lighter, have a much
|
||||
smaller footprint and will have a less abstract interface (less "magic"). It
|
||||
will also have equal security and cross-platform support to popular
|
||||
alternatives.
|
||||
|
||||
There are various features other libraries include which we are unlikely
|
||||
to ever implement, as they would prevent us from providing a lightweight layer.
|
||||
|
||||
For example, if you'd like write scripts rather than individual commands, and
|
||||
prefer to use templating, we'd definitely recommend
|
||||
[zx](https://github.com/google/zx). zx is a much higher level library which
|
||||
does some of the same work `tinyexec` does but behind a template string
|
||||
interface.
|
||||
|
||||
Similarly, libraries like `execa` will provide helpers for various things
|
||||
like passing files as input to processes. We opt not to support features like
|
||||
this since many of them are easy to do yourself (using Node's own APIs).
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
import { ChildProcess, SpawnOptions, SpawnSyncOptions } from "node:child_process";
|
||||
import { Readable } from "node:stream";
|
||||
|
||||
//#region src/normalize.d.ts
|
||||
interface NormalizedSpawnCommand {
|
||||
command: string;
|
||||
args: readonly string[];
|
||||
options: SpawnOptions;
|
||||
}
|
||||
/**
|
||||
* Normalizes the command and arguments to work cross-platform.
|
||||
* On Windows, this basically handles things like shebangs, calling
|
||||
* `node_modules/.bin` commands, and escaping meta characters.
|
||||
* On other platforms, it just returns the command and arguments as-is.
|
||||
*/
|
||||
declare function normalizeSpawnCommand(command: string, args?: readonly string[], options?: SpawnOptions): NormalizedSpawnCommand;
|
||||
//#endregion
|
||||
//#region src/non-zero-exit-error.d.ts
|
||||
declare class NonZeroExitError extends Error {
|
||||
readonly result: CommonOutputApi;
|
||||
readonly output?: Output | undefined;
|
||||
get exitCode(): number | undefined;
|
||||
constructor(result: CommonOutputApi, output?: Output | undefined);
|
||||
}
|
||||
//#endregion
|
||||
//#region src/main.d.ts
|
||||
interface Output {
|
||||
stderr: string;
|
||||
stdout: string;
|
||||
exitCode: number | undefined;
|
||||
}
|
||||
interface PipeOptions extends Options {}
|
||||
type KillSignal = Parameters<ChildProcess['kill']>[0];
|
||||
interface CommonOutputApi {
|
||||
get pid(): number | undefined;
|
||||
get killed(): boolean;
|
||||
get exitCode(): number | undefined;
|
||||
}
|
||||
interface OutputApi extends AsyncIterable<string>, CommonOutputApi {
|
||||
process: ChildProcess | undefined;
|
||||
get aborted(): boolean;
|
||||
pipe(command: string, args?: readonly string[], options?: Partial<PipeOptions>): Result;
|
||||
kill(signal?: KillSignal): boolean;
|
||||
}
|
||||
interface OutputApiSync extends Iterable<string>, CommonOutputApi {}
|
||||
type Result = PromiseLike<Output> & OutputApi;
|
||||
type SyncResult = Output & OutputApiSync;
|
||||
interface CommonOptions {
|
||||
timeout: number;
|
||||
throwOnError: boolean;
|
||||
nodePath: boolean;
|
||||
}
|
||||
interface Options extends CommonOptions {
|
||||
signal: AbortSignal;
|
||||
nodeOptions: SpawnOptions;
|
||||
persist: boolean;
|
||||
stdin: Result | ExecProcess | string;
|
||||
}
|
||||
interface SyncOptions extends CommonOptions {
|
||||
nodeOptions: SpawnSyncOptions;
|
||||
}
|
||||
interface TinyExec {
|
||||
(command: string, args?: readonly string[], options?: Partial<Options>): Result;
|
||||
}
|
||||
declare class ExecProcess implements Result {
|
||||
protected _process?: ChildProcess;
|
||||
protected _aborted: boolean;
|
||||
protected _options: Partial<Options>;
|
||||
protected _command: string;
|
||||
protected _args: readonly string[];
|
||||
protected _resolveClose?: () => void;
|
||||
protected _processClosed: Promise<void>;
|
||||
protected _thrownError?: Error;
|
||||
get process(): ChildProcess | undefined;
|
||||
get pid(): number | undefined;
|
||||
get exitCode(): number | undefined;
|
||||
constructor(command: string, args?: readonly string[], options?: Partial<Options>);
|
||||
kill(signal?: KillSignal): boolean;
|
||||
get aborted(): boolean;
|
||||
get killed(): boolean;
|
||||
pipe(command: string, args?: readonly string[], options?: Partial<PipeOptions>): Result;
|
||||
[Symbol.asyncIterator](): AsyncIterator<string>;
|
||||
protected _waitForOutput(): Promise<Output>;
|
||||
then<TResult1 = Output, TResult2 = never>(onfulfilled?: ((value: Output) => TResult1 | PromiseLike<TResult1>) | null, onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | null): Promise<TResult1 | TResult2>;
|
||||
protected _streamOut?: Readable;
|
||||
protected _streamErr?: Readable;
|
||||
spawn(): void;
|
||||
protected _resetState(): void;
|
||||
protected _onError: (err: Error) => void;
|
||||
protected _onClose: () => void;
|
||||
}
|
||||
declare function xSync(command: string, args?: readonly string[], options?: Partial<SyncOptions>): SyncResult;
|
||||
declare const x: TinyExec;
|
||||
declare const exec: TinyExec;
|
||||
declare const execSync: typeof xSync;
|
||||
//#endregion
|
||||
export { CommonOptions, CommonOutputApi, ExecProcess, KillSignal, NonZeroExitError, Options, Output, OutputApi, OutputApiSync, PipeOptions, Result, SyncOptions, SyncResult, TinyExec, exec, execSync, normalizeSpawnCommand, x, xSync };
|
||||
+388
@@ -0,0 +1,388 @@
|
||||
import { spawn as e, spawnSync as t } from "node:child_process";
|
||||
import { cwd as n } from "node:process";
|
||||
import { basename as r, delimiter as i, dirname as a, normalize as o, resolve as s } from "node:path";
|
||||
import { pipeline as c } from "node:stream/promises";
|
||||
import { PassThrough as l } from "node:stream";
|
||||
import u from "node:readline";
|
||||
import { closeSync as d, openSync as f, readSync as p, statSync as m } from "node:fs";
|
||||
//#region src/env.ts
|
||||
const h = /^path$/i;
|
||||
const g = {
|
||||
key: "PATH",
|
||||
value: ""
|
||||
};
|
||||
function _(e) {
|
||||
for (const t in e) {
|
||||
if (!Object.prototype.hasOwnProperty.call(e, t) || !h.test(t)) continue;
|
||||
const n = e[t];
|
||||
if (!n) return g;
|
||||
return {
|
||||
key: t,
|
||||
value: n
|
||||
};
|
||||
}
|
||||
return g;
|
||||
}
|
||||
function v(e, t) {
|
||||
const n = t.value.split(i);
|
||||
const r = [];
|
||||
let o = e;
|
||||
let c;
|
||||
do {
|
||||
r.push(s(o, "node_modules", ".bin"));
|
||||
c = o;
|
||||
o = a(o);
|
||||
} while (o !== c);
|
||||
r.push(a(process.execPath));
|
||||
const l = r.concat(n).join(i);
|
||||
return {
|
||||
key: t.key,
|
||||
value: l
|
||||
};
|
||||
}
|
||||
function y(e, t, n = true) {
|
||||
const r = {
|
||||
...process.env,
|
||||
...t
|
||||
};
|
||||
if (!n) return r;
|
||||
const i = v(e, _(r));
|
||||
r[i.key] = i.value;
|
||||
return r;
|
||||
}
|
||||
//#endregion
|
||||
//#region src/stream.ts
|
||||
const b = (e) => {
|
||||
let t = e.length;
|
||||
const n = new l();
|
||||
const r = () => {
|
||||
if (--t === 0) n.end();
|
||||
};
|
||||
for (const t of e) c(t, n, { end: false }).then(r).catch(r);
|
||||
return n;
|
||||
};
|
||||
//#endregion
|
||||
//#region src/normalize.ts
|
||||
const x = /([()\][%!^"`<>&|;, *?])/g;
|
||||
const S = /^#!\s*(.+)/;
|
||||
const C = /\.(?:com|exe)$/i;
|
||||
const w = /node_modules[\\/]\.bin[\\/][^\\/]+\.cmd$/i;
|
||||
const T = process.platform === "win32";
|
||||
const E = [
|
||||
".EXE",
|
||||
".CMD",
|
||||
".BAT",
|
||||
".COM"
|
||||
];
|
||||
/**
|
||||
* Normalizes the command and arguments to work cross-platform.
|
||||
* On Windows, this basically handles things like shebangs, calling
|
||||
* `node_modules/.bin` commands, and escaping meta characters.
|
||||
* On other platforms, it just returns the command and arguments as-is.
|
||||
*/
|
||||
function D(e, t = [], n = {}) {
|
||||
if (n.shell === true || !T) return {
|
||||
command: e,
|
||||
args: t,
|
||||
options: n
|
||||
};
|
||||
let i = O(e, n);
|
||||
let a = null;
|
||||
if (i !== null) {
|
||||
const e = 150;
|
||||
const t = Buffer.alloc(e);
|
||||
let n = null;
|
||||
try {
|
||||
n = f(i, "r");
|
||||
p(n, t, 0, e, 0);
|
||||
} catch {} finally {
|
||||
if (n !== null) d(n);
|
||||
}
|
||||
const o = t.toString().match(S);
|
||||
if (o !== null) {
|
||||
const e = o[1].trim();
|
||||
const t = e.indexOf(" ");
|
||||
const n = t !== -1 ? e.slice(0, t) : e;
|
||||
const i = t !== -1 ? e.slice(t + 1) : "";
|
||||
const s = r(n);
|
||||
a = s === "env" ? i || null : s;
|
||||
}
|
||||
}
|
||||
if (a !== null && i !== null) {
|
||||
t = [i, ...t];
|
||||
e = a;
|
||||
i = O(e, n);
|
||||
}
|
||||
if (i === null || !C.test(i)) {
|
||||
const r = i !== null && w.test(i);
|
||||
e = o(e);
|
||||
e = e.replace(x, "^$1");
|
||||
t = t.map((e) => {
|
||||
e = e.replace(/(?=(\\+?)?)\1"/g, "$1$1\\\"");
|
||||
e = e.replace(/(?=(\\+?)?)\1$/, "$1$1");
|
||||
e = `"${e}"`;
|
||||
e = e.replace(x, "^$1");
|
||||
if (r) e = e.replace(x, "^$1");
|
||||
return e;
|
||||
});
|
||||
t = [
|
||||
"/d",
|
||||
"/s",
|
||||
"/c",
|
||||
`"${[e, ...t].join(" ")}"`
|
||||
];
|
||||
e = n.env?.comspec ?? "cmd.exe";
|
||||
n = {
|
||||
...n,
|
||||
windowsVerbatimArguments: true
|
||||
};
|
||||
}
|
||||
return {
|
||||
command: e,
|
||||
args: t,
|
||||
options: n
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Resolves the command to an absolute path if possible.
|
||||
* Handles things like traversing PATH and adding extensions from PATHEXT
|
||||
*/
|
||||
function O(e, t) {
|
||||
const r = (t.cwd ?? n()).toString();
|
||||
const a = t.env ?? process.env;
|
||||
const o = _(a).value;
|
||||
const c = e.includes("/") || e.includes("\\") ? [""] : [r, ...o.split(i)];
|
||||
const l = a.PATHEXT ? a.PATHEXT.split(i) : E;
|
||||
if (e.includes(".") && l[0] !== "") l.unshift("");
|
||||
for (const t of c) {
|
||||
const n = s(r, t.startsWith("\"") && t.endsWith("\"") && t.length > 1 ? t.slice(1, -1) : t, e);
|
||||
for (const e of l) {
|
||||
const t = n + e;
|
||||
try {
|
||||
if (m(t).isFile()) return t;
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
//#endregion
|
||||
//#region src/non-zero-exit-error.ts
|
||||
var k = class extends Error {
|
||||
result;
|
||||
output;
|
||||
get exitCode() {
|
||||
if (this.result.exitCode !== null) return this.result.exitCode;
|
||||
}
|
||||
constructor(e, t) {
|
||||
super(`Process exited with non-zero status (${e.exitCode})`);
|
||||
this.result = e;
|
||||
this.output = t;
|
||||
}
|
||||
};
|
||||
//#endregion
|
||||
//#region src/main.ts
|
||||
const A = /\r?\n/;
|
||||
const j = {
|
||||
timeout: void 0,
|
||||
persist: false
|
||||
};
|
||||
const M = { timeout: void 0 };
|
||||
const N = { windowsHide: true };
|
||||
function P(e) {
|
||||
const t = new AbortController();
|
||||
for (const n of e) {
|
||||
if (n.aborted) {
|
||||
t.abort();
|
||||
return n;
|
||||
}
|
||||
const e = () => {
|
||||
t.abort(n.reason);
|
||||
};
|
||||
n.addEventListener("abort", e, { signal: t.signal });
|
||||
}
|
||||
return t.signal;
|
||||
}
|
||||
async function F(e) {
|
||||
let t = "";
|
||||
try {
|
||||
for await (const n of e) t += n.toString();
|
||||
} catch {}
|
||||
return t;
|
||||
}
|
||||
var I = class {
|
||||
_process;
|
||||
_aborted = false;
|
||||
_options;
|
||||
_command;
|
||||
_args;
|
||||
_resolveClose;
|
||||
_processClosed;
|
||||
_thrownError;
|
||||
get process() {
|
||||
return this._process;
|
||||
}
|
||||
get pid() {
|
||||
return this._process?.pid;
|
||||
}
|
||||
get exitCode() {
|
||||
if (this._process && this._process.exitCode !== null) return this._process.exitCode;
|
||||
}
|
||||
constructor(e, t, n) {
|
||||
this._options = {
|
||||
...j,
|
||||
...n
|
||||
};
|
||||
this._command = e;
|
||||
this._args = t ?? [];
|
||||
this._processClosed = new Promise((e) => {
|
||||
this._resolveClose = e;
|
||||
});
|
||||
}
|
||||
kill(e) {
|
||||
return this._process?.kill(e) === true;
|
||||
}
|
||||
get aborted() {
|
||||
return this._aborted;
|
||||
}
|
||||
get killed() {
|
||||
return this._process?.killed === true;
|
||||
}
|
||||
pipe(e, t, n) {
|
||||
return z(e, t, {
|
||||
...n,
|
||||
stdin: this
|
||||
});
|
||||
}
|
||||
async *[Symbol.asyncIterator]() {
|
||||
const e = this._process;
|
||||
if (!e) return;
|
||||
const t = [];
|
||||
if (this._streamErr) t.push(this._streamErr);
|
||||
if (this._streamOut) t.push(this._streamOut);
|
||||
const n = b(t);
|
||||
const r = u.createInterface({ input: n });
|
||||
for await (const e of r) yield e.toString();
|
||||
await this._processClosed;
|
||||
e.removeAllListeners();
|
||||
if (this._thrownError) throw this._thrownError;
|
||||
if (this._options?.throwOnError && this.exitCode !== 0 && this.exitCode !== void 0) throw new k(this);
|
||||
}
|
||||
async _waitForOutput() {
|
||||
const e = this._process;
|
||||
if (!e) throw new Error("No process was started");
|
||||
const [t, n] = await Promise.all([this._streamOut ? F(this._streamOut) : "", this._streamErr ? F(this._streamErr) : ""]);
|
||||
await this._processClosed;
|
||||
const { stdin: r } = this._options;
|
||||
if (r && typeof r !== "string") await r;
|
||||
e.removeAllListeners();
|
||||
if (this._thrownError) throw this._thrownError;
|
||||
const i = {
|
||||
stderr: n,
|
||||
stdout: t,
|
||||
exitCode: this.exitCode
|
||||
};
|
||||
if (this._options.throwOnError && this.exitCode !== 0 && this.exitCode !== void 0) throw new k(this, i);
|
||||
return i;
|
||||
}
|
||||
then(e, t) {
|
||||
return this._waitForOutput().then(e, t);
|
||||
}
|
||||
_streamOut;
|
||||
_streamErr;
|
||||
spawn() {
|
||||
const t = n();
|
||||
const r = this._options;
|
||||
const i = {
|
||||
...N,
|
||||
...r.nodeOptions
|
||||
};
|
||||
const a = [];
|
||||
this._resetState();
|
||||
if (r.timeout !== void 0) a.push(AbortSignal.timeout(r.timeout));
|
||||
if (r.signal !== void 0) a.push(r.signal);
|
||||
if (r.persist === true) i.detached = true;
|
||||
if (a.length > 0) i.signal = P(a);
|
||||
i.env = y(t, i.env, r.nodePath);
|
||||
const o = D(this._command, this._args, i);
|
||||
const s = e(o.command, o.args, o.options);
|
||||
if (s.stderr) this._streamErr = s.stderr;
|
||||
if (s.stdout) this._streamOut = s.stdout;
|
||||
this._process = s;
|
||||
s.once("error", this._onError);
|
||||
s.once("close", this._onClose);
|
||||
if (s.stdin) {
|
||||
const { stdin: e } = r;
|
||||
if (typeof e === "string") s.stdin.end(e);
|
||||
else e?.process?.stdout?.pipe(s.stdin);
|
||||
}
|
||||
}
|
||||
_resetState() {
|
||||
this._aborted = false;
|
||||
this._processClosed = new Promise((e) => {
|
||||
this._resolveClose = e;
|
||||
});
|
||||
this._thrownError = void 0;
|
||||
}
|
||||
_onError = (e) => {
|
||||
if (e.name === "AbortError" && (!(e.cause instanceof Error) || e.cause.name !== "TimeoutError")) {
|
||||
this._aborted = true;
|
||||
return;
|
||||
}
|
||||
this._thrownError = e;
|
||||
};
|
||||
_onClose = () => {
|
||||
if (this._resolveClose) this._resolveClose();
|
||||
};
|
||||
};
|
||||
function L(e, r, i) {
|
||||
const a = {
|
||||
...M,
|
||||
...i
|
||||
};
|
||||
const o = n();
|
||||
const s = {
|
||||
windowsHide: true,
|
||||
...a.nodeOptions
|
||||
};
|
||||
if (a.timeout !== void 0) s.timeout = a.timeout;
|
||||
s.env = y(o, s.env, a.nodePath);
|
||||
const c = D(e, r ?? [], s);
|
||||
const l = t(c.command, c.args, c.options);
|
||||
if (l.error) throw l.error;
|
||||
const u = l.stdout?.toString() ?? "";
|
||||
const d = l.stderr?.toString() ?? "";
|
||||
const f = l.status ?? void 0;
|
||||
const p = l.signal != null;
|
||||
const m = {
|
||||
stdout: u,
|
||||
stderr: d,
|
||||
get exitCode() {
|
||||
return f;
|
||||
},
|
||||
get pid() {
|
||||
return l.pid;
|
||||
},
|
||||
get killed() {
|
||||
return p;
|
||||
},
|
||||
*[Symbol.iterator]() {
|
||||
for (const e of [u, d]) {
|
||||
if (!e) continue;
|
||||
const t = e.split(A);
|
||||
if (t[t.length - 1] === "") t.pop();
|
||||
yield* t;
|
||||
}
|
||||
}
|
||||
};
|
||||
if (a.throwOnError && f !== 0 && f !== void 0) throw new k(m, m);
|
||||
return m;
|
||||
}
|
||||
const R = (e, t, n) => {
|
||||
const r = new I(e, t, n);
|
||||
r.spawn();
|
||||
return r;
|
||||
};
|
||||
const z = R;
|
||||
const B = L;
|
||||
//#endregion
|
||||
export { I as ExecProcess, k as NonZeroExitError, z as exec, B as execSync, D as normalizeSpawnCommand, R as x, L as xSync };
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
{
|
||||
"name": "tinyexec",
|
||||
"version": "1.2.4",
|
||||
"type": "module",
|
||||
"description": "A minimal library for executing processes in Node",
|
||||
"main": "./dist/main.mjs",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"files": [
|
||||
"dist",
|
||||
"THIRD-PARTY-LICENSES.txt"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "tsdown",
|
||||
"dev": "tsdown --watch",
|
||||
"format": "prettier --write src",
|
||||
"format:check": "prettier --check src",
|
||||
"lint": "tsc --noEmit && eslint src && publint",
|
||||
"prepare": "npm run build",
|
||||
"test": "npm run build && npm run test:unit",
|
||||
"test:unit": "vitest run"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/tinylibs/tinyexec.git"
|
||||
},
|
||||
"keywords": [
|
||||
"execa",
|
||||
"exec",
|
||||
"tiny",
|
||||
"child_process",
|
||||
"spawn"
|
||||
],
|
||||
"author": "James Garbutt (https://github.com/43081j)",
|
||||
"license": "MIT",
|
||||
"bugs": {
|
||||
"url": "https://github.com/tinylibs/tinyexec/issues"
|
||||
},
|
||||
"homepage": "https://github.com/tinylibs/tinyexec#readme",
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@types/node": "^25.9.1",
|
||||
"@vitest/coverage-v8": "^4.1.7",
|
||||
"eslint": "^10.4.0",
|
||||
"prettier": "^3.8.3",
|
||||
"publint": "^0.3.21",
|
||||
"tsdown": "^0.22.0",
|
||||
"typescript": "^6.0.3",
|
||||
"typescript-eslint": "^8.60.0",
|
||||
"vitest": "^4.0.7"
|
||||
},
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/main.d.mts",
|
||||
"default": "./dist/main.mjs"
|
||||
},
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"types": "./dist/main.d.mts"
|
||||
}
|
||||
Reference in New Issue
Block a user