Skip to content
Myr

Add `nodeChildProcess` to subprocess promises and make the subprocess a normal promise (#1255)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Sindre Sorhus · committed by GitHub · parent 29d9cfc · Browse files · 47 files+389 added−155 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

47 files+389 added−155 removed

  • tests:+174 added−71 removed
  • other:+215 added−84 removed

47 files+389 added−155 removed

modified:docs/api.md+12 added-2 removed
209 unmodified lines
210211## Return value212213_TypeScript:_ [`ResultPromise`](typescript.md)\214_Type:_ `Promise<object> | Subprocess`214_Type:_ `Subprocess`215216The return value of all [asynchronous methods](#methods) is both:217- the [subprocess](#subprocess).218- a `Promise` either resolving with its successful [`result`](#result), or rejecting with its [`error`](#execaerror).
3 unmodified lines
222## Subprocess223224_TypeScript:_ [`Subprocess`](typescript.md)225226[`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess) with the following methods and properties.226Promise with the following Execa-specific methods and properties.227228The underlying Node.js [`ChildProcess`](https://nodejs.org/api/child_process.html#class-childprocess) instance is available as [`subprocess.nodeChildProcess`](#subprocessnodechildprocess). This is an escape hatch for Node.js-specific APIs that Execa does not document, such as `.on()`, `.send()`, `.disconnect()`, `.ref()` and `.unref()`.229230### subprocess\[Symbol.asyncIterator\]()231232_Returns_: [`AsyncIterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols)233
102 unmodified lines
336This is `undefined` if the subprocess failed to spawn.337338[More info.](termination.md#inter-process-termination)339340### subprocess.nodeChildProcess341342_Type:_ [`ChildProcess`](https://nodejs.org/api/child_process.html#class-childprocess)343344Underlying Node.js child process instance.345346This is intended as an escape hatch for Node.js-specific APIs that Execa does not document.347348### subprocess.sendMessage(message, sendMessageOptions)349350`message`: [`Message`](ipc.md#message-type)\351`sendMessageOptions`: [`SendMessageOptions`](#sendmessageoptions)\
995 unmodified lines
modified:docs/execution.md+2 added-2 removed
modified:lib/convert/duplex.js+1 added-1 removed
50 unmodified lines
51 readable: duplex,52 subprocess,53 subprocessStdin,54 });55 onStdinFinished(subprocessStdin, duplex, subprocessStdout);55 onStdinFinished(subprocessStdin, duplex, subprocessStdout, subprocess);56 return duplex;57};5859const onDuplexDestroy = async ({subprocessStdout, subprocessStdin, subprocess, waitReadableDestroy, waitWritableFinal, waitWritableDestroy}, error) => {
10 unmodified lines
modified:lib/convert/readable.js+15 added-1 removed
94 unmodified lines
95 readable.push(null);96 }97 } catch (error) {98 await safeWaitForSubprocessStdin(subprocessStdin);99 destroyOtherReadable(readable, error);99 destroyOtherReadable(readable, await getPrematureCloseError(subprocess, error));100 }101};102103const getPrematureCloseError = async (subprocess, error) => {104 if (error.code !== 'ERR_STREAM_PREMATURE_CLOSE') {105 return error;106 }107108 try {109 await subprocess;110 } catch (subprocessError) {111 return subprocessError;112 }113114 return error;115};116117// When `readable` aborts/errors, do the same on `subprocess.stdout`118export const onReadableDestroy = async ({subprocessStdout, subprocess, waitReadableDestroy}, error) => {119 if (!await waitForConcurrentStreams(waitReadableDestroy, subprocess)) {120 return;
9 unmodified lines
modified:lib/convert/writable.js+22 added-3 removed
1import {Writable} from 'node:stream';2import {callbackify} from 'node:util';3import {getToStream} from '../arguments/fd-options.js';4import {isStreamAbort} from '../resolve/wait-stream.js';5import {addConcurrentStream, waitForConcurrentStreams} from './concurrent.js';6import {7 safeWaitForSubprocessStdout,8 waitForSubprocessStdin,
14 unmodified lines
23 })),24 highWaterMark: subprocessStdin.writableHighWaterMark,25 objectMode: subprocessStdin.writableObjectMode,26 });26 onStdinFinished(subprocessStdin, writable);27 onStdinFinished(subprocessStdin, writable, undefined, subprocess);28 return writable;29};3031// Retrieve `stdin` (or other stream depending on `to`)
34 unmodified lines
66 await subprocess;67};6869// When `subprocess.stdin` ends/aborts/errors, do the same on `writable`.69export const onStdinFinished = async (subprocessStdin, writable, subprocessStdout) => {70export const onStdinFinished = async (subprocessStdin, writable, subprocessStdout, subprocess) => {71 try {72 await waitForSubprocessStdin(subprocessStdin);73 await subprocess;74 if (writable.writable) {75 writable.end();76 }77 } catch (error) {78 await safeWaitForSubprocessStdout(subprocessStdout);77 destroyOtherWritable(writable, error);79 destroyOtherWritable(writable, await getSubprocessError(subprocess, error));80 }81};8283const getSubprocessError = async (subprocess, error) => {84 if (!shouldUseSubprocessError(error)) {85 return error;86 }8788 try {89 await subprocess;90 } catch (subprocessError) {91 return subprocessError;92 }9394 return error;95};9697const shouldUseSubprocessError = error => error === undefined98 || isStreamAbort(error);99100// When `writable` aborts/errors, do the same on `subprocess.stdin`101export const onWritableDestroy = async ({subprocessStdin, subprocess, waitWritableFinal, waitWritableDestroy}, error) => {102 await waitForConcurrentStreams(waitWritableFinal, subprocess);103 if (await waitForConcurrentStreams(waitWritableDestroy, subprocess)) {
8 unmodified lines
modified:lib/ipc/forward.js+1 added-1 removed
49 unmodified lines
50// Check whether there might still be some `message` events to receive51export const isConnected = anyProcess => {52 const ipcEmitter = IPC_EMITTERS.get(anyProcess);53 return ipcEmitter === undefined54 ? anyProcess.channel !== null54 ? anyProcess.channel !== undefined && anyProcess.channel !== null55 : ipcEmitter.connected;56};
modified:lib/ipc/get-each.js+4 added-3 removed
18 unmodified lines
19 });20};2122// Same but used internally23export const loopOnMessages = ({anyProcess, channel, isSubprocess, ipc, shouldAwait, reference, signal}) => {23export const loopOnMessages = ({anyProcess, waitProcess = anyProcess, channel, isSubprocess, ipc, shouldAwait, reference, signal}) => {24 validateIpcMethod({25 methodName: 'getEachMessage',26 isSubprocess,27 ipc,
13 unmodified lines
41 state,42 });43 return iterateOnMessages({44 anyProcess,45 waitProcess,46 channel,47 ipcEmitter,48 isSubprocess,49 shouldAwait,
33 unmodified lines
83 controller.abort();84 } catch {}85};8686const iterateOnMessages = async function * ({anyProcess, channel, ipcEmitter, isSubprocess, shouldAwait, controller, state, reference}) {87const iterateOnMessages = async function * ({anyProcess, waitProcess, channel, ipcEmitter, isSubprocess, shouldAwait, controller, state, reference}) {88 try {89 for await (const [message] of on(ipcEmitter, 'message', {signal: controller.signal})) {90 throwIfStrictError(state);91 yield message;
8 unmodified lines
100 disconnect(anyProcess);101 }102103 if (shouldAwait) {103 await anyProcess;104 await waitProcess;105 }106 }107};108
5 unmodified lines
modified:lib/ipc/ipc-input.js+8 added-2 removed
1import {serialize} from 'node:v8';2import {sendMessage} from './send.js';34// Validate the `ipcInput` option5export const validateIpcInputOption = ({ipcInput, ipc, serialization}) => {6 if (ipcInput === undefined) {
28 unmodified lines
35 json: validateJsonInput,36};3738// When the `ipcInput` option is set, it is sent as an initial IPC message to the subprocess38export const sendIpcInput = async (subprocess, ipcInput) => {39export const sendIpcInput = async (subprocess, ipcInput, ipc) => {40 if (ipcInput === undefined) {41 return;42 }4343 await subprocess.sendMessage(ipcInput);44 await sendMessage({45 anyProcess: subprocess,46 channel: subprocess.channel,47 isSubprocess: false,48 ipc,49 }, ipcInput);50};
modified:lib/ipc/methods.js+4 added-3 removed
3 unmodified lines
4import {getEachMessage} from './get-each.js';5import {getCancelSignal} from './graceful.js';67// Add promise-based IPC methods in current process8export const addIpcMethods = (subprocess, {ipc}) => {9 Object.assign(subprocess, getIpcMethods(subprocess, false, ipc));8export const addIpcMethods = (target, subprocess, {ipc}) => {9 Object.assign(target, getIpcMethods(subprocess, false, ipc, target));10};1112// Get promise-based IPC in the subprocess13export const getIpcExport = () => {
12 unmodified lines
26 };27};2829// Retrieve the `ipc` shared by both the current process and the subprocess30const getIpcMethods = (anyProcess, isSubprocess, ipc) => ({30const getIpcMethods = (anyProcess, isSubprocess, ipc, waitProcess = anyProcess) => ({31 sendMessage: sendMessage.bind(undefined, {32 anyProcess,33 channel: anyProcess.channel,34 isSubprocess,
9 unmodified lines
44 anyProcess,45 channel: anyProcess.channel,46 isSubprocess,47 ipc,48 waitProcess,49 }),50});
modified:lib/ipc/outgoing.js+9 added-3 removed
1import {createDeferred} from '../utils/deferred.js';2import {getFdSpecificValue} from '../arguments/specific.js';3import {SUBPROCESS_OPTIONS} from '../arguments/fd-options.js';3import {validateStrictDeadlock} from './strict.js';45// When `sendMessage()` is ongoing, any `message` being received waits before being emitted.6// This allows calling one or multiple `await sendMessage()` followed by `await getOneMessage()`/`await getEachMessage()`.
26 unmodified lines
33 }34};3536const OUTGOING_MESSAGES = new WeakMap();37const IPC_SUBPROCESS_OPTIONS = new WeakMap();3839export const setIpcSubprocessOptions = (subprocess, options) => {40 IPC_SUBPROCESS_OPTIONS.set(subprocess, options);41};4243// Whether any `message` listener is setup44export const hasMessageListeners = (anyProcess, ipcEmitter) => ipcEmitter.listenerCount('message') > getMinListenerCount(anyProcess);4546// When `buffer` is `false`, we set up a `message` listener that should be ignored.47// That listener is only meant to intercept `strict` acknowledgement responses.44const getMinListenerCount = anyProcess => SUBPROCESS_OPTIONS.has(anyProcess)45 && !getFdSpecificValue(SUBPROCESS_OPTIONS.get(anyProcess).options.buffer, 'ipc')48const getMinListenerCount = anyProcess => getOptions(anyProcess) !== undefined49 && !getFdSpecificValue(getOptions(anyProcess).buffer, 'ipc')50 ? 151 : 0;5253const getOptions = anyProcess => IPC_SUBPROCESS_OPTIONS.get(anyProcess);
modified:lib/methods/main-async.js+49 added-9 removed
4 unmodified lines
5import {normalizeOptions} from '../arguments/options.js';6import {SUBPROCESS_OPTIONS} from '../arguments/fd-options.js';7import {concatenateShell} from '../arguments/shell.js';8import {addIpcMethods} from '../ipc/methods.js';9import {setIpcSubprocessOptions} from '../ipc/outgoing.js';10import {makeError, makeSuccessResult} from '../return/result.js';11import {handleResult} from '../return/reject.js';12import {handleEarlyError} from '../return/early-error.js';13import {handleStdioAsync} from '../stdio/handle-async.js';
10 unmodified lines
2425// Main shared logic for all async methods: `execa()`, `$`, `execaNode()`26export const execaCoreAsync = (rawFile, rawArguments, rawOptions, createNested) => {27 const {file, commandArguments, command, escapedCommand, startTime, verboseInfo, options, fileDescriptors} = handleAsyncArguments(rawFile, rawArguments, rawOptions);27 const {subprocess, promise} = spawnSubprocessAsync({28 const {subprocess: nodeChildProcess, promise, kill, all, convertedStreams} = spawnSubprocessAsync({29 file,30 commandArguments,31 options,32 startTime,
1 unmodified line
34 command,35 escapedCommand,36 fileDescriptors,37 });38 const subprocess = getSubprocessPromise({39 promise,40 nodeChildProcess,41 kill,42 all,43 convertedStreams,44 options,45 });46 subprocess.pipe = pipeToSubprocess.bind(undefined, {47 source: subprocess,48 sourcePromise: promise,49 boundOptions: {},50 createNested,51 });43 mergePromise(subprocess, promise);52 SUBPROCESS_OPTIONS.set(subprocess, {options, fileDescriptors});53 return subprocess;54};55
45 unmodified lines
101 setMaxListeners(Infinity, controller.signal);102103 const originalStreams = [...subprocess.stdio];104 pipeOutputAsync(subprocess, fileDescriptors, controller);97 cleanupOnExit(subprocess, options, controller);105 setIpcSubprocessOptions(subprocess, options);106107 const context = {};108 const onInternalError = createDeferred();101 subprocess.kill = subprocessKill.bind(undefined, {109 const kill = subprocessKill.bind(undefined, {110 kill: subprocess.kill.bind(subprocess),111 options,112 onInternalError,113 context,114 controller,115 });108 subprocess.all = makeAllStream(subprocess, options);109 addConvertedStreams(subprocess, options);110 addIpcMethods(subprocess, options);116 cleanupOnExit(kill, options, controller);117 const all = makeAllStream(subprocess, options);118119 const promise = handlePromise({120 subprocess,121 kill,122 all,123 options,124 startTime,125 verboseInfo,126 fileDescriptors,
3 unmodified lines
130 context,131 onInternalError,132 controller,133 });125 return {subprocess, promise};134 return {135 subprocess,136 promise,137 kill,138 all,139 };140};141142const getSubprocessPromise = ({promise, nodeChildProcess, kill, all, convertedStreams, options}) => {143 const subprocess = mergePromise(promise, getSubprocessProperties(nodeChildProcess, all));144 subprocess.kill = kill ?? subprocess.kill;145 if (convertedStreams === undefined) {146 addConvertedStreams(subprocess, options);147 } else {148 Object.assign(subprocess, convertedStreams);149 }150151 addIpcMethods(subprocess, nodeChildProcess, options);152 return subprocess;153};154155const getSubprocessProperties = (nodeChildProcess, all) => ({156 nodeChildProcess,157 pid: nodeChildProcess.pid,158 stdin: nodeChildProcess.stdin,159 stdout: nodeChildProcess.stdout,160 stderr: nodeChildProcess.stderr,161 stdio: nodeChildProcess.stdio,162 all,163 kill: nodeChildProcess.kill.bind(nodeChildProcess),164});165166// Asynchronous logic, as opposed to the previous logic which can be run synchronously, i.e. can be returned to user right away129const handlePromise = async ({subprocess, options, startTime, verboseInfo, fileDescriptors, originalStreams, command, escapedCommand, context, onInternalError, controller}) => {167const handlePromise = async ({subprocess, kill, all: allStream, options, startTime, verboseInfo, fileDescriptors, originalStreams, command, escapedCommand, context, onInternalError, controller}) => {168 const [169 errorInfo,170 [exitCode, signal],171 stdioResults,172 allResult,173 ipcOutput,174 ] = await waitForSubprocessResult({175 subprocess,176 kill,177 all: allStream,178 options,179 context,180 verboseInfo,181 fileDescriptors,
53 unmodified lines
modified:lib/methods/promise.js+2 added-15 removed
1// The return value is a mixin of `subprocess` and `Promise`2export const mergePromise = (subprocess, promise) => {3 for (const [property, descriptor] of descriptors) {4 const value = descriptor.value.bind(promise);5 Reflect.defineProperty(subprocess, property, {...descriptor, value});6 }7};89// eslint-disable-next-line unicorn/prefer-top-level-await10const nativePromisePrototype = (async () => {})().constructor.prototype;1112const descriptors = ['then', 'catch', 'finally'].map(property => [13 property,14 Reflect.getOwnPropertyDescriptor(nativePromisePrototype, property),15]);1// The return value is a native Promise with Execa-specific properties.2export const mergePromise = (promise, properties) => Object.assign(promise, properties);
modified:lib/resolve/all-async.js+5 added-5 removed
5 unmodified lines
6 ? mergeStreams([stdout, stderr].filter(Boolean))7 : undefined;89// Read the contents of `subprocess.all` and|or wait for its completion10export const waitForAllStream = ({subprocess, encoding, buffer, maxBuffer, lines, stripFinalNewline, verboseInfo, streamInfo}) => waitForSubprocessStream({11 ...getAllStream(subprocess, buffer),10export const waitForAllStream = ({subprocess, all, encoding, buffer, maxBuffer, lines, stripFinalNewline, verboseInfo, streamInfo}) => waitForSubprocessStream({11 ...getAllStream(subprocess, all, buffer),12 fdNumber: 'all',13 encoding,14 maxBuffer: maxBuffer[1] + maxBuffer[2],15 lines: lines[1] || lines[2],16 allMixed: getAllMixed(subprocess),16 allMixed: getAllMixed(subprocess, all),17 stripFinalNewline,18 verboseInfo,19 streamInfo,20});2122const getAllStream = ({stdout, stderr, all}, [, bufferStdout, bufferStderr]) => {22const getAllStream = ({stdout, stderr}, all, [, bufferStdout, bufferStderr]) => {23 const buffer = bufferStdout || bufferStderr;24 if (!buffer) {25 return {stream: all, buffer};26 }
12 unmodified lines
39// When `subprocess.stdout` is in objectMode but not `subprocess.stderr` (or the opposite), we need to use both:40// - `getStreamAsArray()` for the chunks in objectMode, to return as an array without changing each chunk41// - `getStreamAsArrayBuffer()` or `getStream()` for the chunks not in objectMode, to convert them from Buffers to string or Uint8Array42// We do this by emulating the Buffer -> string|Uint8Array conversion performed by `get-stream` with our own, which is identical.43const getAllMixed = ({all, stdout, stderr}) => all43const getAllMixed = ({stdout, stderr}, all) => all44 && stdout45 && stderr46 && stdout.readableObjectMode !== stderr.readableObjectMode;
modified:lib/resolve/wait-subprocess.js+7 added-3 removed
14 unmodified lines
1516// Retrieve result of subprocess: exit code, signal, error, streams (stdout/stderr/all)17export const waitForSubprocessResult = async ({18 subprocess,19 kill,20 all,21 options: {22 encoding,23 buffer,24 maxBuffer,
33 unmodified lines
58 streamInfo,59 });60 const allPromise = waitForAllStream({61 subprocess,62 all,63 encoding,64 buffer,65 maxBuffer,66 lines,
20 unmodified lines
87 waitForSuccessfulExit(exitPromise),88 Promise.all(stdioPromises),89 allPromise,90 ipcOutputPromise,88 sendIpcInput(subprocess, ipcInput),91 sendIpcInput(subprocess, ipcInput, ipc),92 ...originalPromises,93 ...customStreamsEndPromises,94 ]),95 onInternalError,96 throwOnSubprocessError(subprocess, controller),94 ...throwOnTimeout(subprocess, timeout, context, controller),97 ...throwOnTimeout(kill, timeout, context, controller),98 ...throwOnCancel({96 subprocess,99 kill,100 cancelSignal,101 gracefulCancel,102 context,103 controller,104 }),105 ...throwOnGracefulCancel({106 subprocess,107 kill,108 cancelSignal,109 gracefulCancel,110 forceKillAfterDelay,111 context,
39 unmodified lines
modified:lib/return/early-error.js+18 added-11 removed
13 unmodified lines
14export const handleEarlyError = ({error, command, escapedCommand, fileDescriptors, options, startTime, verboseInfo}) => {15 cleanupCustomStreams(fileDescriptors);1617 const subprocess = new ChildProcess();18 createDummyStreams(subprocess, fileDescriptors);19 Object.assign(subprocess, {20 readable,21 writable,22 duplex,23 readableStream,24 writableStream,25 transformStream,26 });18 const all = createDummyStreams(subprocess, fileDescriptors);1920 const earlyError = makeEarlyError({21 error,22 command,
3 unmodified lines
26 startTime,27 isSync: false,28 });29 const promise = handleDummyPromise(earlyError, verboseInfo, options);38 return {subprocess, promise};30 return {31 subprocess,32 promise,33 all: options.all ? all : undefined,34 convertedStreams: {35 readable,36 writable,37 duplex,38 readableStream,39 writableStream,40 transformStream,41 iterable,42 [Symbol.asyncIterator]: iterable,43 },44 };45};4647const createDummyStreams = (subprocess, fileDescriptors) => {48 const stdin = createDummyStream();
5 unmodified lines
54 Object.assign(subprocess, {55 stdin,56 stdout,57 stderr,52 all,58 stdio,59 });60 return all;61};6263const createDummyStream = () => {64 const stream = new PassThrough();
6 unmodified lines
71const duplex = () => new Duplex({read() {}, write() {}});72const readableStream = () => Readable.toWeb(readable());73const writableStream = () => Writable.toWeb(writable());74const transformStream = () => Duplex.toWeb(duplex());75const iterable = async function * () {};7677const handleDummyPromise = async (error, verboseInfo, options) => handleResult(error, verboseInfo, options);
modified:lib/terminate/cancel.js+4 added-4 removed
6 unmodified lines
7 }8};910// Terminate the subprocess when aborting the `cancelSignal` option and `gracefulSignal` is `false`11export const throwOnCancel = ({subprocess, cancelSignal, gracefulCancel, context, controller}) => cancelSignal === undefined || gracefulCancel11export const throwOnCancel = ({kill, cancelSignal, gracefulCancel, context, controller}) => cancelSignal === undefined || gracefulCancel12 ? []13 : [terminateOnCancel(subprocess, cancelSignal, context, controller)];13 : [terminateOnCancel(kill, cancelSignal, context, controller)];1415const terminateOnCancel = async (subprocess, cancelSignal, context, {signal}) => {15const terminateOnCancel = async (kill, cancelSignal, context, {signal}) => {16 await onAbortedSignal(cancelSignal, signal);17 context.terminationReason ??= 'cancel';18 subprocess.kill();18 kill();19 throw cancelSignal.reason;20};
modified:lib/terminate/cleanup.js+2 added-2 removed
1import {addAbortListener} from 'node:events';2import {onExit} from 'signal-exit';34// If the `cleanup` option is used, call `subprocess.kill()` when the parent process exits5export const cleanupOnExit = (subprocess, {cleanup, detached}, {signal}) => {5export const cleanupOnExit = (kill, {cleanup, detached}, {signal}) => {6 if (!cleanup || detached) {7 return;8 }910 const removeExitHandler = onExit(() => {11 subprocess.kill();11 kill();12 });13 addAbortListener(signal, () => {14 removeExitHandler();15 });
1 unmodified line
modified:lib/terminate/graceful.js+4 added-2 removed
22 unmodified lines
2324// Send abort reason to the subprocess when aborting the `cancelSignal` option and `gracefulCancel` is `true`25export const throwOnGracefulCancel = ({26 subprocess,27 kill,28 cancelSignal,29 gracefulCancel,30 forceKillAfterDelay,31 context,32 controller,33}) => gracefulCancel34 ? [sendOnAbort({35 subprocess,36 kill,37 cancelSignal,38 forceKillAfterDelay,39 context,40 controller,41 })]42 : [];4342const sendOnAbort = async ({subprocess, cancelSignal, forceKillAfterDelay, context, controller: {signal}}) => {44const sendOnAbort = async ({subprocess, kill, cancelSignal, forceKillAfterDelay, context, controller: {signal}}) => {45 await onAbortedSignal(cancelSignal, signal);46 const reason = getReason(cancelSignal);47 await sendAbort(subprocess, reason);48 killOnTimeout({47 kill: subprocess.kill,49 kill,50 forceKillAfterDelay,51 context,52 controllerSignal: signal,53 });
20 unmodified lines
modified:lib/terminate/timeout.js+4 added-4 removed
7 unmodified lines
8 }9};1011// Fails when the `timeout` option is exceeded12export const throwOnTimeout = (subprocess, timeout, context, controller) => timeout === 0 || timeout === undefined12export const throwOnTimeout = (kill, timeout, context, controller) => timeout === 0 || timeout === undefined13 ? []14 : [killAfterTimeout(subprocess, timeout, context, controller)];14 : [killAfterTimeout(kill, timeout, context, controller)];1516const killAfterTimeout = async (subprocess, timeout, context, {signal}) => {16const killAfterTimeout = async (kill, timeout, context, {signal}) => {17 await setTimeout(timeout, undefined, {signal});18 context.terminationReason ??= 'timeout';19 subprocess.kill();19 kill();20 throw new DiscardedError();21};
modified:test/convert/writable.js+4 added-2 removed
179 unmodified lines
180 subprocess.stdin.destroy();181182 const error = await t.throwsAsync(finishedStream(stream));183 t.like(error, prematureClose);184 assertProcessNormalExit(t, error);184 assertWritableAborted(t, subprocess.stdin);185 t.true(subprocess.stdout.readableEnded);186 t.true(subprocess.stderr.readableEnded);188 await assertSubprocessError(t, subprocess, error);187 const subprocessError = await t.throwsAsync(subprocess);188 t.like(subprocessError, prematureClose);189 t.like(subprocessError.cause, prematureClose);190 assertProcessNormalExit(t, subprocessError);191};192193test('subprocess.stdin abort -> .writable() error + subprocess fail', testStdinAbort, 'writable');194test('subprocess.stdin abort -> .duplex() error + subprocess fail', testStdinAbort, 'duplex');
205 unmodified lines
modified:test/fixtures/ipc-send-pid.js+14 added-1 removed
2 unmodified lines
3import {execa, sendMessage} from '../../index.js';45const cleanup = process.argv[2] === 'true';6const detached = process.argv[3] === 'true';7const subprocess = execa('forever.js', {cleanup, detached});7const file = process.argv[4] === 'no-killable' ? 'no-killable.js' : 'forever.js';8const options = {9 cleanup,10 detached,11 ...(file === 'no-killable.js' && {12 ipc: true,13 killSignal: 'SIGKILL',14 }),15};16const subprocess = execa(file, options);17if (options.ipc) {18 await subprocess.getOneMessage();19}2021await sendMessage(subprocess.pid);22await subprocess;
modified:test/helpers/ipc.js+2 added-1 removed
30 unmodified lines
31// However, I/O errors are seldom and hard to trigger predictably.32// So we mock them.33export const mockSendIoError = anyProcess => {34 const error = new Error(foobarString);35 const target = anyProcess.nodeChildProcess ?? anyProcess;35 anyProcess.send = () => {36 target.send = () => {37 throw error;38 };3940 return error;
1 unmodified line
modified:test/ipc/forward.js+3 added-3 removed
9 unmodified lines
10 const subprocess = execa('ipc-send.js', {ipc: true, buffer});1112 const promise = subprocess.getOneMessage({filter});13 const cause = new Error(foobarString);14 subprocess.emit('error', cause);14 subprocess.nodeChildProcess.emit('error', cause);15 t.is(await promise, foobarString);1617 const error = await t.throwsAsync(subprocess);18 t.is(error.exitCode, undefined);
29 unmodified lines
48 const subprocess = execa('ipc-send-twice.js', {ipc: true, buffer});4950 const promise = iterateAllMessages(subprocess);51 const cause = new Error(foobarString);52 subprocess.emit('error', cause);52 subprocess.nodeChildProcess.emit('error', cause);5354 const error = await t.throwsAsync(subprocess);55 t.is(error, await t.throwsAsync(promise));56 t.is(error.exitCode, undefined);
25 unmodified lines
82test('"error" event does not interrupt result.ipcOutput', async t => {83 const subprocess = execa('ipc-echo-twice.js', {ipcInput: foobarString});8485 const cause = new Error(foobarString);86 subprocess.emit('error', cause);86 subprocess.nodeChildProcess.emit('error', cause);87 t.is(await subprocess.getOneMessage(), foobarString);88 await subprocess.sendMessage(foobarString);89 t.is(await subprocess.getOneMessage(), foobarString);90
6 unmodified lines
modified:test/ipc/get-each.js+10 added-10 removed
141 unmodified lines
142test('Disconnecting in the current process stops exports.getEachMessage()', async t => {143 const subprocess = execa('ipc-iterate-print.js', {ipc: true});144 t.is(await subprocess.getOneMessage(), foobarString);145 await subprocess.sendMessage('.');146 subprocess.disconnect();146 subprocess.nodeChildProcess.disconnect();147148 const {stdout} = await subprocess;149 t.is(stdout, '.');150});
20 unmodified lines
171172const testCleanupListeners = async (t, buffer) => {173 const subprocess = execa('ipc-send.js', {ipc: true, buffer});174175 t.is(subprocess.listenerCount('message'), 1);176 t.is(subprocess.listenerCount('disconnect'), 1);175 t.is(subprocess.nodeChildProcess.listenerCount('message'), 1);176 t.is(subprocess.nodeChildProcess.listenerCount('disconnect'), 1);177178 const promise = iterateAllMessages(subprocess);179 t.is(subprocess.listenerCount('message'), 1);180 t.is(subprocess.listenerCount('disconnect'), 1);179 t.is(subprocess.nodeChildProcess.listenerCount('message'), 1);180 t.is(subprocess.nodeChildProcess.listenerCount('disconnect'), 1);181 t.deepEqual(await promise, [foobarString]);182183 t.is(subprocess.listenerCount('message'), 0);184 t.is(subprocess.listenerCount('disconnect'), 0);183 t.is(subprocess.nodeChildProcess.listenerCount('message'), 0);184 t.is(subprocess.nodeChildProcess.listenerCount('disconnect'), 0);185};186187test('Cleans up subprocess.getEachMessage() listeners, buffer false', testCleanupListeners, false);188test('Cleans up subprocess.getEachMessage() listeners, buffer true', testCleanupListeners, true);189190const sendContinuousMessages = async subprocess => {191 while (subprocess.connected) {191 while (subprocess.nodeChildProcess.connected) {192 for (let index = 0; index < 10; index += 1) {193 subprocess.emit('message', foobarString);193 subprocess.nodeChildProcess.emit('message', foobarString);194 }195196 // eslint-disable-next-line no-await-in-loop197 await scheduler.yield();
3 unmodified lines
201test.serial('Handles buffered messages when disconnecting', async t => {202 const subprocess = execa('ipc-send-fail.js', {ipc: true, buffer: false});203204 const promise = subprocess.getOneMessage();205 subprocess.emit('message', foobarString);205 subprocess.nodeChildProcess.emit('message', foobarString);206 t.is(await promise, foobarString);207 sendContinuousMessages(subprocess);208209 const {exitCode, isTerminated, ipcOutput} = await t.throwsAsync(iterateAllMessages(subprocess));
4 unmodified lines
modified:test/ipc/get-one.js+7 added-7 removed
77 unmodified lines
7879const testCleanupListeners = async (t, buffer, filter) => {80 const subprocess = execa('ipc-send.js', {ipc: true, buffer});8182 t.is(subprocess.listenerCount('message'), 1);83 t.is(subprocess.listenerCount('disconnect'), 1);82 t.is(subprocess.nodeChildProcess.listenerCount('message'), 1);83 t.is(subprocess.nodeChildProcess.listenerCount('disconnect'), 1);8485 const promise = subprocess.getOneMessage({filter});86 t.is(subprocess.listenerCount('message'), 1);87 t.is(subprocess.listenerCount('disconnect'), 1);86 t.is(subprocess.nodeChildProcess.listenerCount('message'), 1);87 t.is(subprocess.nodeChildProcess.listenerCount('disconnect'), 1);8889 t.is(await promise, foobarString);90 await subprocess;9192 t.is(subprocess.listenerCount('message'), 0);93 t.is(subprocess.listenerCount('disconnect'), 0);92 t.is(subprocess.nodeChildProcess.listenerCount('message'), 0);93 t.is(subprocess.nodeChildProcess.listenerCount('disconnect'), 0);94};9596test('Cleans up subprocess.getOneMessage() listeners, buffer false', testCleanupListeners, false, undefined);97test('Cleans up subprocess.getOneMessage() listeners, buffer true', testCleanupListeners, true, undefined);
4 unmodified lines
102 const subprocess = execa('ipc-get-send-get.js', [`${filter}`], {ipc: true, buffer});103 await subprocess.sendMessage(foobarString);104 t.is(await subprocess.getOneMessage(), foobarString);105106 subprocess.disconnect();106 subprocess.nodeChildProcess.disconnect();107108 const {exitCode, isTerminated, message} = await t.throwsAsync(subprocess);109 t.is(exitCode, 1);110 t.false(isTerminated);
21 unmodified lines
modified:test/ipc/graceful.js+4 added-4 removed
87 unmodified lines
8889test('Graceful cancelSignal cannot be manually aborted after disconnection', async t => {90 const controller = new AbortController();91 const subprocess = execa('empty.js', {cancelSignal: controller.signal, gracefulCancel: true});92 subprocess.disconnect();92 subprocess.nodeChildProcess.disconnect();93 controller.abort(foobarString);94 const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, ipcOutput, originalMessage} = await t.throwsAsync(subprocess);95 t.false(isCanceled);96 t.false(isGracefullyCanceled);
7 unmodified lines
104 const controller = new AbortController();105 const subprocess = execa('graceful-disconnect.js', {cancelSignal: controller.signal, gracefulCancel: true});106 controller.abort(foobarString);107 t.is(await subprocess.getOneMessage(), foobarString);108 subprocess.disconnect();108 subprocess.nodeChildProcess.disconnect();109 const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, ipcOutput} = await t.throwsAsync(subprocess);110 t.true(isCanceled);111 t.true(isGracefullyCanceled);112 t.false(isTerminated);
4 unmodified lines
117test('Graceful cancelSignal is automatically aborted on disconnection', async t => {118 const controller = new AbortController();119 const subprocess = execa('graceful-send-print.js', {cancelSignal: controller.signal, gracefulCancel: true});120 t.false(await subprocess.getOneMessage());121 subprocess.disconnect();121 subprocess.nodeChildProcess.disconnect();122 const {isCanceled, isGracefullyCanceled, ipcOutput, stdout} = await subprocess;123 t.false(isCanceled);124 t.false(isGracefullyCanceled);125 t.deepEqual(ipcOutput, [false]);
2 unmodified lines
128129test('getCancelSignal() aborts if already disconnected', async t => {130 const controller = new AbortController();131 const subprocess = execa('graceful-print.js', {cancelSignal: controller.signal, gracefulCancel: true});132 subprocess.disconnect();132 subprocess.nodeChildProcess.disconnect();133 const {isCanceled, isGracefullyCanceled, ipcOutput, stdout} = await subprocess;134 t.false(isCanceled);135 t.false(isGracefullyCanceled);136 t.deepEqual(ipcOutput, []);
80 unmodified lines
modified:test/ipc/outgoing.js+2 added-2 removed
15 unmodified lines
16 const messages = Array.from({length: PARALLEL_COUNT}, (_, index) => index + 1);17 await Promise.all([18 ...messages.map(message => subprocess.sendMessage(message)),19 subprocess.sendMessage(foobarString),20 subprocess.emit('message', '.'),20 subprocess.nodeChildProcess.emit('message', '.'),21 ]);22 t.is(await getMessage(subprocess, {filter}), '.');2324 const {ipcOutput} = await subprocess;
26 unmodified lines
51 await subprocess.sendMessage(0);52 t.is(await subprocess.getOneMessage({filter}), 0);5354 const promise = subprocess.sendMessage(1);55 subprocess.emit('message', '.');55 subprocess.nodeChildProcess.emit('message', '.');56 await promise;5758 const messages = Array.from({length: PARALLEL_COUNT}, (_, index) => index + 2);59 for (const message of messages) {
29 unmodified lines
modified:test/ipc/reference.js+5 added-5 removed
78 unmodified lines
7980test('process.once("disconnect") keeps the subprocess alive', async t => {81 const subprocess = execa('ipc-once-disconnect.js', {ipc: true});82 t.is(await subprocess.getOneMessage(), '.');83 subprocess.disconnect();83 subprocess.nodeChildProcess.disconnect();8485 const {ipcOutput, stdout} = await subprocess;86 t.deepEqual(ipcOutput, ['.']);87 t.is(stdout, '.');
2 unmodified lines
90test('process.once("disconnect") keeps the subprocess alive, after sendMessage()', async t => {91 const subprocess = execa('ipc-once-disconnect-send.js', {ipc: true});92 t.is(await subprocess.getOneMessage(), '.');93 t.is(await subprocess.getOneMessage(), '.');94 subprocess.disconnect();94 subprocess.nodeChildProcess.disconnect();9596 const {ipcOutput, stdout} = await subprocess;97 t.deepEqual(ipcOutput, ['.', '.']);98 t.is(stdout, '.');
2 unmodified lines
101test('process.once("disconnect") does not keep the subprocess alive, after getOneMessage()', async t => {102 const subprocess = execa('ipc-once-disconnect-get.js', {ipc: true});103 await subprocess.sendMessage('.');104 t.is(await subprocess.getOneMessage(), '.');105 subprocess.disconnect();105 subprocess.nodeChildProcess.disconnect();106107 const {ipcOutput, stdout} = await subprocess;108 t.deepEqual(ipcOutput, ['.']);109 t.is(stdout, '.');110});111112test('Can call subprocess.disconnect() right away', async t => {113 const subprocess = execa('ipc-send.js', {ipc: true});114 subprocess.disconnect();115 t.is(subprocess.channel, null);114 subprocess.nodeChildProcess.disconnect();115 t.is(subprocess.nodeChildProcess.channel, null);116117 await t.throwsAsync(subprocess.getOneMessage(), {118 message: /subprocess.getOneMessage\(\) could not complete/,119 });
10 unmodified lines
modified:test/ipc/send.js+2 added-2 removed
48 unmodified lines
4950test('Handles backpressure', async t => {51 const subprocess = execa('ipc-iterate.js', {ipc: true});52 await subprocess.sendMessage(BIG_PAYLOAD_SIZE);53 t.true(subprocess.send(foobarString));53 t.true(subprocess.nodeChildProcess.send(foobarString));54 t.is(await subprocess.getOneMessage(), BIG_PAYLOAD_SIZE);55 const {ipcOutput} = await subprocess;56 t.deepEqual(ipcOutput, [BIG_PAYLOAD_SIZE]);57});
65 unmodified lines
123test('Does not hold message events on I/O errors', async t => {124 const subprocess = execa('ipc-echo.js', {ipc: true});125 const error = mockSendIoError(subprocess);126 const promise = subprocess.sendMessage('.');127 subprocess.emit('message', '.');127 subprocess.nodeChildProcess.emit('message', '.');128 t.is(await t.throwsAsync(promise), error);129130 const {exitCode, isTerminated, message, ipcOutput} = await t.throwsAsync(subprocess);131 t.is(exitCode, 1);
12 unmodified lines
modified:test/ipc/strict.js+1 added-1 removed
111 unmodified lines
112});113114test('exports.sendMessage() "strict" fails if the current process uses once() and buffer false', async t => {115 const subprocess = execa('ipc-send-strict.js', {ipc: true, buffer: {ipc: false}});116 const [message] = await once(subprocess, 'message');116 const [message] = await once(subprocess.nodeChildProcess, 'message');117 t.deepEqual(message, {118 id: 0n,119 type: 'execa:ipc:request',120 message: foobarString,
109 unmodified lines
modified:test/ipc/validation.js+1 added-1 removed
42 unmodified lines
43test('subprocess.getEachMessage() after disconnection', testPostDisconnection, 'getEachMessage');4445const testPostDisconnectionSubprocess = async (t, methodName) => {46 const subprocess = execa('ipc-disconnect.js', [methodName], {ipc: true});47 subprocess.disconnect();47 subprocess.nodeChildProcess.disconnect();48 const {message} = await t.throwsAsync(subprocess);49 t.true(message.includes(`${methodName}() cannot be used`));50};51
43 unmodified lines
modified:test/methods/main-async.js+36 added
1import process from 'node:process';2import {ChildProcess} from 'node:child_process';3import test from 'ava';4import {execa} from '../../index.js';5import {setFixtureDirectory, FIXTURES_DIRECTORY} from '../helpers/fixtures-directory.js';6
34 unmodified lines
41 const subprocess = execa('noop.js', ['foo']);42 t.is(typeof subprocess.pid, 'number');43 await subprocess;44});4546test('execa() returns a promise with nodeChildProcess', async t => {47 const subprocess = execa('noop.js', ['foo']);48 t.true(subprocess instanceof Promise);49 t.false(subprocess instanceof ChildProcess);50 t.true(subprocess.nodeChildProcess instanceof ChildProcess);51 t.is(subprocess.pid, subprocess.nodeChildProcess.pid);52 t.is(subprocess.stdout, subprocess.nodeChildProcess.stdout);53 t.is(subprocess.on, undefined);54 t.is(subprocess.once, undefined);55 t.is(subprocess.send, undefined);56 t.is(subprocess.ref, undefined);57 t.is(subprocess.unref, undefined);58 t.is(subprocess.disconnect, undefined);59 t.is(subprocess.channel, undefined);60 t.is(subprocess.connected, undefined);61 t.is(subprocess.exitCode, undefined);62 t.is(subprocess.signalCode, undefined);63 t.is(subprocess.killed, undefined);64 t.is(subprocess.spawnargs, undefined);65 t.is(subprocess.spawnfile, undefined);66 t.is(subprocess[Symbol.dispose], undefined);67 await subprocess;68});6970test('nodeChildProcess does not include Execa-specific APIs', async t => {71 const subprocess = execa('noop.js', ['foo'], {all: true});72 t.false(Object.hasOwn(subprocess.nodeChildProcess, 'all'));73 t.is(subprocess.nodeChildProcess.readable, undefined);74 t.is(subprocess.nodeChildProcess.writable, undefined);75 t.is(subprocess.nodeChildProcess.duplex, undefined);76 t.is(subprocess.nodeChildProcess.iterable, undefined);77 t.is(subprocess.nodeChildProcess[Symbol.asyncIterator], undefined);78 await subprocess;79});
modified:test/methods/promise.js+2 added-4 removed
2 unmodified lines
3import {setFixtureDirectory} from '../helpers/fixtures-directory.js';45setFixtureDirectory();67test('promise methods are not enumerable', t => {7test('subprocess properties are enumerable', t => {8 const descriptors = Object.getOwnPropertyDescriptors(execa('noop.js'));9 t.false(descriptors.then.enumerable);10 t.false(descriptors.catch.enumerable);11 t.false(descriptors.finally.enumerable);9 t.true(descriptors.nodeChildProcess.enumerable);10});1112test('finally function is executed on success', async t => {13 let isCalled = false;
38 unmodified lines
modified:test/pipe/sequence.js+2 added-2 removed
283 unmodified lines
284 const destination = execa('stdin.js');285 const pipePromise = source.pipe(destination);286287 const sourceCause = new Error(foobarString);288 source.emit('error', sourceCause);288 source.nodeChildProcess.emit('error', sourceCause);289 const destinationCause = new Error('other');290 destination.emit('error', destinationCause);290 destination.nodeChildProcess.emit('error', destinationCause);291292 t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(destination));293 t.like(await t.throwsAsync(source), {cause: {originalMessage: sourceCause.originalMessage}});294 t.like(await t.throwsAsync(destination), {cause: {originalMessage: destinationCause.originalMessage}});
87 unmodified lines
modified:test/resolve/wait-subprocess.js+2 added-2 removed
17 unmodified lines
18test('stdio[*] is undefined if ignored - sync', testIgnore, 3, execaSync);1920const testSubprocessEventsCleanup = async (t, fixtureName) => {21 const subprocess = execa(fixtureName, {reject: false});22 t.deepEqual(subprocess.eventNames().map(String).sort(), ['error', 'exit', 'spawn']);22 t.deepEqual(subprocess.nodeChildProcess.eventNames().map(String).sort(), ['error', 'exit', 'spawn']);23 await subprocess;24 t.deepEqual(subprocess.eventNames(), []);24 t.deepEqual(subprocess.nodeChildProcess.eventNames(), []);25};2627test('subprocess listeners are cleaned up on success', testSubprocessEventsCleanup, 'empty.js');28test('subprocess listeners are cleaned up on failure', testSubprocessEventsCleanup, 'fail.js');
21 unmodified lines
modified:test/return/early-error.js+36 added-2 removed
25 unmodified lines
26const testEarlyErrorShape = async (t, reject) => {27 const subprocess = getEarlyErrorSubprocess({reject});28 t.notThrows(() => {29 subprocess.catch(() => {});30 subprocess.unref();31 subprocess.on('error', () => {});30 subprocess.nodeChildProcess.unref();31 subprocess.nodeChildProcess.on('error', () => {});32 });33};3435test('child_process.spawn() early errors have correct shape', testEarlyErrorShape, true);
76 unmodified lines
112test('child_process.spawn() early errors can use .readableStream()', testEarlyErrorWebConvertor, 'readableStream');113test('child_process.spawn() early errors can use .writableStream()', testEarlyErrorWebConvertor, 'writableStream');114test('child_process.spawn() early errors can use .transformStream()', testEarlyErrorWebConvertor, 'transformStream');115116const testEarlyErrorIpc = async (t, runIpcMethod) => {117 const subprocess = getEarlyErrorSubprocess({ipc: true});118 t.throws(() => {119 runIpcMethod(subprocess);120 }, {message: /cannot be used: the subprocess has already exited or disconnected/});121 await t.throwsAsync(subprocess, expectedEarlyError);122};123124test('child_process.spawn() early errors can use .sendMessage()', testEarlyErrorIpc, subprocess => subprocess.sendMessage('.'));125test('child_process.spawn() early errors can use .getOneMessage()', testEarlyErrorIpc, subprocess => subprocess.getOneMessage());126test('child_process.spawn() early errors can use .getEachMessage()', testEarlyErrorIpc, subprocess => subprocess.getEachMessage());127128test('child_process.spawn() early errors can use .iterable()', async t => {129 const subprocess = getEarlyErrorSubprocess();130 const lines = [];131 for await (const line of subprocess.iterable()) {132 lines.push(line);133 }134135 t.deepEqual(lines, []);136 await t.throwsAsync(subprocess);137});138139test('child_process.spawn() early errors can use Symbol.asyncIterator', async t => {140 const subprocess = getEarlyErrorSubprocess();141 const lines = [];142 for await (const line of subprocess) {143 lines.push(line);144 }145146 t.deepEqual(lines, []);147 await t.throwsAsync(subprocess);148});149150const testEarlyErrorStream = async (t, getStreamProperty, options) => {151 const subprocess = getEarlyErrorSubprocess(options);152 const stream = getStreamProperty(subprocess);153 stream.on('close', () => {});
11 unmodified lines
modified:test/return/final-error.js+4 added-4 removed
11 unmodified lines
12setFixtureDirectory();1314const testUnusualError = async (t, error, expectedOriginalMessage = String(error)) => {15 const subprocess = execa('empty.js');16 subprocess.emit('error', error);16 subprocess.nodeChildProcess.emit('error', error);17 const {originalMessage, shortMessage, message} = await t.throwsAsync(subprocess);18 t.is(originalMessage, expectedOriginalMessage === '' ? undefined : expectedOriginalMessage);19 t.true(shortMessage.includes(expectedOriginalMessage));20 t.is(message, shortMessage);
12 unmodified lines
33test('error instance can be undefined', testUnusualError, undefined, 'undefined');3435test('error instance can be a plain object', async t => {36 const subprocess = execa('empty.js');37 subprocess.emit('error', {message: foobarString});37 subprocess.nodeChildProcess.emit('error', {message: foobarString});38 await t.throwsAsync(subprocess, {message: new RegExp(foobarString)});39});4041const runAndFail = (t, fixtureName, argument, error) => {42 const subprocess = execa(fixtureName, [argument]);43 subprocess.emit('error', error);43 subprocess.nodeChildProcess.emit('error', error);44 return t.throwsAsync(subprocess);45};4647const testErrorCopy = async (t, getPreviousArgument, argument = 'two') => {
42 unmodified lines
9091test('error.cause is set on error event', async t => {92 const subprocess = execa('empty.js');93 const error = new Error(foobarString);94 subprocess.emit('error', error);94 subprocess.nodeChildProcess.emit('error', error);95 const {cause} = await t.throwsAsync(subprocess);96 t.is(cause, error);97});98
66 unmodified lines
modified:test/return/result.js+1 added-1 removed
112 unmodified lines
113114test('result.isTerminated is false if not killed and subprocess.kill() was called', async t => {115 const subprocess = execa('noop.js');116 subprocess.kill(0);117 t.true(subprocess.killed);117 t.true(subprocess.nodeChildProcess.killed);118 const {isTerminated} = await subprocess;119 t.false(isTerminated);120});121
26 unmodified lines
modified:test/terminate/cancel.js+2 added-2 removed
67 unmodified lines
6869test('calling abort is considered a signal termination', async t => {70 const abortController = new AbortController();71 const subprocess = execa('forever.js', {cancelSignal: abortController.signal});72 await once(subprocess, 'spawn');72 await once(subprocess.nodeChildProcess, 'spawn');73 abortController.abort();74 const {isCanceled, isGracefullyCanceled, isTerminated, signal} = await t.throwsAsync(subprocess);75 t.true(isCanceled);76 t.false(isGracefullyCanceled);
14 unmodified lines
91test('calling abort does not emit the "error" event', async t => {92 const abortController = new AbortController();93 const subprocess = execa('forever.js', {cancelSignal: abortController.signal});94 let error;95 subprocess.once('error', errorArgument => {95 subprocess.nodeChildProcess.once('error', errorArgument => {96 error = errorArgument;97 });98 abortController.abort();99 const {isCanceled, isGracefullyCanceled} = await t.throwsAsync(subprocess);
110 unmodified lines
modified:test/terminate/cleanup.js+19 added
71 unmodified lines
72test('spawnAndKill detached SIGKILL', spawnAndKill, ['SIGKILL', false, true, false]);73test('spawnAndKill cleanup detached SIGTERM', spawnAndKill, ['SIGTERM', true, true, false]);74test('spawnAndKill cleanup detached SIGKILL', spawnAndKill, ['SIGKILL', true, true, false]);7576if (!isWindows) {77 test('spawnAndKill cleanup uses killSignal', async t => {78 const subprocess = execa('ipc-send-pid.js', ['true', 'false', 'no-killable'], {stdio: 'ignore', ipc: true});7980 const pid = await subprocess.getOneMessage();81 t.true(Number.isInteger(pid));82 t.true(isRunning(pid));8384 process.kill(subprocess.pid, 'SIGTERM');8586 await t.throwsAsync(subprocess);87 await Promise.race([88 setTimeout(1e4, undefined, {ref: false}),89 pollForSubprocessExit(pid),90 ]);91 t.false(isRunning(pid));92 });93}9495// See #12896test('removes exit handler on exit', async t => {97 // @todo this relies on `signal-exit` internals98 const exitListeners = globalThis[Symbol.for('signal-exit emitter')].listeners.exit;
22 unmodified lines
modified:test/terminate/graceful.js+2 added-2 removed
45 unmodified lines
46 const subprocess = execa('ipc-echo.js', {cancelSignal: controller.signal, gracefulCancel: true, forceKillAfterDelay: false});47 const error = mockSendIoError(subprocess);48 controller.abort(foobarString);49 await setTimeout(0);50 t.true(subprocess.connected);50 t.true(subprocess.nodeChildProcess.connected);51 subprocess.kill();52 const {isCanceled, isGracefullyCanceled, signal, ipcOutput, cause} = await t.throwsAsync(subprocess);53 t.false(isCanceled);54 t.false(isGracefullyCanceled);
41 unmodified lines
96 const controller = new AbortController();97 const subprocess = execa('ipc-echo.js', {cancelSignal: controller.signal, gracefulCancel: true, forceKillAfterDelay: false});98 controller.abort(() => {});99 await setTimeout(0);100 t.true(subprocess.connected);100 t.true(subprocess.nodeChildProcess.connected);101 await subprocess.sendMessage(foobarString);102 const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, cause, ipcOutput} = await t.throwsAsync(subprocess);103 t.false(isCanceled);104 t.false(isGracefullyCanceled);
74 unmodified lines
modified:test/terminate/kill-error.js+1 added-1 removed
76 unmodified lines
77test('.kill(error) does not emit the "error" event', async t => {78 const subprocess = execa('forever.js');79 const cause = new Error('test');80 subprocess.kill(cause);81 const error = await Promise.race([t.throwsAsync(subprocess), once(subprocess, 'error')]);81 const error = await Promise.race([t.throwsAsync(subprocess), once(subprocess.nodeChildProcess, 'error')]);82 t.is(error.cause, cause);83});
modified:test/terminate/kill-force.js+3 added-3 removed
109 unmodified lines
110111 test('`forceKillAfterDelay` works with the "cancelSignal" option', async t => {112 const abortController = new AbortController();113 const subprocess = spawnNoKillableSimple({cancelSignal: abortController.signal});114 await once(subprocess, 'spawn');114 await once(subprocess.nodeChildProcess, 'spawn');115 abortController.abort('');116 const {isTerminated, signal, isCanceled, isGracefullyCanceled, isForcefullyTerminated, shortMessage} = await t.throwsAsync(subprocess);117 t.true(isTerminated);118 t.is(signal, 'SIGKILL');
25 unmodified lines
144 });145146 test('`forceKillAfterDelay` works with the "error" event', async t => {147 const subprocess = spawnNoKillableSimple();148 await once(subprocess, 'spawn');148 await once(subprocess.nodeChildProcess, 'spawn');149 const error = new Error(foobarString);150 error.code = 'ECODE';151 subprocess.emit('error', error);151 subprocess.nodeChildProcess.emit('error', error);152 subprocess.kill();153 const {isTerminated, signal, isForcefullyTerminated, shortMessage, originalMessage, cause} = await t.throwsAsync(subprocess);154 t.true(isTerminated);155 t.is(signal, 'SIGKILL');
63 unmodified lines
modified:test/terminate/kill-signal.js+8 added-8 removed
87 unmodified lines
8889test('subprocess errors are handled before spawn', async t => {90 const subprocess = execa('forever.js');91 const cause = new Error('test');92 subprocess.emit('error', cause);92 subprocess.nodeChildProcess.emit('error', cause);93 subprocess.kill();94 const error = await t.throwsAsync(subprocess);95 t.is(error.cause, cause);96 t.is(error.exitCode, undefined);
2 unmodified lines
99});100101test('subprocess errors are handled after spawn', async t => {102 const subprocess = execa('forever.js');103 await once(subprocess, 'spawn');103 await once(subprocess.nodeChildProcess, 'spawn');104 const cause = new Error('test');105 subprocess.emit('error', cause);105 subprocess.nodeChildProcess.emit('error', cause);106 subprocess.kill();107 const error = await t.throwsAsync(subprocess);108 t.is(error.cause, cause);109 t.is(error.exitCode, undefined);
3 unmodified lines
113114test('subprocess double errors are handled after spawn', async t => {115 const abortController = new AbortController();116 const subprocess = execa('forever.js', {cancelSignal: abortController.signal});117 await once(subprocess, 'spawn');117 await once(subprocess.nodeChildProcess, 'spawn');118 const cause = new Error('test');119 subprocess.emit('error', cause);119 subprocess.nodeChildProcess.emit('error', cause);120 await setImmediate();121 abortController.abort();122 subprocess.emit('error', cause);122 subprocess.nodeChildProcess.emit('error', cause);123 const error = await t.throwsAsync(subprocess);124 t.is(error.cause, cause);125 t.is(error.exitCode, undefined);126 t.is(error.signal, 'SIGTERM');
1 unmodified line
128});129130test('subprocess errors use killSignal', async t => {131 const subprocess = execa('forever.js', {killSignal: 'SIGINT'});132 await once(subprocess, 'spawn');132 await once(subprocess.nodeChildProcess, 'spawn');133 const cause = new Error('test');134 subprocess.emit('error', cause);134 subprocess.nodeChildProcess.emit('error', cause);135 subprocess.kill();136 const error = await t.throwsAsync(subprocess);137 t.is(error.cause, cause);138 t.true(error.isTerminated);
2 unmodified lines
modified:test/terminate/timeout.js+1 added-1 removed
67 unmodified lines
6869test('timedOut is false if the timeout happened after a different error occurred', async t => {70 const subprocess = execa('forever.js', {timeout: 1e3});71 const cause = new Error('test');72 subprocess.emit('error', cause);72 subprocess.nodeChildProcess.emit('error', cause);73 const error = await t.throwsAsync(subprocess);74 t.is(error.cause, cause);75 t.false(error.timedOut);76});
modified:test-d/subprocess/subprocess.test-d.ts+30 added-2 removed
1import type {ChildProcess} from 'node:child_process';2import {expectType, expectError, expectAssignable} from 'tsd';2import {execa, type Subprocess} from '../../index.js';3import {execa, type Result, type Subprocess} from '../../index.js';45const subprocess = execa('unicorns');6expectAssignable<Subprocess>(subprocess);7expectType<Result<{}>>(await subprocess);89expectType<number | undefined>(subprocess.pid);10expectType<ChildProcess>(subprocess.nodeChildProcess);11subprocess.nodeChildProcess.on('exit', () => undefined);12subprocess.nodeChildProcess.once('exit', () => undefined);13subprocess.nodeChildProcess.ref();14subprocess.nodeChildProcess.unref();15subprocess.nodeChildProcess.send('message');16subprocess.nodeChildProcess.disconnect();17expectType<boolean>(subprocess.nodeChildProcess.connected);18expectType<number | null>(subprocess.nodeChildProcess.exitCode);19expectType<NodeJS.Signals | null>(subprocess.nodeChildProcess.signalCode);20expectType<boolean>(subprocess.nodeChildProcess.killed);21expectType<string[]>(subprocess.nodeChildProcess.spawnargs);22expectType<string>(subprocess.nodeChildProcess.spawnfile);23expectError(subprocess.on('exit', () => undefined));24expectError(subprocess.once('exit', () => undefined));25expectError(subprocess.ref());26expectError(subprocess.unref());27expectError(subprocess.send('message'));28expectError(subprocess.disconnect());29expectError(subprocess.connected);30expectError(subprocess.channel);31expectError(subprocess.exitCode);32expectError(subprocess.signalCode);33expectError(subprocess.killed);34expectError(subprocess.spawnargs);35expectError(subprocess.spawnfile);3637expectType<boolean>(subprocess.kill());38subprocess.kill('SIGKILL');39subprocess.kill(undefined);
14 unmodified lines
54expectError(subprocess.kill('SIGKILL', {}));55expectError(subprocess.kill(null, new Error('test')));5657const ipcSubprocess = execa('unicorns', {ipc: true});30expectAssignable<Subprocess>(subprocess);58expectAssignable<Subprocess>(ipcSubprocess);
modified:types/subprocess/subprocess.d.ts+12 added-6 removed
119 unmodified lines
120 /**121 Converts the subprocess to a [`{readable, writable}`](https://developer.mozilla.org/en-US/docs/Web/API/TransformStream) pair of web streams.122 */123 transformStream(duplexOptions?: DuplexOptions): ReadableWritablePair;124125 /**126 Underlying Node.js [`ChildProcess`](https://nodejs.org/api/child_process.html#class-childprocess) instance.127128 This is an escape hatch for Node.js-specific APIs not documented by Execa, such as `.on()`, `.send()`, `.disconnect()`, `.ref()` or `.unref()`.129 */130 nodeChildProcess: ChildProcess;131 };132133/**127[`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess) with additional methods and properties.134Subprocess with Execa-specific methods and properties. It is also a `Promise` either resolving with its successful `result`, or rejecting with its `error`.135*/136export type Subprocess<OptionsType extends Options = Options> =130 & Omit<ChildProcess, keyof ExecaCustomSubprocess<OptionsType>>131 & ExecaCustomSubprocess<OptionsType>;137 & ExecaCustomSubprocess<OptionsType>138 & Promise<Result<OptionsType>>;139140/**141The return value of all asynchronous methods is both:135- the subprocess.142- the subprocess with Execa-specific methods and properties.143- a `Promise` either resolving with its successful `result`, or rejecting with its `error`.144*/145export type ResultPromise<OptionsType extends Options = Options> =139 & Subprocess<OptionsType>140 & Promise<Result<OptionsType>>;146 Subprocess<OptionsType>;147148export {};