Bump @ava/typescript from 3.0.1 to 4.0.0 (#1576)

* Bump @ava/typescript from 3.0.1 to 4.0.0

Bumps [@ava/typescript](https://github.com/avajs/typescript) from 3.0.1 to 4.0.0.
- [Release notes](https://github.com/avajs/typescript/releases)
- [Commits](https://github.com/avajs/typescript/compare/v3.0.1...v4.0.0)

---
updated-dependencies:
- dependency-name: "@ava/typescript"
  dependency-type: direct:development
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>

* Update checked-in dependencies

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: github-actions[bot] <github-actions@github.com>
This commit is contained in:
dependabot[bot]
2023-03-13 14:10:40 -07:00
committed by GitHub
parent ec298233c1
commit 19f00dc212
68 changed files with 2374 additions and 1754 deletions

1436
node_modules/execa/index.d.ts generated vendored

File diff suppressed because it is too large Load Diff

119
node_modules/execa/index.js generated vendored
View File

@@ -1,16 +1,19 @@
'use strict';
const path = require('path');
const childProcess = require('child_process');
const crossSpawn = require('cross-spawn');
const stripFinalNewline = require('strip-final-newline');
const npmRunPath = require('npm-run-path');
const onetime = require('onetime');
const makeError = require('./lib/error');
const normalizeStdio = require('./lib/stdio');
const {spawnedKill, spawnedCancel, setupTimeout, validateTimeout, setExitHandler} = require('./lib/kill');
const {handleInput, getSpawnedResult, makeAllStream, validateInputSync} = require('./lib/stream');
const {mergePromise, getSpawnedPromise} = require('./lib/promise');
const {joinCommand, parseCommand, getEscapedCommand} = require('./lib/command');
import {Buffer} from 'node:buffer';
import path from 'node:path';
import childProcess from 'node:child_process';
import process from 'node:process';
import crossSpawn from 'cross-spawn';
import stripFinalNewline from 'strip-final-newline';
import {npmRunPathEnv} from 'npm-run-path';
import onetime from 'onetime';
import {makeError} from './lib/error.js';
import {normalizeStdio, normalizeStdioNode} from './lib/stdio.js';
import {spawnedKill, spawnedCancel, setupTimeout, validateTimeout, setExitHandler} from './lib/kill.js';
import {addPipeMethods} from './lib/pipe.js';
import {handleInput, getSpawnedResult, makeAllStream, handleInputSync} from './lib/stream.js';
import {mergePromise, getSpawnedPromise} from './lib/promise.js';
import {joinCommand, parseCommand, parseTemplates, getEscapedCommand} from './lib/command.js';
import {logCommand, verboseDefault} from './lib/verbose.js';
const DEFAULT_MAX_BUFFER = 1000 * 1000 * 100;
@@ -18,7 +21,7 @@ const getEnv = ({env: envOption, extendEnv, preferLocal, localDir, execPath}) =>
const env = extendEnv ? {...process.env, ...envOption} : envOption;
if (preferLocal) {
return npmRunPath.env({env, cwd: localDir, execPath});
return npmRunPathEnv({env, cwd: localDir, execPath});
}
return env;
@@ -43,7 +46,8 @@ const handleArguments = (file, args, options = {}) => {
cleanup: true,
all: false,
windowsHide: true,
...options
verbose: verboseDefault,
...options,
};
options.env = getEnv(options);
@@ -60,7 +64,7 @@ const handleArguments = (file, args, options = {}) => {
const handleOutput = (options, value, error) => {
if (typeof value !== 'string' && !Buffer.isBuffer(value)) {
// When `execa.sync()` errors, we normalize it to '' to mimic `execa()`
// When `execaSync()` errors, we normalize it to '' to mimic `execa()`
return error === undefined ? undefined : '';
}
@@ -71,10 +75,11 @@ const handleOutput = (options, value, error) => {
return value;
};
const execa = (file, args, options) => {
export function execa(file, args, options) {
const parsed = handleArguments(file, args, options);
const command = joinCommand(file, args);
const escapedCommand = getEscapedCommand(file, args);
logCommand(escapedCommand, parsed.options);
validateTimeout(parsed.options);
@@ -94,9 +99,10 @@ const execa = (file, args, options) => {
parsed,
timedOut: false,
isCanceled: false,
killed: false
killed: false,
}));
return mergePromise(dummySpawned, errorPromise);
mergePromise(dummySpawned, errorPromise);
return dummySpawned;
}
const spawnedPromise = getSpawnedPromise(spawned);
@@ -126,8 +132,8 @@ const execa = (file, args, options) => {
escapedCommand,
parsed,
timedOut,
isCanceled: context.isCanceled,
killed: spawned.killed
isCanceled: context.isCanceled || (parsed.options.signal ? parsed.options.signal.aborted : false),
killed: spawned.killed,
});
if (!parsed.options.reject) {
@@ -147,31 +153,32 @@ const execa = (file, args, options) => {
failed: false,
timedOut: false,
isCanceled: false,
killed: false
killed: false,
};
};
const handlePromiseOnce = onetime(handlePromise);
handleInput(spawned, parsed.options.input);
handleInput(spawned, parsed.options);
spawned.all = makeAllStream(spawned, parsed.options);
return mergePromise(spawned, handlePromiseOnce);
};
addPipeMethods(spawned);
mergePromise(spawned, handlePromiseOnce);
return spawned;
}
module.exports = execa;
module.exports.sync = (file, args, options) => {
export function execaSync(file, args, options) {
const parsed = handleArguments(file, args, options);
const command = joinCommand(file, args);
const escapedCommand = getEscapedCommand(file, args);
logCommand(escapedCommand, parsed.options);
validateInputSync(parsed.options);
const input = handleInputSync(parsed.options);
let result;
try {
result = childProcess.spawnSync(parsed.file, parsed.args, parsed.options);
result = childProcess.spawnSync(parsed.file, parsed.args, {...parsed.options, input});
} catch (error) {
throw makeError({
error,
@@ -183,7 +190,7 @@ module.exports.sync = (file, args, options) => {
parsed,
timedOut: false,
isCanceled: false,
killed: false
killed: false,
});
}
@@ -202,7 +209,7 @@ module.exports.sync = (file, args, options) => {
parsed,
timedOut: result.error && result.error.code === 'ETIMEDOUT',
isCanceled: false,
killed: result.signal !== null
killed: result.signal !== null,
});
if (!parsed.options.reject) {
@@ -221,32 +228,52 @@ module.exports.sync = (file, args, options) => {
failed: false,
timedOut: false,
isCanceled: false,
killed: false
killed: false,
};
};
}
module.exports.command = (command, options) => {
function create$(options) {
function $(templatesOrOptions, ...expressions) {
if (Array.isArray(templatesOrOptions)) {
const [file, ...args] = parseTemplates(templatesOrOptions, expressions);
return execa(file, args, options);
}
return create$({...options, ...templatesOrOptions});
}
$.sync = (templates, ...expressions) => {
const [file, ...args] = parseTemplates(templates, expressions);
return execaSync(file, args, options);
};
return $;
}
export const $ = create$({preferLocal: true});
export function execaCommand(command, options) {
const [file, ...args] = parseCommand(command);
return execa(file, args, options);
};
}
module.exports.commandSync = (command, options) => {
export function execaCommandSync(command, options) {
const [file, ...args] = parseCommand(command);
return execa.sync(file, args, options);
};
return execaSync(file, args, options);
}
module.exports.node = (scriptPath, args, options = {}) => {
export function execaNode(scriptPath, args, options = {}) {
if (args && !Array.isArray(args) && typeof args === 'object') {
options = args;
args = [];
}
const stdio = normalizeStdio.node(options);
const stdio = normalizeStdioNode(options);
const defaultExecArgv = process.execArgv.filter(arg => !arg.startsWith('--inspect'));
const {
nodePath = process.execPath,
nodeOptions = defaultExecArgv
nodeOptions = defaultExecArgv,
} = options;
return execa(
@@ -254,7 +281,7 @@ module.exports.node = (scriptPath, args, options = {}) => {
[
...nodeOptions,
scriptPath,
...(Array.isArray(args) ? args : [])
...(Array.isArray(args) ? args : []),
],
{
...options,
@@ -262,7 +289,7 @@ module.exports.node = (scriptPath, args, options = {}) => {
stdout: undefined,
stderr: undefined,
stdio,
shell: false
}
shell: false,
},
);
};
}

70
node_modules/execa/lib/command.js generated vendored
View File

@@ -1,4 +1,6 @@
'use strict';
import {Buffer} from 'node:buffer';
import {ChildProcess} from 'node:child_process';
const normalizeArgs = (file, args = []) => {
if (!Array.isArray(args)) {
return [file];
@@ -18,18 +20,14 @@ const escapeArg = arg => {
return `"${arg.replace(DOUBLE_QUOTES_REGEXP, '\\"')}"`;
};
const joinCommand = (file, args) => {
return normalizeArgs(file, args).join(' ');
};
export const joinCommand = (file, args) => normalizeArgs(file, args).join(' ');
const getEscapedCommand = (file, args) => {
return normalizeArgs(file, args).map(arg => escapeArg(arg)).join(' ');
};
export const getEscapedCommand = (file, args) => normalizeArgs(file, args).map(arg => escapeArg(arg)).join(' ');
const SPACES_REGEXP = / +/g;
// Handle `execa.command()`
const parseCommand = command => {
// Handle `execaCommand()`
export const parseCommand = command => {
const tokens = [];
for (const token of command.trim().split(SPACES_REGEXP)) {
// Allow spaces to be escaped by a backslash if not meant as a delimiter
@@ -45,8 +43,54 @@ const parseCommand = command => {
return tokens;
};
module.exports = {
joinCommand,
getEscapedCommand,
parseCommand
const parseExpression = expression => {
const typeOfExpression = typeof expression;
if (typeOfExpression === 'string') {
return expression;
}
if (typeOfExpression === 'number') {
return String(expression);
}
if (
typeOfExpression === 'object'
&& expression !== null
&& !(expression instanceof ChildProcess)
&& 'stdout' in expression
) {
const typeOfStdout = typeof expression.stdout;
if (typeOfStdout === 'string') {
return expression.stdout;
}
if (Buffer.isBuffer(expression.stdout)) {
return expression.stdout.toString();
}
throw new TypeError(`Unexpected "${typeOfStdout}" stdout in template expression`);
}
throw new TypeError(`Unexpected "${typeOfExpression}" in template expression`);
};
const parseTemplate = (template, index, templates, expressions) => {
const templateString = template ?? templates.raw[index];
const templateTokens = templateString.split(SPACES_REGEXP).filter(Boolean);
if (index === expressions.length) {
return templateTokens;
}
const expression = expressions[index];
return Array.isArray(expression)
? [...templateTokens, ...expression.map(expression => parseExpression(expression))]
: [...templateTokens, parseExpression(expression)];
};
export const parseTemplates = (templates, expressions) => templates.flatMap(
(template, index) => parseTemplate(template, index, templates, expressions),
);

9
node_modules/execa/lib/error.js generated vendored
View File

@@ -1,5 +1,4 @@
'use strict';
const {signalsByName} = require('human-signals');
import {signalsByName} from 'human-signals';
const getErrorPrefix = ({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}) => {
if (timedOut) {
@@ -25,7 +24,7 @@ const getErrorPrefix = ({timedOut, timeout, errorCode, signal, signalDescription
return 'failed';
};
const makeError = ({
export const makeError = ({
stdout,
stderr,
all,
@@ -37,7 +36,7 @@ const makeError = ({
timedOut,
isCanceled,
killed,
parsed: {options: {timeout}}
parsed: {options: {timeout}},
}) => {
// `signal` and `exitCode` emitted on `spawned.on('exit')` event can be `null`.
// We normalize them to `undefined`
@@ -84,5 +83,3 @@ const makeError = ({
return error;
};
module.exports = makeError;

33
node_modules/execa/lib/kill.js generated vendored
View File

@@ -1,11 +1,10 @@
'use strict';
const os = require('os');
const onExit = require('signal-exit');
import os from 'node:os';
import onExit from 'signal-exit';
const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5;
// Monkey-patches `childProcess.kill()` to add `forceKillAfterTimeout` behavior
const spawnedKill = (kill, signal = 'SIGTERM', options = {}) => {
export const spawnedKill = (kill, signal = 'SIGTERM', options = {}) => {
const killResult = kill(signal);
setKillTimeout(kill, signal, options, killResult);
return killResult;
@@ -30,14 +29,10 @@ const setKillTimeout = (kill, signal, options, killResult) => {
}
};
const shouldForceKill = (signal, {forceKillAfterTimeout}, killResult) => {
return isSigterm(signal) && forceKillAfterTimeout !== false && killResult;
};
const shouldForceKill = (signal, {forceKillAfterTimeout}, killResult) => isSigterm(signal) && forceKillAfterTimeout !== false && killResult;
const isSigterm = signal => {
return signal === os.constants.signals.SIGTERM ||
(typeof signal === 'string' && signal.toUpperCase() === 'SIGTERM');
};
const isSigterm = signal => signal === os.constants.signals.SIGTERM
|| (typeof signal === 'string' && signal.toUpperCase() === 'SIGTERM');
const getForceKillAfterTimeout = ({forceKillAfterTimeout = true}) => {
if (forceKillAfterTimeout === true) {
@@ -52,7 +47,7 @@ const getForceKillAfterTimeout = ({forceKillAfterTimeout = true}) => {
};
// `childProcess.cancel()`
const spawnedCancel = (spawned, context) => {
export const spawnedCancel = (spawned, context) => {
const killResult = spawned.kill();
if (killResult) {
@@ -66,7 +61,7 @@ const timeoutKill = (spawned, signal, reject) => {
};
// `timeout` option handling
const setupTimeout = (spawned, {timeout, killSignal = 'SIGTERM'}, spawnedPromise) => {
export const setupTimeout = (spawned, {timeout, killSignal = 'SIGTERM'}, spawnedPromise) => {
if (timeout === 0 || timeout === undefined) {
return spawnedPromise;
}
@@ -85,14 +80,14 @@ const setupTimeout = (spawned, {timeout, killSignal = 'SIGTERM'}, spawnedPromise
return Promise.race([timeoutPromise, safeSpawnedPromise]);
};
const validateTimeout = ({timeout}) => {
export const validateTimeout = ({timeout}) => {
if (timeout !== undefined && (!Number.isFinite(timeout) || timeout < 0)) {
throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`);
}
};
// `cleanup` option handling
const setExitHandler = async (spawned, {cleanup, detached}, timedPromise) => {
export const setExitHandler = async (spawned, {cleanup, detached}, timedPromise) => {
if (!cleanup || detached) {
return timedPromise;
}
@@ -105,11 +100,3 @@ const setExitHandler = async (spawned, {cleanup, detached}, timedPromise) => {
removeExitHandler();
});
};
module.exports = {
spawnedKill,
spawnedCancel,
setupTimeout,
validateTimeout,
setExitHandler
};

42
node_modules/execa/lib/pipe.js generated vendored Normal file
View File

@@ -0,0 +1,42 @@
import {createWriteStream} from 'node:fs';
import {ChildProcess} from 'node:child_process';
import {isWritableStream} from 'is-stream';
const isExecaChildProcess = target => target instanceof ChildProcess && typeof target.then === 'function';
const pipeToTarget = (spawned, streamName, target) => {
if (typeof target === 'string') {
spawned[streamName].pipe(createWriteStream(target));
return spawned;
}
if (isWritableStream(target)) {
spawned[streamName].pipe(target);
return spawned;
}
if (!isExecaChildProcess(target)) {
throw new TypeError('The second argument must be a string, a stream or an Execa child process.');
}
if (!isWritableStream(target.stdin)) {
throw new TypeError('The target child process\'s stdin must be available.');
}
spawned[streamName].pipe(target.stdin);
return target;
};
export const addPipeMethods = spawned => {
if (spawned.stdout !== null) {
spawned.pipeStdout = pipeToTarget.bind(undefined, spawned, 'stdout');
}
if (spawned.stderr !== null) {
spawned.pipeStderr = pipeToTarget.bind(undefined, spawned, 'stderr');
}
if (spawned.all !== undefined) {
spawned.pipeAll = pipeToTarget.bind(undefined, spawned, 'all');
}
};

48
node_modules/execa/lib/promise.js generated vendored
View File

@@ -1,46 +1,36 @@
'use strict';
// eslint-disable-next-line unicorn/prefer-top-level-await
const nativePromisePrototype = (async () => {})().constructor.prototype;
const descriptors = ['then', 'catch', 'finally'].map(property => [
property,
Reflect.getOwnPropertyDescriptor(nativePromisePrototype, property)
Reflect.getOwnPropertyDescriptor(nativePromisePrototype, property),
]);
// The return value is a mixin of `childProcess` and `Promise`
const mergePromise = (spawned, promise) => {
export const mergePromise = (spawned, promise) => {
for (const [property, descriptor] of descriptors) {
// Starting the main `promise` is deferred to avoid consuming streams
const value = typeof promise === 'function' ?
(...args) => Reflect.apply(descriptor.value, promise(), args) :
descriptor.value.bind(promise);
const value = typeof promise === 'function'
? (...args) => Reflect.apply(descriptor.value, promise(), args)
: descriptor.value.bind(promise);
Reflect.defineProperty(spawned, property, {...descriptor, value});
}
return spawned;
};
// Use promises instead of `child_process` events
const getSpawnedPromise = spawned => {
return new Promise((resolve, reject) => {
spawned.on('exit', (exitCode, signal) => {
resolve({exitCode, signal});
});
export const getSpawnedPromise = spawned => new Promise((resolve, reject) => {
spawned.on('exit', (exitCode, signal) => {
resolve({exitCode, signal});
});
spawned.on('error', error => {
spawned.on('error', error => {
reject(error);
});
if (spawned.stdin) {
spawned.stdin.on('error', error => {
reject(error);
});
if (spawned.stdin) {
spawned.stdin.on('error', error => {
reject(error);
});
}
});
};
module.exports = {
mergePromise,
getSpawnedPromise
};
}
});

7
node_modules/execa/lib/stdio.js generated vendored
View File

@@ -1,9 +1,8 @@
'use strict';
const aliases = ['stdin', 'stdout', 'stderr'];
const hasAlias = options => aliases.some(alias => options[alias] !== undefined);
const normalizeStdio = options => {
export const normalizeStdio = options => {
if (!options) {
return;
}
@@ -30,10 +29,8 @@ const normalizeStdio = options => {
return Array.from({length}, (value, index) => stdio[index]);
};
module.exports = normalizeStdio;
// `ipc` is pushed unless it is already present
module.exports.node = options => {
export const normalizeStdioNode = options => {
const stdio = normalizeStdio(options);
if (stdio === 'ipc') {

76
node_modules/execa/lib/stream.js generated vendored
View File

@@ -1,13 +1,48 @@
'use strict';
const isStream = require('is-stream');
const getStream = require('get-stream');
const mergeStream = require('merge-stream');
import {createReadStream, readFileSync} from 'node:fs';
import {isStream} from 'is-stream';
import getStream from 'get-stream';
import mergeStream from 'merge-stream';
// `input` option
const handleInput = (spawned, input) => {
// Checking for stdin is workaround for https://github.com/nodejs/node/issues/26852
// @todo remove `|| spawned.stdin === undefined` once we drop support for Node.js <=12.2.0
if (input === undefined || spawned.stdin === undefined) {
const validateInputOptions = input => {
if (input !== undefined) {
throw new TypeError('The `input` and `inputFile` options cannot be both set.');
}
};
const getInputSync = ({input, inputFile}) => {
if (typeof inputFile !== 'string') {
return input;
}
validateInputOptions(input);
return readFileSync(inputFile);
};
// `input` and `inputFile` option in sync mode
export const handleInputSync = options => {
const input = getInputSync(options);
if (isStream(input)) {
throw new TypeError('The `input` option cannot be a stream in sync mode');
}
return input;
};
const getInput = ({input, inputFile}) => {
if (typeof inputFile !== 'string') {
return input;
}
validateInputOptions(input);
return createReadStream(inputFile);
};
// `input` and `inputFile` option in async mode
export const handleInput = (spawned, options) => {
const input = getInput(options);
if (input === undefined) {
return;
}
@@ -19,7 +54,7 @@ const handleInput = (spawned, input) => {
};
// `all` interleaves `stdout` and `stderr`
const makeAllStream = (spawned, {all}) => {
export const makeAllStream = (spawned, {all}) => {
if (!all || (!spawned.stdout && !spawned.stderr)) {
return;
}
@@ -39,7 +74,8 @@ const makeAllStream = (spawned, {all}) => {
// On failure, `result.stdout|stderr|all` should contain the currently buffered stream
const getBufferedData = async (stream, streamPromise) => {
if (!stream) {
// When `buffer` is `false`, `streamPromise` is `undefined` and there is no buffered data to retrieve
if (!stream || streamPromise === undefined) {
return;
}
@@ -65,7 +101,7 @@ const getStreamPromise = (stream, {encoding, buffer, maxBuffer}) => {
};
// Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all)
const getSpawnedResult = async ({stdout, stderr, all}, {encoding, buffer, maxBuffer}, processDone) => {
export const getSpawnedResult = async ({stdout, stderr, all}, {encoding, buffer, maxBuffer}, processDone) => {
const stdoutPromise = getStreamPromise(stdout, {encoding, buffer, maxBuffer});
const stderrPromise = getStreamPromise(stderr, {encoding, buffer, maxBuffer});
const allPromise = getStreamPromise(all, {encoding, buffer, maxBuffer: maxBuffer * 2});
@@ -77,21 +113,7 @@ const getSpawnedResult = async ({stdout, stderr, all}, {encoding, buffer, maxBuf
{error, signal: error.signal, timedOut: error.timedOut},
getBufferedData(stdout, stdoutPromise),
getBufferedData(stderr, stderrPromise),
getBufferedData(all, allPromise)
getBufferedData(all, allPromise),
]);
}
};
const validateInputSync = ({input}) => {
if (isStream(input)) {
throw new TypeError('The `input` option cannot be a stream in sync mode');
}
};
module.exports = {
handleInput,
makeAllStream,
getSpawnedResult,
validateInputSync
};

19
node_modules/execa/lib/verbose.js generated vendored Normal file
View File

@@ -0,0 +1,19 @@
import {debuglog} from 'node:util';
import process from 'node:process';
export const verboseDefault = debuglog('execa').enabled;
const padField = (field, padding) => String(field).padStart(padding, '0');
const getTimestamp = () => {
const date = new Date();
return `${padField(date.getHours(), 2)}:${padField(date.getMinutes(), 2)}:${padField(date.getSeconds(), 2)}.${padField(date.getMilliseconds(), 3)}`;
};
export const logCommand = (escapedCommand, {verbose}) => {
if (!verbose) {
return;
}
process.stderr.write(`[${getTimestamp()}] ${escapedCommand}\n`);
};

View File

@@ -1,52 +0,0 @@
'use strict';
const {PassThrough: PassThroughStream} = require('stream');
module.exports = options => {
options = {...options};
const {array} = options;
let {encoding} = options;
const isBuffer = encoding === 'buffer';
let objectMode = false;
if (array) {
objectMode = !(encoding || isBuffer);
} else {
encoding = encoding || 'utf8';
}
if (isBuffer) {
encoding = null;
}
const stream = new PassThroughStream({objectMode});
if (encoding) {
stream.setEncoding(encoding);
}
let length = 0;
const chunks = [];
stream.on('data', chunk => {
chunks.push(chunk);
if (objectMode) {
length = chunks.length;
} else {
length += chunk.length;
}
});
stream.getBufferedValue = () => {
if (array) {
return chunks;
}
return isBuffer ? Buffer.concat(chunks, length) : chunks.join('');
};
stream.getBufferedLength = () => length;
return stream;
};

View File

@@ -1,105 +0,0 @@
/// <reference types="node"/>
import {Stream} from 'stream';
declare class MaxBufferErrorClass extends Error {
readonly name: 'MaxBufferError';
constructor();
}
declare namespace getStream {
interface Options {
/**
Maximum length of the returned string. If it exceeds this value before the stream ends, the promise will be rejected with a `MaxBufferError` error.
@default Infinity
*/
readonly maxBuffer?: number;
}
interface OptionsWithEncoding<EncodingType = BufferEncoding> extends Options {
/**
[Encoding](https://nodejs.org/api/buffer.html#buffer_buffer) of the incoming stream.
@default 'utf8'
*/
readonly encoding?: EncodingType;
}
type MaxBufferError = MaxBufferErrorClass;
}
declare const getStream: {
/**
Get the `stream` as a string.
@returns A promise that resolves when the end event fires on the stream, indicating that there is no more data to be read. The stream is switched to flowing mode.
@example
```
import * as fs from 'fs';
import getStream = require('get-stream');
(async () => {
const stream = fs.createReadStream('unicorn.txt');
console.log(await getStream(stream));
// ,,))))))));,
// __)))))))))))))),
// \|/ -\(((((''''((((((((.
// -*-==//////(('' . `)))))),
// /|\ ))| o ;-. '((((( ,(,
// ( `| / ) ;))))' ,_))^;(~
// | | | ,))((((_ _____------~~~-. %,;(;(>';'~
// o_); ; )))(((` ~---~ `:: \ %%~~)(v;(`('~
// ; ''''```` `: `:::|\,__,%% );`'; ~
// | _ ) / `:|`----' `-'
// ______/\/~ | / /
// /~;;.____/;;' / ___--,-( `;;;/
// / // _;______;'------~~~~~ /;;/\ /
// // | | / ; \;;,\
// (<_ | ; /',/-----' _>
// \_| ||_ //~;~~~~~~~~~
// `\_| (,~~
// \~\
// ~~
})();
```
*/
(stream: Stream, options?: getStream.OptionsWithEncoding): Promise<string>;
/**
Get the `stream` as a buffer.
It honors the `maxBuffer` option as above, but it refers to byte length rather than string length.
*/
buffer(
stream: Stream,
options?: getStream.Options
): Promise<Buffer>;
/**
Get the `stream` as an array of values.
It honors both the `maxBuffer` and `encoding` options. The behavior changes slightly based on the encoding chosen:
- When `encoding` is unset, it assumes an [object mode stream](https://nodesource.com/blog/understanding-object-streams/) and collects values emitted from `stream` unmodified. In this case `maxBuffer` refers to the number of items in the array (not the sum of their sizes).
- When `encoding` is set to `buffer`, it collects an array of buffers. `maxBuffer` refers to the summed byte lengths of every buffer in the array.
- When `encoding` is set to anything else, it collects an array of strings. `maxBuffer` refers to the summed character lengths of every string in the array.
*/
array<StreamObjectModeType>(
stream: Stream,
options?: getStream.Options
): Promise<StreamObjectModeType[]>;
array(
stream: Stream,
options: getStream.OptionsWithEncoding<'buffer'>
): Promise<Buffer[]>;
array(
stream: Stream,
options: getStream.OptionsWithEncoding<BufferEncoding>
): Promise<string[]>;
MaxBufferError: typeof MaxBufferErrorClass;
};
export = getStream;

View File

@@ -1,61 +0,0 @@
'use strict';
const {constants: BufferConstants} = require('buffer');
const stream = require('stream');
const {promisify} = require('util');
const bufferStream = require('./buffer-stream');
const streamPipelinePromisified = promisify(stream.pipeline);
class MaxBufferError extends Error {
constructor() {
super('maxBuffer exceeded');
this.name = 'MaxBufferError';
}
}
async function getStream(inputStream, options) {
if (!inputStream) {
throw new Error('Expected a stream');
}
options = {
maxBuffer: Infinity,
...options
};
const {maxBuffer} = options;
const stream = bufferStream(options);
await new Promise((resolve, reject) => {
const rejectPromise = error => {
// Don't retrieve an oversized buffer.
if (error && stream.getBufferedLength() <= BufferConstants.MAX_LENGTH) {
error.bufferedData = stream.getBufferedValue();
}
reject(error);
};
(async () => {
try {
await streamPipelinePromisified(inputStream, stream);
resolve();
} catch (error) {
rejectPromise(error);
}
})();
stream.on('data', () => {
if (stream.getBufferedLength() > maxBuffer) {
rejectPromise(new MaxBufferError());
}
});
});
return stream.getBufferedValue();
}
module.exports = getStream;
module.exports.buffer = (stream, options) => getStream(stream, {...options, encoding: 'buffer'});
module.exports.array = (stream, options) => getStream(stream, {...options, array: true});
module.exports.MaxBufferError = MaxBufferError;

View File

@@ -1,9 +0,0 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
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.

View File

@@ -1,47 +0,0 @@
{
"name": "get-stream",
"version": "6.0.1",
"description": "Get a stream as a string, buffer, or array",
"license": "MIT",
"repository": "sindresorhus/get-stream",
"funding": "https://github.com/sponsors/sindresorhus",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "https://sindresorhus.com"
},
"engines": {
"node": ">=10"
},
"scripts": {
"test": "xo && ava && tsd"
},
"files": [
"index.js",
"index.d.ts",
"buffer-stream.js"
],
"keywords": [
"get",
"stream",
"promise",
"concat",
"string",
"text",
"buffer",
"read",
"data",
"consume",
"readable",
"readablestream",
"array",
"object"
],
"devDependencies": {
"@types/node": "^14.0.27",
"ava": "^2.4.0",
"into-stream": "^5.0.0",
"tsd": "^0.13.1",
"xo": "^0.24.0"
}
}

View File

@@ -1,124 +0,0 @@
# get-stream
> Get a stream as a string, buffer, or array
## Install
```
$ npm install get-stream
```
## Usage
```js
const fs = require('fs');
const getStream = require('get-stream');
(async () => {
const stream = fs.createReadStream('unicorn.txt');
console.log(await getStream(stream));
/*
,,))))))));,
__)))))))))))))),
\|/ -\(((((''''((((((((.
-*-==//////(('' . `)))))),
/|\ ))| o ;-. '((((( ,(,
( `| / ) ;))))' ,_))^;(~
| | | ,))((((_ _____------~~~-. %,;(;(>';'~
o_); ; )))(((` ~---~ `:: \ %%~~)(v;(`('~
; ''''```` `: `:::|\,__,%% );`'; ~
| _ ) / `:|`----' `-'
______/\/~ | / /
/~;;.____/;;' / ___--,-( `;;;/
/ // _;______;'------~~~~~ /;;/\ /
// | | / ; \;;,\
(<_ | ; /',/-----' _>
\_| ||_ //~;~~~~~~~~~
`\_| (,~~
\~\
~~
*/
})();
```
## API
The methods returns a promise that resolves when the `end` event fires on the stream, indicating that there is no more data to be read. The stream is switched to flowing mode.
### getStream(stream, options?)
Get the `stream` as a string.
#### options
Type: `object`
##### encoding
Type: `string`\
Default: `'utf8'`
[Encoding](https://nodejs.org/api/buffer.html#buffer_buffer) of the incoming stream.
##### maxBuffer
Type: `number`\
Default: `Infinity`
Maximum length of the returned string. If it exceeds this value before the stream ends, the promise will be rejected with a `getStream.MaxBufferError` error.
### getStream.buffer(stream, options?)
Get the `stream` as a buffer.
It honors the `maxBuffer` option as above, but it refers to byte length rather than string length.
### getStream.array(stream, options?)
Get the `stream` as an array of values.
It honors both the `maxBuffer` and `encoding` options. The behavior changes slightly based on the encoding chosen:
- When `encoding` is unset, it assumes an [object mode stream](https://nodesource.com/blog/understanding-object-streams/) and collects values emitted from `stream` unmodified. In this case `maxBuffer` refers to the number of items in the array (not the sum of their sizes).
- When `encoding` is set to `buffer`, it collects an array of buffers. `maxBuffer` refers to the summed byte lengths of every buffer in the array.
- When `encoding` is set to anything else, it collects an array of strings. `maxBuffer` refers to the summed character lengths of every string in the array.
## Errors
If the input stream emits an `error` event, the promise will be rejected with the error. The buffered data will be attached to the `bufferedData` property of the error.
```js
(async () => {
try {
await getStream(streamThatErrorsAtTheEnd('unicorn'));
} catch (error) {
console.log(error.bufferedData);
//=> 'unicorn'
}
})()
```
## FAQ
### How is this different from [`concat-stream`](https://github.com/maxogden/concat-stream)?
This module accepts a stream instead of being one and returns a promise instead of using a callback. The API is simpler and it only supports returning a string, buffer, or array. It doesn't have a fragile type inference. You explicitly choose what you want. And it doesn't depend on the huge `readable-stream` package.
## Related
- [get-stdin](https://github.com/sindresorhus/get-stdin) - Get stdin as a string or buffer
---
<div align="center">
<b>
<a href="https://tidelift.com/subscription/pkg/npm-get-stream?utm_source=npm-get-stream&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a>
</b>
<br>
<sub>
Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
</sub>
</div>

50
node_modules/execa/package.json generated vendored
View File

@@ -1,6 +1,6 @@
{
"name": "execa",
"version": "5.1.1",
"version": "7.1.0",
"description": "Process execution for humans",
"license": "MIT",
"repository": "sindresorhus/execa",
@@ -10,11 +10,13 @@
"email": "sindresorhus@gmail.com",
"url": "https://sindresorhus.com"
},
"type": "module",
"exports": "./index.js",
"engines": {
"node": ">=10"
"node": "^14.18.0 || ^16.14.0 || >=18.0.0"
},
"scripts": {
"test": "xo && nyc ava && tsd"
"test": "xo && c8 ava && tsd"
},
"files": [
"index.js",
@@ -40,27 +42,28 @@
],
"dependencies": {
"cross-spawn": "^7.0.3",
"get-stream": "^6.0.0",
"human-signals": "^2.1.0",
"is-stream": "^2.0.0",
"get-stream": "^6.0.1",
"human-signals": "^4.3.0",
"is-stream": "^3.0.0",
"merge-stream": "^2.0.0",
"npm-run-path": "^4.0.1",
"onetime": "^5.1.2",
"signal-exit": "^3.0.3",
"strip-final-newline": "^2.0.0"
"npm-run-path": "^5.1.0",
"onetime": "^6.0.0",
"signal-exit": "^3.0.7",
"strip-final-newline": "^3.0.0"
},
"devDependencies": {
"@types/node": "^14.14.10",
"ava": "^2.4.0",
"get-node": "^11.0.1",
"@types/node": "^18.13.0",
"ava": "^5.2.0",
"c8": "^7.12.0",
"get-node": "^13.5.0",
"is-running": "^2.1.0",
"nyc": "^15.1.0",
"p-event": "^4.2.0",
"tempfile": "^3.0.0",
"tsd": "^0.13.1",
"xo": "^0.35.0"
"p-event": "^5.0.1",
"path-key": "^4.0.0",
"tempfile": "^4.0.0",
"tsd": "^0.25.0",
"xo": "^0.53.1"
},
"nyc": {
"c8": {
"reporter": [
"text",
"lcov"
@@ -70,5 +73,14 @@
"**/test.js",
"**/test/**"
]
},
"ava": {
"workerThreads": false
},
"xo": {
"rules": {
"unicorn/no-empty-file": "off",
"@typescript-eslint/ban-types": "off"
}
}
}

441
node_modules/execa/readme.md generated vendored
View File

@@ -1,4 +1,7 @@
<img src="media/logo.svg" width="400">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="media/logo_dark.svg">
<img alt="execa logo" src="media/logo.svg" width="400">
</picture>
<br>
[![Coverage Status](https://codecov.io/gh/sindresorhus/execa/branch/main/graph/badge.svg)](https://codecov.io/gh/sindresorhus/execa)
@@ -9,123 +12,173 @@
This package improves [`child_process`](https://nodejs.org/api/child_process.html) methods with:
- Promise interface.
- [Promise interface](#execacommandcommand-options).
- [Scripts interface](#scripts-interface), like `zx`.
- Improved [Windows support](https://github.com/IndigoUnited/node-cross-spawn#why), including [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)) binaries.
- Executes [locally installed binaries](#preferlocal) without `npx`.
- [Cleans up](#cleanup) child processes when the parent process ends.
- [Graceful termination](#optionsforcekillaftertimeout).
- Get [interleaved output](#all) from `stdout` and `stderr` similar to what is printed on the terminal.
- [Strips the final newline](#stripfinalnewline) from the output so you don't have to do `stdout.trim()`.
- Supports [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)) binaries cross-platform.
- [Improved Windows support.](https://github.com/IndigoUnited/node-cross-spawn#why)
- Higher max buffer. 100 MB instead of 200 KB.
- [Executes locally installed binaries by name.](#preferlocal)
- [Cleans up spawned processes when the parent process dies.](#cleanup)
- [Get interleaved output](#all) from `stdout` and `stderr` similar to what is printed on the terminal. [*(Async only)*](#execasyncfile-arguments-options)
- [Can specify file and arguments as a single string without a shell](#execacommandcommand-options)
- Convenience methods to pipe processes' [input](#input) and [output](#redirect-output-to-a-file).
- Can specify file and arguments [as a single string](#execacommandcommand-options) without a shell.
- [Verbose mode](#verbose-mode) for debugging.
- More descriptive errors.
- Higher max buffer: 100 MB instead of 1 MB.
## Install
```
$ npm install execa
```sh
npm install execa
```
## Usage
```js
const execa = require('execa');
### Promise interface
(async () => {
const {stdout} = await execa('echo', ['unicorns']);
console.log(stdout);
//=> 'unicorns'
})();
```js
import {execa} from 'execa';
const {stdout} = await execa('echo', ['unicorns']);
console.log(stdout);
//=> 'unicorns'
```
### Pipe the child process stdout to the parent
### Scripts interface
For more information about Execa scripts, please see [this page](docs/scripts.md).
#### Basic
```js
const execa = require('execa');
import {$} from 'execa';
execa('echo', ['unicorns']).stdout.pipe(process.stdout);
const branch = await $`git branch --show-current`;
await $`dep deploy --branch=${branch}`;
```
#### Multiple arguments
```js
import {$} from 'execa';
const args = ['unicorns', '&', 'rainbows!'];
const {stdout} = await $`echo ${args}`;
console.log(stdout);
//=> 'unicorns & rainbows!'
```
#### With options
```js
import {$} from 'execa';
await $({stdio: 'inherit'})`echo unicorns`;
//=> 'unicorns'
```
#### Shared options
```js
import {$} from 'execa';
const $$ = $({stdio: 'inherit'});
await $$`echo unicorns`;
//=> 'unicorns'
await $$`echo rainbows`;
//=> 'rainbows'
```
#### Verbose mode
```sh
> node file.js
unicorns
rainbows
> NODE_DEBUG=execa node file.js
[16:50:03.305] echo unicorns
unicorns
[16:50:03.308] echo rainbows
rainbows
```
### Input/output
#### Redirect output to a file
```js
import {execa} from 'execa';
// Similar to `echo unicorns > stdout.txt` in Bash
await execa('echo', ['unicorns']).pipeStdout('stdout.txt');
// Similar to `echo unicorns 2> stdout.txt` in Bash
await execa('echo', ['unicorns']).pipeStderr('stderr.txt');
// Similar to `echo unicorns &> stdout.txt` in Bash
await execa('echo', ['unicorns'], {all: true}).pipeAll('all.txt');
```
#### Redirect input from a file
```js
import {execa} from 'execa';
// Similar to `cat < stdin.txt` in Bash
const {stdout} = await execa('cat', {inputFile: 'stdin.txt'});
console.log(stdout);
//=> 'unicorns'
```
#### Save and pipe output from a child process
```js
import {execa} from 'execa';
const {stdout} = await execa('echo', ['unicorns']).pipeStdout(process.stdout);
// Prints `unicorns`
console.log(stdout);
// Also returns 'unicorns'
```
#### Pipe multiple processes
```js
import {execa} from 'execa';
// Similar to `echo unicorns | cat` in Bash
const {stdout} = await execa('echo', ['unicorns']).pipeStdout(execa('cat'));
console.log(stdout);
//=> 'unicorns'
```
### Handling Errors
```js
const execa = require('execa');
import {execa} from 'execa';
(async () => {
// Catching an error
try {
await execa('unknown', ['command']);
} catch (error) {
console.log(error);
/*
{
message: 'Command failed with ENOENT: unknown command spawn unknown ENOENT',
errno: -2,
code: 'ENOENT',
syscall: 'spawn unknown',
path: 'unknown',
spawnargs: ['command'],
originalMessage: 'spawn unknown ENOENT',
shortMessage: 'Command failed with ENOENT: unknown command spawn unknown ENOENT',
command: 'unknown command',
escapedCommand: 'unknown command',
stdout: '',
stderr: '',
all: '',
failed: true,
timedOut: false,
isCanceled: false,
killed: false
}
*/
}
})();
```
### Cancelling a spawned process
```js
const execa = require('execa');
(async () => {
const subprocess = execa('node');
setTimeout(() => {
subprocess.cancel();
}, 1000);
try {
await subprocess;
} catch (error) {
console.log(subprocess.killed); // true
console.log(error.isCanceled); // true
}
})()
```
### Catching an error with the sync method
```js
// Catching an error
try {
execa.sync('unknown', ['command']);
await execa('unknown', ['command']);
} catch (error) {
console.log(error);
/*
{
message: 'Command failed with ENOENT: unknown command spawnSync unknown ENOENT',
message: 'Command failed with ENOENT: unknown command spawn unknown ENOENT',
errno: -2,
code: 'ENOENT',
syscall: 'spawnSync unknown',
syscall: 'spawn unknown',
path: 'unknown',
spawnargs: ['command'],
originalMessage: 'spawnSync unknown ENOENT',
shortMessage: 'Command failed with ENOENT: unknown command spawnSync unknown ENOENT',
originalMessage: 'spawn unknown ENOENT',
shortMessage: 'Command failed with ENOENT: unknown command spawn unknown ENOENT',
command: 'unknown command',
escapedCommand: 'unknown command',
stdout: '',
stderr: '',
all: '',
failed: true,
timedOut: false,
isCanceled: false,
@@ -135,7 +188,7 @@ try {
}
```
### Kill a process
### Graceful termination
Using SIGTERM, and after 2 seconds, kill it with SIGKILL.
@@ -151,17 +204,84 @@ setTimeout(() => {
## API
### execa(file, arguments, options?)
### Methods
Execute a file. Think of this as a mix of [`child_process.execFile()`](https://nodejs.org/api/child_process.html#child_process_child_process_execfile_file_args_options_callback) and [`child_process.spawn()`](https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options).
#### execa(file, arguments?, options?)
No escaping/quoting is needed.
Executes a command using `file ...arguments`. `arguments` are specified as an array of strings. Returns a [`childProcess`](#childprocess).
Unless the [`shell`](#shell) option is used, no shell interpreter (Bash, `cmd.exe`, etc.) is used, so shell features such as variables substitution (`echo $PATH`) are not allowed.
Arguments are [automatically escaped](#shell-syntax). They can contain any character, including spaces.
Returns a [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess) which:
- is also a `Promise` resolving or rejecting with a [`childProcessResult`](#childProcessResult).
- exposes the following additional methods and properties.
This is the preferred method when executing single commands.
#### execaNode(scriptPath, arguments?, options?)
Executes a Node.js file using `node scriptPath ...arguments`. `arguments` are specified as an array of strings. Returns a [`childProcess`](#childprocess).
Arguments are [automatically escaped](#shell-syntax). They can contain any character, including spaces.
This is the preferred method when executing Node.js files.
Like [`child_process#fork()`](https://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options):
- the current Node version and options are used. This can be overridden using the [`nodePath`](#nodepath-for-node-only) and [`nodeOptions`](#nodeoptions-for-node-only) options.
- the [`shell`](#shell) option cannot be used
- an extra channel [`ipc`](https://nodejs.org/api/child_process.html#child_process_options_stdio) is passed to [`stdio`](#stdio)
#### $\`command\`
Executes a command. The `command` string includes both the `file` and its `arguments`. Returns a [`childProcess`](#childprocess).
Arguments are [automatically escaped](#shell-syntax). They can contain any character, but spaces must use `${}` like `` $`echo ${'has space'}` ``.
This is the preferred method when executing multiple commands in a script file.
The `command` string can inject any `${value}` with the following types: string, number, [`childProcess`](#childprocess) or an array of those types. For example: `` $`echo one ${'two'} ${3} ${['four', 'five']}` ``. For `${childProcess}`, the process's `stdout` is used.
For more information, please see [this section](#scripts-interface) and [this page](docs/scripts.md).
#### $(options)
Returns a new instance of [`$`](#command) but with different default `options`. Consecutive calls are merged to previous ones.
This can be used to either:
- Set options for a specific command: `` $(options)`command` ``
- Share options for multiple commands: `` const $$ = $(options); $$`command`; $$`otherCommand`; ``
#### execaCommand(command, options?)
Executes a command. The `command` string includes both the `file` and its `arguments`. Returns a [`childProcess`](#childprocess).
Arguments are [automatically escaped](#shell-syntax). They can contain any character, but spaces must be escaped with a backslash like `execaCommand('echo has\\ space')`.
This is the preferred method when executing a user-supplied `command` string, such as in a REPL.
### execaSync(file, arguments?, options?)
Same as [`execa()`](#execacommandcommand-options) but synchronous.
Returns or throws a [`childProcessResult`](#childProcessResult).
### $.sync\`command\`
Same as [$\`command\`](#command) but synchronous.
Returns or throws a [`childProcessResult`](#childProcessResult).
### execaCommandSync(command, options?)
Same as [`execaCommand()`](#execacommand-command-options) but synchronous.
Returns or throws a [`childProcessResult`](#childProcessResult).
### Shell syntax
For all the [methods above](#methods), no shell interpreter (Bash, cmd.exe, etc.) is used unless the [`shell` option](#shell) is set. This means shell-specific characters and expressions (`$variable`, `&&`, `||`, `;`, `|`, etc.) have no special meaning and do not need to be escaped.
### childProcess
The return value of all [asynchronous methods](#methods) is both:
- a `Promise` resolving or rejecting with a [`childProcessResult`](#childProcessResult).
- a [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess) with the following additional methods and properties.
#### kill(signal?, options?)
@@ -176,10 +296,6 @@ Milliseconds to wait for the child process to terminate before sending `SIGKILL`
Can be disabled with `false`.
#### cancel()
Similar to [`childProcess.kill()`](https://nodejs.org/api/child_process.html#child_process_subprocess_kill_signal). This is preferred when cancelling the child process execution as the error is more descriptive and [`childProcessResult.isCanceled`](#iscanceled) is set to `true`.
#### all
Type: `ReadableStream | undefined`
@@ -190,34 +306,28 @@ This is `undefined` if either:
- the [`all` option](#all-2) is `false` (the default value)
- both [`stdout`](#stdout-1) and [`stderr`](#stderr-1) options are set to [`'inherit'`, `'ipc'`, `Stream` or `integer`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio)
### execa.sync(file, arguments?, options?)
#### pipeStdout(target)
Execute a file synchronously.
[Pipe](https://nodejs.org/api/stream.html#readablepipedestination-options) the child process's `stdout` to `target`, which can be:
- Another [`execa()` return value](#pipe-multiple-processes)
- A [writable stream](#save-and-pipe-output-from-a-child-process)
- A [file path string](#redirect-output-to-a-file)
Returns or throws a [`childProcessResult`](#childProcessResult).
If the `target` is another [`execa()` return value](#execacommandcommand-options), it is returned. Otherwise, the original `execa()` return value is returned. This allows chaining `pipeStdout()` then `await`ing the [final result](#childprocessresult).
### execa.command(command, options?)
The [`stdout` option](#stdout-1) must be kept as `pipe`, its default value.
Same as [`execa()`](#execafile-arguments-options) except both file and arguments are specified in a single `command` string. For example, `execa('echo', ['unicorns'])` is the same as `execa.command('echo unicorns')`.
#### pipeStderr(target)
If the file or an argument contains spaces, they must be escaped with backslashes. This matters especially if `command` is not a constant but a variable, for example with `__dirname` or `process.cwd()`. Except for spaces, no escaping/quoting is needed.
Like [`pipeStdout()`](#pipestdouttarget) but piping the child process's `stderr` instead.
The [`shell` option](#shell) must be used if the `command` uses shell-specific features (for example, `&&` or `||`), as opposed to being a simple `file` followed by its `arguments`.
The [`stderr` option](#stderr-1) must be kept as `pipe`, its default value.
### execa.commandSync(command, options?)
#### pipeAll(target)
Same as [`execa.command()`](#execacommand-command-options) but synchronous.
Combines both [`pipeStdout()`](#pipestdouttarget) and [`pipeStderr()`](#pipestderrtarget).
Returns or throws a [`childProcessResult`](#childProcessResult).
### execa.node(scriptPath, arguments?, options?)
Execute a Node.js script as a child process.
Same as `execa('node', [scriptPath, ...arguments], options)` except (like [`child_process#fork()`](https://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options)):
- the current Node version and options are used. This can be overridden using the [`nodePath`](#nodepath-for-node-only) and [`nodeOptions`](#nodeoptions-for-node-only) options.
- the [`shell`](#shell) option cannot be used
- an extra channel [`ipc`](https://nodejs.org/api/child_process.html#child_process_options_stdio) is passed to [`stdio`](#stdio)
Either the [`stdout` option](#stdout-1) or the [`stderr` option](#stderr-1) must be kept as `pipe`, their default value. Also, the [`all` option](#all-2) must be set to `true`.
### childProcessResult
@@ -238,16 +348,16 @@ Type: `string`
The file and arguments that were run, for logging purposes.
This is not escaped and should not be executed directly as a process, including using [`execa()`](#execafile-arguments-options) or [`execa.command()`](#execacommandcommand-options).
This is not escaped and should not be executed directly as a process, including using [`execa()`](#execafile-arguments-options) or [`execaCommand()`](#execacommandcommand-options).
#### escapedCommand
Type: `string`
Same as [`command`](#command) but escaped.
Same as [`command`](#command-1) but escaped.
This is meant to be copy and pasted into a shell, for debugging purposes.
Since the escaping is fairly basic, this should not be executed directly as a process, including using [`execa()`](#execafile-arguments-options) or [`execa.command()`](#execacommandcommand-options).
Since the escaping is fairly basic, this should not be executed directly as a process, including using [`execa()`](#execafile-arguments-options) or [`execaCommand()`](#execacommandcommand-options).
#### exitCode
@@ -275,7 +385,7 @@ The output of the process with `stdout` and `stderr` interleaved.
This is `undefined` if either:
- the [`all` option](#all-2) is `false` (the default value)
- `execa.sync()` was used
- `execaSync()` was used
#### failed
@@ -295,6 +405,8 @@ Type: `boolean`
Whether the process was canceled.
You can cancel the spawned process using the [`signal`](#signal-1) option.
#### killed
Type: `boolean`
@@ -355,14 +467,14 @@ Kill the spawned process when the parent process exits unless either:
#### preferLocal
Type: `boolean`\
Default: `false`
Default: `true` with [`$`](#command)/[`$.sync`](#synccommand), `false` otherwise
Prefer locally installed binaries when looking for a binary to execute.\
If you `$ npm install foo`, you can then `execa('foo')`.
#### localDir
Type: `string`\
Type: `string | URL`\
Default: `process.cwd()`
Preferred path to find locally installed binaries in (use with `preferLocal`).
@@ -396,6 +508,16 @@ Type: `string | Buffer | stream.Readable`
Write some input to the `stdin` of your binary.\
Streams are not allowed when using the synchronous methods.
If the input is a file, use the [`inputFile` option](#inputfile) instead.
#### inputFile
Type: `string`
Use a file as input to the the `stdin` of your binary.
If the input is not a file, use the [`input` option](#input) instead.
#### stdin
Type: `string | number | Stream | undefined`\
@@ -451,7 +573,7 @@ Execa also accepts the below options which are the same as the options for [`chi
#### cwd
Type: `string`\
Type: `string | URL`\
Default: `process.cwd()`
Current working directory of the child process.
@@ -481,12 +603,10 @@ Child's [stdio](https://nodejs.org/api/child_process.html#child_process_options_
Type: `string`\
Default: `'json'`
Specify the kind of serialization used for sending messages between processes when using the [`stdio: 'ipc'`](#stdio) option or [`execa.node()`](#execanodescriptpath-arguments-options):
Specify the kind of serialization used for sending messages between processes when using the [`stdio: 'ipc'`](#stdio) option or [`execaNode()`](#execanodescriptpath-arguments-options):
- `json`: Uses `JSON.stringify()` and `JSON.parse()`.
- `advanced`: Uses [`v8.serialize()`](https://nodejs.org/api/v8.html#v8_v8_serialize_value)
Requires Node.js `13.2.0` or later.
[More info.](https://nodejs.org/api/child_process.html#child_process_advanced_serialization)
#### detached
@@ -547,6 +667,16 @@ Default: `SIGTERM`
Signal value to be used when the spawned process will be killed.
#### signal
Type: [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal)
You can abort the spawned process using [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController).
When `AbortController.abort()` is called, [`.isCanceled`](#iscanceled) becomes `false`.
*Requires Node.js 16 or later.*
#### windowsVerbatimArguments
Type: `boolean`\
@@ -561,6 +691,15 @@ Default: `true`
On Windows, do not create a new console window. Please note this also prevents `CTRL-C` [from working](https://github.com/nodejs/node/issues/29837) on Windows.
#### verbose
Type: `boolean`\
Default: `false`
[Print each command](#verbose-mode) on `stderr` before executing it.
This can also be enabled by setting the `NODE_DEBUG=execa` environment variable in the current process.
#### nodePath *(For `.node()` only)*
Type: `string`\
@@ -582,59 +721,43 @@ List of [CLI options](https://nodejs.org/api/cli.html#cli_options) passed to the
Gracefully handle failures by using automatic retries and exponential backoff with the [`p-retry`](https://github.com/sindresorhus/p-retry) package:
```js
const pRetry = require('p-retry');
import pRetry from 'p-retry';
const run = async () => {
const results = await execa('curl', ['-sSL', 'https://sindresorhus.com/unicorn']);
return results;
};
(async () => {
console.log(await pRetry(run, {retries: 5}));
})();
console.log(await pRetry(run, {retries: 5}));
```
### Save and pipe output from a child process
Let's say you want to show the output of a child process in real-time while also saving it to a variable.
### Cancelling a spawned process
```js
const execa = require('execa');
import {execa} from 'execa';
const subprocess = execa('echo', ['foo']);
subprocess.stdout.pipe(process.stdout);
const abortController = new AbortController();
const subprocess = execa('node', [], {signal: abortController.signal});
(async () => {
const {stdout} = await subprocess;
console.log('child output:', stdout);
})();
```
setTimeout(() => {
abortController.abort();
}, 1000);
### Redirect output to a file
```js
const execa = require('execa');
const subprocess = execa('echo', ['foo'])
subprocess.stdout.pipe(fs.createWriteStream('stdout.txt'))
```
### Redirect input from a file
```js
const execa = require('execa');
const subprocess = execa('cat')
fs.createReadStream('stdin.txt').pipe(subprocess.stdin)
try {
await subprocess;
} catch (error) {
console.log(subprocess.killed); // true
console.log(error.isCanceled); // true
}
```
### Execute the current package's binary
```js
const {getBinPathSync} = require('get-bin-path');
import {getBinPath} from 'get-bin-path';
const binPath = getBinPathSync();
const subprocess = execa(binPath);
const binPath = await getBinPath();
await execa(binPath);
```
`execa` can be combined with [`get-bin-path`](https://github.com/ehmicky/get-bin-path) to test the current package's binary. As opposed to hard-coding the path to the binary, this validates that the `package.json` `bin` field is correctly set up.