@simbo/exec-file 0.0.0-stage → 1.0.0
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/CHANGELOG.md +24 -0
- package/LICENSE.md +20 -0
- package/README.md +164 -2
- package/dist/exec-file-error.d.ts +43 -0
- package/dist/exec-file-error.js +53 -0
- package/dist/exec-file-error.js.map +1 -0
- package/dist/exec-file.d.ts +38 -0
- package/dist/exec-file.js +173 -0
- package/dist/exec-file.js.map +1 -0
- package/dist/exec-file.types.d.ts +98 -0
- package/dist/exec-file.types.js +2 -0
- package/dist/exec-file.types.js.map +1 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -0
- package/package.json +65 -3
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# @simbo/exec-file
|
|
2
|
+
|
|
3
|
+
## 1.0.0
|
|
4
|
+
|
|
5
|
+
### Major Changes
|
|
6
|
+
|
|
7
|
+
- 3ae5e70: Add package `@simbo/exec-file` to run executables without a shell and
|
|
8
|
+
get their output as text or buffer.
|
|
9
|
+
|
|
10
|
+
- `execFile()` returns the standard output and standard error as text,
|
|
11
|
+
`execFileBuffer()` as buffers for binary data.
|
|
12
|
+
- Standard input is closed, so a command that reads it does not wait forever.
|
|
13
|
+
- Failures reject with an `ExecFileError<string>` or `ExecFileError<Buffer>`
|
|
14
|
+
that holds the executable, the arguments, the command line, the exit code,
|
|
15
|
+
the signal, and the output; the message names the command and the reason,
|
|
16
|
+
followed by the output shortened to 500 characters.
|
|
17
|
+
- `exitCode` is set only when the command exited on its own, not on a timeout,
|
|
18
|
+
so callers can tell a reported failure from a command that could not run to
|
|
19
|
+
completion.
|
|
20
|
+
- Options for the working directory, environment variables merged over
|
|
21
|
+
`process.env`, `maxBuffer` (default 256 MiB, limited to the maximum string
|
|
22
|
+
length of V8 for text), a timeout, an `AbortSignal`, and a `debug` callback.
|
|
23
|
+
- `formatCommand()` formats a command line for messages.
|
|
24
|
+
- No dependencies; Windows batch files are not supported.
|
package/LICENSE.md
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright © 2026 Simon Lepel <simbo@simbo.de> (https://simbo.de)
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
|
6
|
+
this software and associated documentation files (the "Software"), to deal in
|
|
7
|
+
the Software without restriction, including without limitation the rights to
|
|
8
|
+
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
|
|
9
|
+
the Software, and to permit persons to whom the Software is furnished to do so,
|
|
10
|
+
subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
|
17
|
+
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
|
18
|
+
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
|
|
19
|
+
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
|
|
20
|
+
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,165 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Exec File
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
📦 [**`@simbo/exec-file`**](https://npmjs.com/package/@simbo/exec-file)
|
|
4
|
+
|
|
5
|
+
Run executables without a shell and get their output as text or buffer, with
|
|
6
|
+
errors that hold the exit code, the signal, and the output.
|
|
7
|
+
|
|
8
|
+
A small layer over `execFile` from `node:child_process` for command line tools,
|
|
9
|
+
GitHub Actions, and libraries that run programs such as Git or pnpm.
|
|
10
|
+
|
|
11
|
+
## Features
|
|
12
|
+
|
|
13
|
+
- `execFile()` returns the standard output and standard error as text
|
|
14
|
+
|
|
15
|
+
- `execFileBuffer()` returns them as buffers, for binary data
|
|
16
|
+
|
|
17
|
+
- Failures reject with an `ExecFileError` that holds the command, the exit code,
|
|
18
|
+
the signal, and the output, with a message that tells why the command failed
|
|
19
|
+
|
|
20
|
+
- Options for the working directory, environment variables merged over
|
|
21
|
+
`process.env`, `maxBuffer`, a timeout, and an `AbortSignal`
|
|
22
|
+
|
|
23
|
+
- A `debug` callback receives each command before it runs, for example
|
|
24
|
+
`core.debug` from `@actions/core`
|
|
25
|
+
|
|
26
|
+
- Zero dependencies
|
|
27
|
+
|
|
28
|
+
## Requirements
|
|
29
|
+
|
|
30
|
+
Requires Node.js `^24.15.0 || >=26.0.0`.
|
|
31
|
+
|
|
32
|
+
Windows batch files, such as the `.cmd` shims of npm packages, cannot run
|
|
33
|
+
without a shell, so they are not supported.
|
|
34
|
+
|
|
35
|
+
## Installation
|
|
36
|
+
|
|
37
|
+
Install `@simbo/exec-file` from the npm registry:
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
npm i @simbo/exec-file
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## Usage
|
|
44
|
+
|
|
45
|
+
For a complete API reference, see the
|
|
46
|
+
[documentation](https://simbo.de/packages/modules/_simbo_exec-file/).
|
|
47
|
+
|
|
48
|
+
```ts
|
|
49
|
+
import { execFile, execFileBuffer, ExecFileError } from '@simbo/exec-file';
|
|
50
|
+
|
|
51
|
+
const { stdout } = await execFile('pnpm', ['licenses', 'list', '--json'], {
|
|
52
|
+
cwd: '/path/to/repo',
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
const { stdout: blob } = await execFileBuffer('git', [
|
|
56
|
+
'cat-file',
|
|
57
|
+
'blob',
|
|
58
|
+
'HEAD:image.png',
|
|
59
|
+
]);
|
|
60
|
+
|
|
61
|
+
try {
|
|
62
|
+
await execFile('git', ['switch', 'missing-branch']);
|
|
63
|
+
} catch (error) {
|
|
64
|
+
if (error instanceof ExecFileError) {
|
|
65
|
+
console.error(error.exitCode, error.stderr);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
The output is returned unchanged; trim it where needed. Standard input is
|
|
71
|
+
closed, so a command that reads it gets the end of input instead of waiting.
|
|
72
|
+
|
|
73
|
+
### Options
|
|
74
|
+
|
|
75
|
+
| Option | Description | Default |
|
|
76
|
+
| ----------- | -------------------------------------------------------------------- | --------------- |
|
|
77
|
+
| `cwd` | The working directory of the command. | `process.cwd()` |
|
|
78
|
+
| `env` | Variables merged over `process.env`; `undefined` removes a variable. | none |
|
|
79
|
+
| `maxBuffer` | The largest output in bytes on standard output or standard error. | 256 MiB |
|
|
80
|
+
| `timeout` | Milliseconds after which the command is terminated with `SIGTERM`. | none |
|
|
81
|
+
| `signal` | An `AbortSignal` that terminates the command. | none |
|
|
82
|
+
| `debug` | A callback for the command and the working directory before it runs. | none |
|
|
83
|
+
|
|
84
|
+
For text, `maxBuffer` must not exceed the maximum string length of V8
|
|
85
|
+
(`buffer.constants.MAX_STRING_LENGTH`); `execFile()` rejects with a `RangeError`
|
|
86
|
+
otherwise. Use `execFileBuffer()` for larger output.
|
|
87
|
+
|
|
88
|
+
The option `signal` is an `AbortSignal`, while `ExecFileError.signal` is the
|
|
89
|
+
name of the signal that terminated a command, as in `node:child_process`.
|
|
90
|
+
|
|
91
|
+
### Errors
|
|
92
|
+
|
|
93
|
+
`execFile()` and `execFileBuffer()` reject with an `ExecFileError` if the
|
|
94
|
+
command cannot be started, exits with a non-zero code, is terminated, times out,
|
|
95
|
+
is aborted, or exceeds `maxBuffer`.
|
|
96
|
+
|
|
97
|
+
The message starts with the command and the reason, such as
|
|
98
|
+
`git status failed (exit code 128)`, followed by the trimmed standard error
|
|
99
|
+
output and, for `execFile()`, the standard output, shortened to 500 characters.
|
|
100
|
+
The properties hold the full details:
|
|
101
|
+
|
|
102
|
+
| Property | Description |
|
|
103
|
+
| ---------- | --------------------------------------------------------------------- |
|
|
104
|
+
| `file` | The executable. |
|
|
105
|
+
| `args` | The arguments. |
|
|
106
|
+
| `command` | The command line, for messages. |
|
|
107
|
+
| `exitCode` | The exit code, or `undefined` if the command did not exit on its own. |
|
|
108
|
+
| `signal` | The name of the signal that terminated the command, or `undefined`. |
|
|
109
|
+
| `stdout` | The standard output up to the failure. |
|
|
110
|
+
| `stderr` | The standard error output up to the failure. |
|
|
111
|
+
| `cause` | The original error of `node:child_process`. |
|
|
112
|
+
|
|
113
|
+
The output is text for `execFile()` and buffers for `execFileBuffer()`, typed as
|
|
114
|
+
`ExecFileError<string>` and `ExecFileError<Buffer>`. `exitCode` is `undefined`
|
|
115
|
+
for a timeout, even if the command exited with a code after `SIGTERM`.
|
|
116
|
+
|
|
117
|
+
Check `exitCode` to tell a command that reported a failure from one that could
|
|
118
|
+
not run to completion:
|
|
119
|
+
|
|
120
|
+
```ts
|
|
121
|
+
try {
|
|
122
|
+
await execFile('git', ['fetch', 'origin']);
|
|
123
|
+
} catch (error) {
|
|
124
|
+
if (error instanceof ExecFileError && error.exitCode === undefined) {
|
|
125
|
+
throw error; // the command did not run to completion
|
|
126
|
+
}
|
|
127
|
+
// the command ran and reported a failure
|
|
128
|
+
}
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
`formatCommand()` formats a command line the same way as the messages, quoting
|
|
132
|
+
the parts that contain special characters.
|
|
133
|
+
|
|
134
|
+
## Security
|
|
135
|
+
|
|
136
|
+
The arguments are passed to the executable as given, without a shell, so no
|
|
137
|
+
shell interprets them. The executable itself, however, may run commands that
|
|
138
|
+
some of its options name, such as `--upload-pack` for `git clone`.
|
|
139
|
+
`@simbo/exec-file` does not filter arguments.
|
|
140
|
+
|
|
141
|
+
Never pass untrusted values, such as user input or data from a pull request, as
|
|
142
|
+
options. Place them where the executable cannot read them as options, for
|
|
143
|
+
example after `--end-of-options` or `--` for Git.
|
|
144
|
+
|
|
145
|
+
### Secrets and Logs
|
|
146
|
+
|
|
147
|
+
`@simbo/exec-file` does not redact or escape anything. The `debug` message, the
|
|
148
|
+
`command`, and the message of an `ExecFileError` contain all arguments; the
|
|
149
|
+
error message also contains the start of the output, and `stdout` and `stderr`
|
|
150
|
+
hold it in full.
|
|
151
|
+
|
|
152
|
+
- Do not pass secrets as arguments. Pass them through `env` or a file instead,
|
|
153
|
+
for example a token for Git through `GIT_CONFIG_*` variables or a credential
|
|
154
|
+
helper.
|
|
155
|
+
- In GitHub Actions, the runner masks registered secrets in all log output.
|
|
156
|
+
Register every secret that an action reads or creates itself, such as an
|
|
157
|
+
installation token, with `core.setSecret()` before it can reach a command.
|
|
158
|
+
- The output of a command may contain lines that look like workflow commands,
|
|
159
|
+
such as `::stop-commands::`. Log messages and output only through functions
|
|
160
|
+
that escape them, such as `core.setFailed()`, `core.error()`, or
|
|
161
|
+
`core.warning()`, never raw through `console.log()` or `core.info()`.
|
|
162
|
+
|
|
163
|
+
## License
|
|
164
|
+
|
|
165
|
+
[MIT © Simon Lepel](https://simbo.mit-license.org/2026/)
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { ExecFileErrorDetails } from './exec-file.types.js';
|
|
2
|
+
/**
|
|
3
|
+
* An error thrown when a command fails, with the output as text for
|
|
4
|
+
* `execFile()` or as buffer for `execFileBuffer()`.
|
|
5
|
+
*/
|
|
6
|
+
export declare class ExecFileError<T extends Buffer | string = Buffer | string> extends Error {
|
|
7
|
+
/**
|
|
8
|
+
* The executable.
|
|
9
|
+
*/
|
|
10
|
+
readonly file: string;
|
|
11
|
+
/**
|
|
12
|
+
* The arguments.
|
|
13
|
+
*/
|
|
14
|
+
readonly args: readonly string[];
|
|
15
|
+
/**
|
|
16
|
+
* The command line, for messages.
|
|
17
|
+
*/
|
|
18
|
+
readonly command: string;
|
|
19
|
+
/**
|
|
20
|
+
* The exit code, or `undefined` if the command did not exit on its own.
|
|
21
|
+
*/
|
|
22
|
+
readonly exitCode: number | undefined;
|
|
23
|
+
/**
|
|
24
|
+
* The name of the signal that terminated the command, such as `SIGTERM`, or
|
|
25
|
+
* `undefined`.
|
|
26
|
+
*/
|
|
27
|
+
readonly signal: string | undefined;
|
|
28
|
+
/**
|
|
29
|
+
* The standard output up to the failure, unchanged.
|
|
30
|
+
*/
|
|
31
|
+
readonly stdout: T;
|
|
32
|
+
/**
|
|
33
|
+
* The standard error output up to the failure, unchanged.
|
|
34
|
+
*/
|
|
35
|
+
readonly stderr: T;
|
|
36
|
+
/**
|
|
37
|
+
* Creates an error for a failed command.
|
|
38
|
+
*
|
|
39
|
+
* @param message - The error message.
|
|
40
|
+
* @param details - The details of the failed command.
|
|
41
|
+
*/
|
|
42
|
+
constructor(message: string, details: ExecFileErrorDetails<T>);
|
|
43
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An error thrown when a command fails, with the output as text for
|
|
3
|
+
* `execFile()` or as buffer for `execFileBuffer()`.
|
|
4
|
+
*/
|
|
5
|
+
export class ExecFileError extends Error {
|
|
6
|
+
/**
|
|
7
|
+
* The executable.
|
|
8
|
+
*/
|
|
9
|
+
file;
|
|
10
|
+
/**
|
|
11
|
+
* The arguments.
|
|
12
|
+
*/
|
|
13
|
+
args;
|
|
14
|
+
/**
|
|
15
|
+
* The command line, for messages.
|
|
16
|
+
*/
|
|
17
|
+
command;
|
|
18
|
+
/**
|
|
19
|
+
* The exit code, or `undefined` if the command did not exit on its own.
|
|
20
|
+
*/
|
|
21
|
+
exitCode;
|
|
22
|
+
/**
|
|
23
|
+
* The name of the signal that terminated the command, such as `SIGTERM`, or
|
|
24
|
+
* `undefined`.
|
|
25
|
+
*/
|
|
26
|
+
signal;
|
|
27
|
+
/**
|
|
28
|
+
* The standard output up to the failure, unchanged.
|
|
29
|
+
*/
|
|
30
|
+
stdout;
|
|
31
|
+
/**
|
|
32
|
+
* The standard error output up to the failure, unchanged.
|
|
33
|
+
*/
|
|
34
|
+
stderr;
|
|
35
|
+
/**
|
|
36
|
+
* Creates an error for a failed command.
|
|
37
|
+
*
|
|
38
|
+
* @param message - The error message.
|
|
39
|
+
* @param details - The details of the failed command.
|
|
40
|
+
*/
|
|
41
|
+
constructor(message, details) {
|
|
42
|
+
super(message, { cause: details.cause });
|
|
43
|
+
this.name = 'ExecFileError';
|
|
44
|
+
this.file = details.file;
|
|
45
|
+
this.args = details.args;
|
|
46
|
+
this.command = details.command;
|
|
47
|
+
this.exitCode = details.exitCode;
|
|
48
|
+
this.signal = details.signal;
|
|
49
|
+
this.stdout = details.stdout;
|
|
50
|
+
this.stderr = details.stderr;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
//# sourceMappingURL=exec-file-error.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"exec-file-error.js","sourceRoot":"","sources":["../src/exec-file-error.ts"],"names":[],"mappings":"AAEA;;;GAGG;AACH,MAAM,OAAO,aAA2D,SAAQ,KAAK;IACnF;;OAEG;IACa,IAAI,CAAS;IAE7B;;OAEG;IACa,IAAI,CAAoB;IAExC;;OAEG;IACa,OAAO,CAAS;IAEhC;;OAEG;IACa,QAAQ,CAAqB;IAE7C;;;OAGG;IACa,MAAM,CAAqB;IAE3C;;OAEG;IACa,MAAM,CAAI;IAE1B;;OAEG;IACa,MAAM,CAAI;IAE1B;;;;;OAKG;IACH,YAAmB,OAAe,EAAE,OAAgC;QAClE,KAAK,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,OAAO,CAAC,KAAK,EAAE,CAAC,CAAC;QACzC,IAAI,CAAC,IAAI,GAAG,eAAe,CAAC;QAC5B,IAAI,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;QACzB,IAAI,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;QACzB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;QAC/B,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC;QACjC,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;QAC7B,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;QAC7B,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAC/B,CAAC;CACF","sourcesContent":["import type { ExecFileErrorDetails } from './exec-file.types.js';\n\n/**\n * An error thrown when a command fails, with the output as text for\n * `execFile()` or as buffer for `execFileBuffer()`.\n */\nexport class ExecFileError<T extends Buffer | string = Buffer | string> extends Error {\n /**\n * The executable.\n */\n public readonly file: string;\n\n /**\n * The arguments.\n */\n public readonly args: readonly string[];\n\n /**\n * The command line, for messages.\n */\n public readonly command: string;\n\n /**\n * The exit code, or `undefined` if the command did not exit on its own.\n */\n public readonly exitCode: number | undefined;\n\n /**\n * The name of the signal that terminated the command, such as `SIGTERM`, or\n * `undefined`.\n */\n public readonly signal: string | undefined;\n\n /**\n * The standard output up to the failure, unchanged.\n */\n public readonly stdout: T;\n\n /**\n * The standard error output up to the failure, unchanged.\n */\n public readonly stderr: T;\n\n /**\n * Creates an error for a failed command.\n *\n * @param message - The error message.\n * @param details - The details of the failed command.\n */\n public constructor(message: string, details: ExecFileErrorDetails<T>) {\n super(message, { cause: details.cause });\n this.name = 'ExecFileError';\n this.file = details.file;\n this.args = details.args;\n this.command = details.command;\n this.exitCode = details.exitCode;\n this.signal = details.signal;\n this.stdout = details.stdout;\n this.stderr = details.stderr;\n }\n}\n"]}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import type { ExecFileOptions, ExecFileResult } from './exec-file.types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Runs an executable and returns its output as UTF-8 text.
|
|
4
|
+
*
|
|
5
|
+
* The arguments are passed as given, without a shell. Executables that
|
|
6
|
+
* interpret arguments as commands, such as Git with `--upload-pack`, can still
|
|
7
|
+
* run them; pass untrusted values only where the executable cannot read them
|
|
8
|
+
* as options. Standard input is closed, so a command that reads it gets the
|
|
9
|
+
* end of input instead of waiting.
|
|
10
|
+
*
|
|
11
|
+
* @param file - The executable, as a name on the `PATH` or a path.
|
|
12
|
+
* @param args - The arguments.
|
|
13
|
+
* @param options - Options for running the command.
|
|
14
|
+
* @returns The command line and the unchanged output as text.
|
|
15
|
+
* @throws {RangeError} if `maxBuffer` exceeds the maximum string length of V8.
|
|
16
|
+
* @throws {ExecFileError} if the command cannot be started, exits with a non-zero code, is terminated, or exceeds `maxBuffer`.
|
|
17
|
+
*/
|
|
18
|
+
export declare function execFile(file: string, args: readonly string[], options?: ExecFileOptions): Promise<ExecFileResult<string>>;
|
|
19
|
+
/**
|
|
20
|
+
* Runs an executable and returns its raw output, for binary data.
|
|
21
|
+
*
|
|
22
|
+
* The arguments are passed as given, without a shell, as for `execFile()`.
|
|
23
|
+
*
|
|
24
|
+
* @param file - The executable, as a name on the `PATH` or a path.
|
|
25
|
+
* @param args - The arguments.
|
|
26
|
+
* @param options - Options for running the command.
|
|
27
|
+
* @returns The command line and the unchanged output as buffers.
|
|
28
|
+
* @throws {ExecFileError} if the command cannot be started, exits with a non-zero code, is terminated, or exceeds `maxBuffer`.
|
|
29
|
+
*/
|
|
30
|
+
export declare function execFileBuffer(file: string, args: readonly string[], options?: ExecFileOptions): Promise<ExecFileResult<Buffer>>;
|
|
31
|
+
/**
|
|
32
|
+
* Formats a command for messages, quoting the parts that contain special characters.
|
|
33
|
+
*
|
|
34
|
+
* @param file - The executable.
|
|
35
|
+
* @param args - The arguments.
|
|
36
|
+
* @returns The command line.
|
|
37
|
+
*/
|
|
38
|
+
export declare function formatCommand(file: string, args: readonly string[]): string;
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import { constants } from 'node:buffer';
|
|
2
|
+
import { execFile as nodeExecFile } from 'node:child_process';
|
|
3
|
+
import { cwd as processCwd, env as processEnv } from 'node:process';
|
|
4
|
+
import { promisify } from 'node:util';
|
|
5
|
+
import { ExecFileError } from './exec-file-error.js';
|
|
6
|
+
const execFileAsync = promisify(nodeExecFile);
|
|
7
|
+
/**
|
|
8
|
+
* The default for `maxBuffer`: 256 MiB, below the maximum string length of V8.
|
|
9
|
+
*/
|
|
10
|
+
const DEFAULT_MAX_BUFFER = 268_435_456;
|
|
11
|
+
/**
|
|
12
|
+
* The maximum length of the output in error messages.
|
|
13
|
+
*/
|
|
14
|
+
const MAX_OUTPUT_LENGTH = 500;
|
|
15
|
+
/**
|
|
16
|
+
* The largest number of bytes of a character in UTF-8.
|
|
17
|
+
*/
|
|
18
|
+
const MAX_UTF8_CHARACTER_BYTES = 4;
|
|
19
|
+
/**
|
|
20
|
+
* The bytes of each output decoded for error messages: enough for
|
|
21
|
+
* `MAX_OUTPUT_LENGTH` characters.
|
|
22
|
+
*/
|
|
23
|
+
const MAX_OUTPUT_BYTES = MAX_OUTPUT_LENGTH * MAX_UTF8_CHARACTER_BYTES;
|
|
24
|
+
/**
|
|
25
|
+
* Runs an executable and returns its output as UTF-8 text.
|
|
26
|
+
*
|
|
27
|
+
* The arguments are passed as given, without a shell. Executables that
|
|
28
|
+
* interpret arguments as commands, such as Git with `--upload-pack`, can still
|
|
29
|
+
* run them; pass untrusted values only where the executable cannot read them
|
|
30
|
+
* as options. Standard input is closed, so a command that reads it gets the
|
|
31
|
+
* end of input instead of waiting.
|
|
32
|
+
*
|
|
33
|
+
* @param file - The executable, as a name on the `PATH` or a path.
|
|
34
|
+
* @param args - The arguments.
|
|
35
|
+
* @param options - Options for running the command.
|
|
36
|
+
* @returns The command line and the unchanged output as text.
|
|
37
|
+
* @throws {RangeError} if `maxBuffer` exceeds the maximum string length of V8.
|
|
38
|
+
* @throws {ExecFileError} if the command cannot be started, exits with a non-zero code, is terminated, or exceeds `maxBuffer`.
|
|
39
|
+
*/
|
|
40
|
+
export async function execFile(file, args, options = {}) {
|
|
41
|
+
const { maxBuffer = DEFAULT_MAX_BUFFER } = options;
|
|
42
|
+
if (maxBuffer > constants.MAX_STRING_LENGTH) {
|
|
43
|
+
throw new RangeError(`maxBuffer must not exceed ${constants.MAX_STRING_LENGTH} for text output; use execFileBuffer() for larger output.`);
|
|
44
|
+
}
|
|
45
|
+
return run(file, args, options, output => output.toString('utf8'));
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Runs an executable and returns its raw output, for binary data.
|
|
49
|
+
*
|
|
50
|
+
* The arguments are passed as given, without a shell, as for `execFile()`.
|
|
51
|
+
*
|
|
52
|
+
* @param file - The executable, as a name on the `PATH` or a path.
|
|
53
|
+
* @param args - The arguments.
|
|
54
|
+
* @param options - Options for running the command.
|
|
55
|
+
* @returns The command line and the unchanged output as buffers.
|
|
56
|
+
* @throws {ExecFileError} if the command cannot be started, exits with a non-zero code, is terminated, or exceeds `maxBuffer`.
|
|
57
|
+
*/
|
|
58
|
+
export async function execFileBuffer(file, args, options = {}) {
|
|
59
|
+
return run(file, args, options, output => output);
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Formats a command for messages, quoting the parts that contain special characters.
|
|
63
|
+
*
|
|
64
|
+
* @param file - The executable.
|
|
65
|
+
* @param args - The arguments.
|
|
66
|
+
* @returns The command line.
|
|
67
|
+
*/
|
|
68
|
+
export function formatCommand(file, args) {
|
|
69
|
+
return [file, ...args].map(part => (/^[\w%+,./:=@^~-]+$/.test(part) ? part : JSON.stringify(part))).join(' ');
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Runs an executable with buffered output and converts the output.
|
|
73
|
+
*
|
|
74
|
+
* @param file - The executable.
|
|
75
|
+
* @param args - The arguments.
|
|
76
|
+
* @param options - Options for running the command.
|
|
77
|
+
* @param convert - Converts an output buffer into the result type.
|
|
78
|
+
* @returns The command line and the converted output.
|
|
79
|
+
* @throws {ExecFileError} if the command fails.
|
|
80
|
+
*/
|
|
81
|
+
async function run(file, args, options, convert) {
|
|
82
|
+
const { cwd = processCwd(), env, maxBuffer = DEFAULT_MAX_BUFFER, timeout, signal, debug } = options;
|
|
83
|
+
const command = formatCommand(file, args);
|
|
84
|
+
debug?.(`Running ${command} in ${cwd}`);
|
|
85
|
+
try {
|
|
86
|
+
const pending = execFileAsync(file, args, {
|
|
87
|
+
cwd,
|
|
88
|
+
env: env ? { ...processEnv, ...env } : processEnv,
|
|
89
|
+
encoding: 'buffer',
|
|
90
|
+
maxBuffer,
|
|
91
|
+
timeout,
|
|
92
|
+
signal,
|
|
93
|
+
});
|
|
94
|
+
// `execFile` keeps standard input open; close it so that a command that reads it does not wait forever.
|
|
95
|
+
pending.child.stdin?.end();
|
|
96
|
+
const { stdout, stderr } = await pending;
|
|
97
|
+
return { command, stdout: convert(stdout), stderr: convert(stderr) };
|
|
98
|
+
}
|
|
99
|
+
catch (error) {
|
|
100
|
+
throw toExecFileError({ file, args, command, timeout, convert }, error);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Converts an error of `execFile` from `node:child_process` into an `ExecFileError`.
|
|
105
|
+
*
|
|
106
|
+
* @param call - The command and how it was run.
|
|
107
|
+
* @param call.file - The executable.
|
|
108
|
+
* @param call.args - The arguments.
|
|
109
|
+
* @param call.command - The command line.
|
|
110
|
+
* @param call.timeout - The timeout of the command.
|
|
111
|
+
* @param call.convert - Converts an output buffer into the result type.
|
|
112
|
+
* @param error - The error of `execFile`.
|
|
113
|
+
* @returns The error for the failed command.
|
|
114
|
+
*/
|
|
115
|
+
function toExecFileError(call, error) {
|
|
116
|
+
const { file, args, command, timeout, convert } = call;
|
|
117
|
+
const { code, killed, signal, stdout, stderr } = (error ?? {});
|
|
118
|
+
const stdoutBuffer = Buffer.isBuffer(stdout) ? stdout : Buffer.alloc(0);
|
|
119
|
+
const stderrBuffer = Buffer.isBuffer(stderr) ? stderr : Buffer.alloc(0);
|
|
120
|
+
const stdoutValue = convert(stdoutBuffer);
|
|
121
|
+
const reason = failureReason({ code, killed, signal, timeout }, error);
|
|
122
|
+
// Binary standard output stays out of the message.
|
|
123
|
+
const output = shortenOutput(typeof stdoutValue === 'string' ? [stderrBuffer, stdoutBuffer] : [stderrBuffer]);
|
|
124
|
+
return new ExecFileError(`${command} failed (${reason})${output ? `\n${output}` : ''}`, {
|
|
125
|
+
file,
|
|
126
|
+
args,
|
|
127
|
+
command,
|
|
128
|
+
// A command that Node.js terminated, such as on timeout, did not exit on its own, even if it exited with a code.
|
|
129
|
+
exitCode: typeof code === 'number' && killed !== true ? code : undefined,
|
|
130
|
+
signal: typeof signal === 'string' ? signal : undefined,
|
|
131
|
+
stdout: stdoutValue,
|
|
132
|
+
stderr: convert(stderrBuffer),
|
|
133
|
+
cause: error,
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
/**
|
|
137
|
+
* Describes why a command failed: the timeout that terminated it, its exit
|
|
138
|
+
* code, the signal that terminated it, or the error that prevented it from
|
|
139
|
+
* running.
|
|
140
|
+
*
|
|
141
|
+
* @param failure - The properties of the error of `execFile`.
|
|
142
|
+
* @param failure.code - The exit code, or an error code such as `ENOENT`.
|
|
143
|
+
* @param failure.killed - Whether Node.js terminated the command.
|
|
144
|
+
* @param failure.signal - The signal that terminated the command.
|
|
145
|
+
* @param failure.timeout - The timeout of the command.
|
|
146
|
+
* @param error - The error of `execFile`.
|
|
147
|
+
* @returns The reason for messages.
|
|
148
|
+
*/
|
|
149
|
+
function failureReason(failure, error) {
|
|
150
|
+
const { code, killed, signal, timeout } = failure;
|
|
151
|
+
if (killed === true && timeout && typeof code !== 'string')
|
|
152
|
+
return `timed out after ${timeout} ms`;
|
|
153
|
+
if (typeof code === 'number')
|
|
154
|
+
return `exit code ${code}`;
|
|
155
|
+
if (typeof code !== 'string' && typeof signal === 'string')
|
|
156
|
+
return `terminated by ${signal}`;
|
|
157
|
+
return error instanceof Error ? error.message : String(error);
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Decodes the start of each output, joins the non-empty ones, and shortens
|
|
161
|
+
* them for messages, without decoding the full output.
|
|
162
|
+
*
|
|
163
|
+
* @param outputs - The output buffers.
|
|
164
|
+
* @returns The shortened output, or an empty string if there is none.
|
|
165
|
+
*/
|
|
166
|
+
function shortenOutput(outputs) {
|
|
167
|
+
const output = outputs
|
|
168
|
+
.map(part => part.subarray(0, MAX_OUTPUT_BYTES).toString('utf8').trim())
|
|
169
|
+
.filter(part => part.length > 0)
|
|
170
|
+
.join('\n');
|
|
171
|
+
return output.length > MAX_OUTPUT_LENGTH ? `${output.slice(0, MAX_OUTPUT_LENGTH)}…` : output;
|
|
172
|
+
}
|
|
173
|
+
//# sourceMappingURL=exec-file.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"exec-file.js","sourceRoot":"","sources":["../src/exec-file.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACxC,OAAO,EAAE,QAAQ,IAAI,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAC9D,OAAO,EAAE,GAAG,IAAI,UAAU,EAAE,GAAG,IAAI,UAAU,EAAE,MAAM,cAAc,CAAC;AACpE,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAEtC,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAGrD,MAAM,aAAa,GAAG,SAAS,CAAC,YAAY,CAAC,CAAC;AAE9C;;GAEG;AACH,MAAM,kBAAkB,GAAG,WAAW,CAAC;AAEvC;;GAEG;AACH,MAAM,iBAAiB,GAAG,GAAG,CAAC;AAE9B;;GAEG;AACH,MAAM,wBAAwB,GAAG,CAAC,CAAC;AAEnC;;;GAGG;AACH,MAAM,gBAAgB,GAAG,iBAAiB,GAAG,wBAAwB,CAAC;AAEtE;;;;;;;;;;;;;;;GAeG;AACH,MAAM,CAAC,KAAK,UAAU,QAAQ,CAC5B,IAAY,EACZ,IAAuB,EACvB,UAA2B,EAAE;IAE7B,MAAM,EAAE,S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QAAQ;QAAE,OAAO,aAAa,IAAI,EAAE,CAAC;IACzD,IAAI,OAAO,IAAI,KAAK,QAAQ,IAAI,OAAO,MAAM,KAAK,QAAQ;QAAE,OAAO,iBAAiB,MAAM,EAAE,CAAC;IAC7F,OAAO,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAChE,CAAC;AAED;;;;;;GAMG;AACH,SAAS,aAAa,CAAC,OAA0B;IAC/C,MAAM,MAAM,GAAG,OAAO;SACnB,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,EAAE,gBAAgB,CAAC,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,IAAI,EAAE,CAAC;SACvE,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC;SAC/B,IAAI,CAAC,IAAI,CAAC,CAAC;IACd,OAAO,MAAM,CAAC,MAAM,GAAG,iBAAiB,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC,EAAE,iBAAiB,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC;AAC/F,CAAC","sourcesContent":["import { constants } from 'node:buffer';\nimport { execFile as nodeExecFile } from 'node:child_process';\nimport { cwd as processCwd, env as processEnv } from 'node:process';\nimport { promisify } from 'node:util';\n\nimport { ExecFileError } from './exec-file-error.js';\nimport type { ExecFileOptions, ExecFileResult } from './exec-file.types.js';\n\nconst execFileAsync = promisify(nodeExecFile);\n\n/**\n * The default for `maxBuffer`: 256 MiB, below the maximum string length of V8.\n */\nconst DEFAULT_MAX_BUFFER = 268_435_456;\n\n/**\n * The maximum length of the output in error messages.\n */\nconst MAX_OUTPUT_LENGTH = 500;\n\n/**\n * The largest number of bytes of a character in UTF-8.\n */\nconst MAX_UTF8_CHARACTER_BYTES = 4;\n\n/**\n * The bytes of each output decoded for error messages: enough for\n * `MAX_OUTPUT_LENGTH` characters.\n */\nconst MAX_OUTPUT_BYTES = MAX_OUTPUT_LENGTH * MAX_UTF8_CHARACTER_BYTES;\n\n/**\n * Runs an executable and returns its output as UTF-8 text.\n *\n * The arguments are passed as given, without a shell. Executables that\n * interpret arguments as commands, such as Git with `--upload-pack`, can still\n * run them; pass untrusted values only where the executable cannot read them\n * as options. Standard input is closed, so a command that reads it gets the\n * end of input instead of waiting.\n *\n * @param file - The executable, as a name on the `PATH` or a path.\n * @param args - The arguments.\n * @param options - Options for running the command.\n * @returns The command line and the unchanged output as text.\n * @throws {RangeError} if `maxBuffer` exceeds the maximum string length of V8.\n * @throws {ExecFileError} if the command cannot be started, exits with a non-zero code, is terminated, or exceeds `maxBuffer`.\n */\nexport async function execFile(\n file: string,\n args: readonly string[],\n options: ExecFileOptions = {},\n): Promise<ExecFileResult<string>> {\n const { maxBuffer = DEFAULT_MAX_BUFFER } = options;\n if (maxBuffer > constants.MAX_STRING_LENGTH) {\n throw new RangeError(\n `maxBuffer must not exceed ${constants.MAX_STRING_LENGTH} for text output; use execFileBuffer() for larger output.`,\n );\n }\n return run(file, args, options, output => output.toString('utf8'));\n}\n\n/**\n * Runs an executable and returns its raw output, for binary data.\n *\n * The arguments are passed as given, without a shell, as for `execFile()`.\n *\n * @param file - The executable, as a name on the `PATH` or a path.\n * @param args - The arguments.\n * @param options - Options for running the command.\n * @returns The command line and the unchanged output as buffers.\n * @throws {ExecFileError} if the command cannot be started, exits with a non-zero code, is terminated, or exceeds `maxBuffer`.\n */\nexport async function execFileBuffer(\n file: string,\n args: readonly string[],\n options: ExecFileOptions = {},\n): Promise<ExecFileResult<Buffer>> {\n return run(file, args, options, output => output);\n}\n\n/**\n * Formats a command for messages, quoting the parts that contain special characters.\n *\n * @param file - The executable.\n * @param args - The arguments.\n * @returns The command line.\n */\nexport function formatCommand(file: string, args: readonly string[]): string {\n return [file, ...args].map(part => (/^[\\w%+,./:=@^~-]+$/.test(part) ? part : JSON.stringify(part))).join(' ');\n}\n\n/**\n * Runs an executable with buffered output and converts the output.\n *\n * @param file - The executable.\n * @param args - The arguments.\n * @param options - Options for running the command.\n * @param convert - Converts an output buffer into the result type.\n * @returns The command line and the converted output.\n * @throws {ExecFileError} if the command fails.\n */\nasync function run<T extends Buffer | string>(\n file: string,\n args: readonly string[],\n options: ExecFileOptions,\n convert: (output: Buffer) => T,\n): Promise<ExecFileResult<T>> {\n const { cwd = processCwd(), env, maxBuffer = DEFAULT_MAX_BUFFER, timeout, signal, debug } = options;\n const command = formatCommand(file, args);\n\n debug?.(`Running ${command} in ${cwd}`);\n\n try {\n const pending = execFileAsync(file, args, {\n cwd,\n env: env ? { ...processEnv, ...env } : processEnv,\n encoding: 'buffer',\n maxBuffer,\n timeout,\n signal,\n });\n // `execFile` keeps standard input open; close it so that a command that reads it does not wait forever.\n pending.child.stdin?.end();\n const { stdout, stderr } = await pending;\n return { command, stdout: convert(stdout), stderr: convert(stderr) };\n } catch (error) {\n throw toExecFileError({ file, args, command, timeout, convert }, error);\n }\n}\n\n/**\n * Converts an error of `execFile` from `node:child_process` into an `ExecFileError`.\n *\n * @param call - The command and how it was run.\n * @param call.file - The executable.\n * @param call.args - The arguments.\n * @param call.command - The command line.\n * @param call.timeout - The timeout of the command.\n * @param call.convert - Converts an output buffer into the result type.\n * @param error - The error of `execFile`.\n * @returns The error for the failed command.\n */\nfunction toExecFileError<T extends Buffer | string>(\n call: {\n file: string;\n args: readonly string[];\n command: string;\n timeout: number | undefined;\n convert: (output: Buffer) => T;\n },\n error: unknown,\n): ExecFileError<T> {\n const { file, args, command, timeout, convert } = call;\n const { code, killed, signal, stdout, stderr } = (error ?? {}) as {\n code?: unknown;\n killed?: unknown;\n signal?: unknown;\n stdout?: unknown;\n stderr?: unknown;\n };\n\n const stdoutBuffer = Buffer.isBuffer(stdout) ? stdout : Buffer.alloc(0);\n const stderrBuffer = Buffer.isBuffer(stderr) ? stderr : Buffer.alloc(0);\n const stdoutValue = convert(stdoutBuffer);\n const reason = failureReason({ code, killed, signal, timeout }, error);\n // Binary standard output stays out of the message.\n const output = shortenOutput(typeof stdoutValue === 'string' ? [stderrBuffer, stdoutBuffer] : [stderrBuffer]);\n\n return new ExecFileError(`${command} failed (${reason})${output ? `\\n${output}` : ''}`, {\n file,\n args,\n command,\n // A command that Node.js terminated, such as on timeout, did not exit on its own, even if it exited with a code.\n exitCode: typeof code === 'number' && killed !== true ? code : undefined,\n signal: typeof signal === 'string' ? signal : undefined,\n stdout: stdoutValue,\n stderr: convert(stderrBuffer),\n cause: error,\n });\n}\n\n/**\n * Describes why a command failed: the timeout that terminated it, its exit\n * code, the signal that terminated it, or the error that prevented it from\n * running.\n *\n * @param failure - The properties of the error of `execFile`.\n * @param failure.code - The exit code, or an error code such as `ENOENT`.\n * @param failure.killed - Whether Node.js terminated the command.\n * @param failure.signal - The signal that terminated the command.\n * @param failure.timeout - The timeout of the command.\n * @param error - The error of `execFile`.\n * @returns The reason for messages.\n */\nfunction failureReason(\n failure: { code: unknown; killed: unknown; signal: unknown; timeout: number | undefined },\n error: unknown,\n): string {\n const { code, killed, signal, timeout } = failure;\n if (killed === true && timeout && typeof code !== 'string') return `timed out after ${timeout} ms`;\n if (typeof code === 'number') return `exit code ${code}`;\n if (typeof code !== 'string' && typeof signal === 'string') return `terminated by ${signal}`;\n return error instanceof Error ? error.message : String(error);\n}\n\n/**\n * Decodes the start of each output, joins the non-empty ones, and shortens\n * them for messages, without decoding the full output.\n *\n * @param outputs - The output buffers.\n * @returns The shortened output, or an empty string if there is none.\n */\nfunction shortenOutput(outputs: readonly Buffer[]): string {\n const output = outputs\n .map(part => part.subarray(0, MAX_OUTPUT_BYTES).toString('utf8').trim())\n .filter(part => part.length > 0)\n .join('\\n');\n return output.length > MAX_OUTPUT_LENGTH ? `${output.slice(0, MAX_OUTPUT_LENGTH)}…` : output;\n}\n"]}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Options for running an executable.
|
|
3
|
+
*/
|
|
4
|
+
export interface ExecFileOptions {
|
|
5
|
+
/**
|
|
6
|
+
* The working directory of the command.
|
|
7
|
+
*
|
|
8
|
+
* @default process.cwd()
|
|
9
|
+
*/
|
|
10
|
+
cwd?: string;
|
|
11
|
+
/**
|
|
12
|
+
* Environment variables for the command, merged over `process.env`.
|
|
13
|
+
* A variable set to `undefined` is removed from the environment.
|
|
14
|
+
*/
|
|
15
|
+
env?: Record<string, string | undefined>;
|
|
16
|
+
/**
|
|
17
|
+
* The largest amount of data in bytes allowed on standard output or
|
|
18
|
+
* standard error. The command is terminated and fails if it is exceeded.
|
|
19
|
+
* For text output, it must not exceed the maximum string length of V8
|
|
20
|
+
* (`buffer.constants.MAX_STRING_LENGTH`).
|
|
21
|
+
*
|
|
22
|
+
* @default 268435456 (256 MiB)
|
|
23
|
+
*/
|
|
24
|
+
maxBuffer?: number;
|
|
25
|
+
/**
|
|
26
|
+
* The time in milliseconds after which the command is terminated with
|
|
27
|
+
* `SIGTERM` and fails. `0` or `undefined` means no limit.
|
|
28
|
+
*/
|
|
29
|
+
timeout?: number;
|
|
30
|
+
/**
|
|
31
|
+
* An `AbortSignal` that terminates the command and makes it fail when
|
|
32
|
+
* aborted. Not to be confused with `ExecFileError.signal`, the name of the
|
|
33
|
+
* signal that terminated a command; both follow `node:child_process`.
|
|
34
|
+
*/
|
|
35
|
+
signal?: AbortSignal;
|
|
36
|
+
/**
|
|
37
|
+
* A callback for debug messages, such as `core.debug` in GitHub Actions.
|
|
38
|
+
* It receives the command and the working directory before the command runs.
|
|
39
|
+
*/
|
|
40
|
+
debug?: (message: string) => void;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* The result of a command that exited with code 0.
|
|
44
|
+
*/
|
|
45
|
+
export interface ExecFileResult<T extends Buffer | string> {
|
|
46
|
+
/**
|
|
47
|
+
* The command line, for messages.
|
|
48
|
+
*/
|
|
49
|
+
command: string;
|
|
50
|
+
/**
|
|
51
|
+
* The standard output, unchanged.
|
|
52
|
+
*/
|
|
53
|
+
stdout: T;
|
|
54
|
+
/**
|
|
55
|
+
* The standard error output, unchanged.
|
|
56
|
+
*/
|
|
57
|
+
stderr: T;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Details of a failed command, with the output as text or buffer.
|
|
61
|
+
*/
|
|
62
|
+
export interface ExecFileErrorDetails<T extends Buffer | string = Buffer | string> {
|
|
63
|
+
/**
|
|
64
|
+
* The executable.
|
|
65
|
+
*/
|
|
66
|
+
file: string;
|
|
67
|
+
/**
|
|
68
|
+
* The arguments.
|
|
69
|
+
*/
|
|
70
|
+
args: readonly string[];
|
|
71
|
+
/**
|
|
72
|
+
* The command line, for messages.
|
|
73
|
+
*/
|
|
74
|
+
command: string;
|
|
75
|
+
/**
|
|
76
|
+
* The exit code, or `undefined` if the command did not exit on its own, for
|
|
77
|
+
* example because it could not be started, was terminated by a signal, or
|
|
78
|
+
* exceeded `maxBuffer` or the timeout.
|
|
79
|
+
*/
|
|
80
|
+
exitCode: number | undefined;
|
|
81
|
+
/**
|
|
82
|
+
* The name of the signal that terminated the command, such as `SIGTERM`, or
|
|
83
|
+
* `undefined`.
|
|
84
|
+
*/
|
|
85
|
+
signal: string | undefined;
|
|
86
|
+
/**
|
|
87
|
+
* The standard output up to the failure, unchanged.
|
|
88
|
+
*/
|
|
89
|
+
stdout: T;
|
|
90
|
+
/**
|
|
91
|
+
* The standard error output up to the failure, unchanged.
|
|
92
|
+
*/
|
|
93
|
+
stderr: T;
|
|
94
|
+
/**
|
|
95
|
+
* The original error.
|
|
96
|
+
*/
|
|
97
|
+
cause: unknown;
|
|
98
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"exec-file.types.js","sourceRoot":"","sources":["../src/exec-file.types.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * Options for running an executable.\n */\nexport interface ExecFileOptions {\n /**\n * The working directory of the command.\n *\n * @default process.cwd()\n */\n cwd?: string;\n\n /**\n * Environment variables for the command, merged over `process.env`.\n * A variable set to `undefined` is removed from the environment.\n */\n env?: Record<string, string | undefined>;\n\n /**\n * The largest amount of data in bytes allowed on standard output or\n * standard error. The command is terminated and fails if it is exceeded.\n * For text output, it must not exceed the maximum string length of V8\n * (`buffer.constants.MAX_STRING_LENGTH`).\n *\n * @default 268435456 (256 MiB)\n */\n maxBuffer?: number;\n\n /**\n * The time in milliseconds after which the command is terminated with\n * `SIGTERM` and fails. `0` or `undefined` means no limit.\n */\n timeout?: number;\n\n /**\n * An `AbortSignal` that terminates the command and makes it fail when\n * aborted. Not to be confused with `ExecFileError.signal`, the name of the\n * signal that terminated a command; both follow `node:child_process`.\n */\n signal?: AbortSignal;\n\n /**\n * A callback for debug messages, such as `core.debug` in GitHub Actions.\n * It receives the command and the working directory before the command runs.\n */\n debug?: (message: string) => void;\n}\n\n/**\n * The result of a command that exited with code 0.\n */\nexport interface ExecFileResult<T extends Buffer | string> {\n /**\n * The command line, for messages.\n */\n command: string;\n\n /**\n * The standard output, unchanged.\n */\n stdout: T;\n\n /**\n * The standard error output, unchanged.\n */\n stderr: T;\n}\n\n/**\n * Details of a failed command, with the output as text or buffer.\n */\nexport interface ExecFileErrorDetails<T extends Buffer | string = Buffer | string> {\n /**\n * The executable.\n */\n file: string;\n\n /**\n * The arguments.\n */\n args: readonly string[];\n\n /**\n * The command line, for messages.\n */\n command: string;\n\n /**\n * The exit code, or `undefined` if the command did not exit on its own, for\n * example because it could not be started, was terminated by a signal, or\n * exceeded `maxBuffer` or the timeout.\n */\n exitCode: number | undefined;\n\n /**\n * The name of the signal that terminated the command, such as `SIGTERM`, or\n * `undefined`.\n */\n signal: string | undefined;\n\n /**\n * The standard output up to the failure, unchanged.\n */\n stdout: T;\n\n /**\n * The standard error output up to the failure, unchanged.\n */\n stderr: T;\n\n /**\n * The original error.\n */\n cause: unknown;\n}\n"]}
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,gBAAgB,CAAC;AAC/B,cAAc,sBAAsB,CAAC","sourcesContent":["export * from './exec-file.js';\nexport * from './exec-file-error.js';\nexport type * from './exec-file.types.js';\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,68 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@simbo/exec-file",
|
|
3
|
-
"
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"description": "Run executables without a shell and get their output as text or buffer, with errors that hold exit code, signal, and output.",
|
|
4
|
+
"version": "1.0.0",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"exec",
|
|
7
|
+
"execfile",
|
|
8
|
+
"child-process",
|
|
9
|
+
"command",
|
|
10
|
+
"process",
|
|
11
|
+
"async",
|
|
12
|
+
"no-shell",
|
|
13
|
+
"cli",
|
|
14
|
+
"utility",
|
|
15
|
+
"typescript"
|
|
16
|
+
],
|
|
17
|
+
"author": "Simon Lepel <simbo@simbo.de> (https://simbo.de/)",
|
|
18
|
+
"license": "MIT",
|
|
19
|
+
"homepage": "https://github.com/simbo/packages/tree/main/packages/exec-file",
|
|
20
|
+
"repository": {
|
|
21
|
+
"type": "git",
|
|
22
|
+
"url": "git+https://github.com/simbo/packages.git",
|
|
23
|
+
"directory": "packages/exec-file"
|
|
24
|
+
},
|
|
25
|
+
"bugs": "https://github.com/simbo/packages/issues",
|
|
26
|
+
"engines": {
|
|
27
|
+
"node": "^24.15.0 || >=26.0.0"
|
|
28
|
+
},
|
|
29
|
+
"type": "module",
|
|
30
|
+
"exports": {
|
|
31
|
+
".": "./dist/index.js"
|
|
32
|
+
},
|
|
33
|
+
"files": [
|
|
34
|
+
"CHANGELOG.md",
|
|
35
|
+
"dist",
|
|
36
|
+
"LICENSE.md",
|
|
37
|
+
"README.md"
|
|
38
|
+
],
|
|
39
|
+
"devDependencies": {
|
|
40
|
+
"@arethetypeswrong/cli": "^0.18.5",
|
|
41
|
+
"@simbo/eslint-config": "7.0.0",
|
|
42
|
+
"@simbo/tsconfig": "5.0.0",
|
|
43
|
+
"@types/node": "^24.19.4",
|
|
44
|
+
"@vitest/coverage-v8": "^5.1.2",
|
|
45
|
+
"@vitest/ui": "^5.1.2",
|
|
46
|
+
"eslint": "^10.16.0",
|
|
47
|
+
"jiti": "^2.7.0",
|
|
48
|
+
"publint": "^0.3.25",
|
|
49
|
+
"typescript": "^6.0.3",
|
|
50
|
+
"vitest": "^5.1.2"
|
|
51
|
+
},
|
|
52
|
+
"scripts": {
|
|
53
|
+
"build": "tsc --project tsconfig.build.json",
|
|
54
|
+
"check": "pnpm run check:eslint && pnpm run check:types",
|
|
55
|
+
"check:eslint": "eslint --config ./eslint.config.ts --max-warnings 0",
|
|
56
|
+
"check:pack": "pnpm pack --out node_modules/.cache/check-pack/package.tgz && publint node_modules/.cache/check-pack/package.tgz --strict && attw node_modules/.cache/check-pack/package.tgz --profile esm-only",
|
|
57
|
+
"check:types": "tsc --noEmit",
|
|
58
|
+
"clean": "pnpm run clean:dist && pnpm run clean:coverage && pnpm run clean:turbo && pnpm run clean:node_modules",
|
|
59
|
+
"clean:dist": "rm -rf dist",
|
|
60
|
+
"clean:node_modules": "rm -rf node_modules",
|
|
61
|
+
"clean:turbo": "rm -rf .turbo",
|
|
62
|
+
"clean:coverage": "rm -rf coverage",
|
|
63
|
+
"fix:eslint": "pnpm run check:eslint --fix",
|
|
64
|
+
"test": "vitest run --coverage",
|
|
65
|
+
"test:ui": "pnpm run test:watch --ui",
|
|
66
|
+
"test:watch": "vitest dev --coverage"
|
|
67
|
+
}
|
|
6
68
|
}
|