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
Provenance
- Commit
ade74bf- Tree
eeb3e4b- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
29d9cfc
47 files changed+389 added−155 removed
modified:docs/api.md+12 added-2 removed
209 unmodified lines210 211 ## Return value212 213 _TypeScript:_ [`ResultPromise`](typescript.md)\214-_Type:_ `Promise<object> | Subprocess`214+_Type:_ `Subprocess`215 216 The 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 lines222 ## Subprocess223 224 _TypeScript:_ [`Subprocess`](typescript.md)225 226-[`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess) with the following methods and properties.226+Promise with the following Execa-specific methods and properties.227 228+The 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()`.229+230 ### subprocess\[Symbol.asyncIterator\]()231 232 _Returns_: [`AsyncIterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols)233 102 unmodified lines336 This is `undefined` if the subprocess failed to spawn.337 338 [More info.](termination.md#inter-process-termination)339 340+### subprocess.nodeChildProcess341+342+_Type:_ [`ChildProcess`](https://nodejs.org/api/child_process.html#class-childprocess)343+344+Underlying Node.js child process instance.345+346+This is intended as an escape hatch for Node.js-specific APIs that Execa does not document.347+348 ### subprocess.sendMessage(message, sendMessageOptions)349 350 `message`: [`Message`](ipc.md#message-type)\351 `sendMessageOptions`: [`SendMessageOptions`](#sendmessageoptions)\995 unmodified linesmodified:docs/execution.md+2 added-2 removed
125 unmodified linesExpand all12612712812913013013113213313413513613713813913914014114214326 unmodified lines125 unmodified linesExpand all## Return value
### Subprocess
The subprocess is returned as soon as it is spawned. It is a [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess) with [additional methods and properties](api.md#subprocess).The subprocess is returned as soon as it is spawned. It is a `Promise` with [Execa-specific methods and properties](api.md#subprocess). The underlying Node.js [`ChildProcess`](https://nodejs.org/api/child_process.html#class-childprocess) is available as [`subprocess.nodeChildProcess`](api.md#subprocessnodechildprocess).
```jsconst subprocess = execa`npm run build`;console.log(subprocess.pid);```
### Result
The subprocess is also a `Promise` that resolves with the [`result`](api.md#result).The subprocess resolves with the [`result`](api.md#result).
```jsconst {stdout} = await execa`npm run build`;```26 unmodified linesmodified:lib/convert/duplex.js+1 added-1 removed
50 unmodified lines51 readable: duplex,52 subprocess,53 subprocessStdin,54 });55- onStdinFinished(subprocessStdin, duplex, subprocessStdout);55+ onStdinFinished(subprocessStdin, duplex, subprocessStdout, subprocess);56 return duplex;57 };58 59 const onDuplexDestroy = async ({subprocessStdout, subprocessStdin, subprocess, waitReadableDestroy, waitWritableFinal, waitWritableDestroy}, error) => {10 unmodified linesmodified:lib/convert/readable.js+15 added-1 removed
94 unmodified lines95 readable.push(null);96 }97 } catch (error) {98 await safeWaitForSubprocessStdin(subprocessStdin);99- destroyOtherReadable(readable, error);99+ destroyOtherReadable(readable, await getPrematureCloseError(subprocess, error));100 }101 };102 103+const getPrematureCloseError = async (subprocess, error) => {104+ if (error.code !== 'ERR_STREAM_PREMATURE_CLOSE') {105+ return error;106+ }107+108+ try {109+ await subprocess;110+ } catch (subprocessError) {111+ return subprocessError;112+ }113+114+ return error;115+};116+117 // When `readable` aborts/errors, do the same on `subprocess.stdout`118 export const onReadableDestroy = async ({subprocessStdout, subprocess, waitReadableDestroy}, error) => {119 if (!await waitForConcurrentStreams(waitReadableDestroy, subprocess)) {120 return;9 unmodified linesmodified:lib/convert/writable.js+22 added-3 removed
1 import {Writable} from 'node:stream';2 import {callbackify} from 'node:util';3 import {getToStream} from '../arguments/fd-options.js';4+import {isStreamAbort} from '../resolve/wait-stream.js';5 import {addConcurrentStream, waitForConcurrentStreams} from './concurrent.js';6 import {7 safeWaitForSubprocessStdout,8 waitForSubprocessStdin,14 unmodified lines23 })),24 highWaterMark: subprocessStdin.writableHighWaterMark,25 objectMode: subprocessStdin.writableObjectMode,26 });26- onStdinFinished(subprocessStdin, writable);27+ onStdinFinished(subprocessStdin, writable, undefined, subprocess);28 return writable;29 };30 31 // Retrieve `stdin` (or other stream depending on `to`)34 unmodified lines66 await subprocess;67 };68 69 // When `subprocess.stdin` ends/aborts/errors, do the same on `writable`.69-export const onStdinFinished = async (subprocessStdin, writable, subprocessStdout) => {70+export 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 };82 83+const getSubprocessError = async (subprocess, error) => {84+ if (!shouldUseSubprocessError(error)) {85+ return error;86+ }87+88+ try {89+ await subprocess;90+ } catch (subprocessError) {91+ return subprocessError;92+ }93+94+ return error;95+};96+97+const shouldUseSubprocessError = error => error === undefined98+ || isStreamAbort(error);99+100 // When `writable` aborts/errors, do the same on `subprocess.stdin`101 export const onWritableDestroy = async ({subprocessStdin, subprocess, waitWritableFinal, waitWritableDestroy}, error) => {102 await waitForConcurrentStreams(waitWritableFinal, subprocess);103 if (await waitForConcurrentStreams(waitWritableDestroy, subprocess)) {8 unmodified linesmodified:lib/ipc/forward.js+1 added-1 removed
49 unmodified lines50 // Check whether there might still be some `message` events to receive51 export 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 lines19 });20 };21 22 // Same but used internally23-export const loopOnMessages = ({anyProcess, channel, isSubprocess, ipc, shouldAwait, reference, signal}) => {23+export const loopOnMessages = ({anyProcess, waitProcess = anyProcess, channel, isSubprocess, ipc, shouldAwait, reference, signal}) => {24 validateIpcMethod({25 methodName: 'getEachMessage',26 isSubprocess,27 ipc,13 unmodified lines41 state,42 });43 return iterateOnMessages({44 anyProcess,45+ waitProcess,46 channel,47 ipcEmitter,48 isSubprocess,49 shouldAwait,33 unmodified lines83 controller.abort();84 } catch {}85 };86 86-const iterateOnMessages = async function * ({anyProcess, channel, ipcEmitter, isSubprocess, shouldAwait, controller, state, reference}) {87+const 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 lines100 disconnect(anyProcess);101 }102 103 if (shouldAwait) {103- await anyProcess;104+ await waitProcess;105 }106 }107 };108 5 unmodified linesmodified:lib/ipc/ipc-input.js+8 added-2 removed
1 import {serialize} from 'node:v8';2+import {sendMessage} from './send.js';3 4 // Validate the `ipcInput` option5 export const validateIpcInputOption = ({ipcInput, ipc, serialization}) => {6 if (ipcInput === undefined) {28 unmodified lines35 json: validateJsonInput,36 };37 38 // When the `ipcInput` option is set, it is sent as an initial IPC message to the subprocess38-export const sendIpcInput = async (subprocess, ipcInput) => {39+export const sendIpcInput = async (subprocess, ipcInput, ipc) => {40 if (ipcInput === undefined) {41 return;42 }43 43- 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 lines4 import {getEachMessage} from './get-each.js';5 import {getCancelSignal} from './graceful.js';6 7 // Add promise-based IPC methods in current process8-export const addIpcMethods = (subprocess, {ipc}) => {9- Object.assign(subprocess, getIpcMethods(subprocess, false, ipc));8+export const addIpcMethods = (target, subprocess, {ipc}) => {9+ Object.assign(target, getIpcMethods(subprocess, false, ipc, target));10 };11 12 // Get promise-based IPC in the subprocess13 export const getIpcExport = () => {12 unmodified lines26 };27 };28 29 // Retrieve the `ipc` shared by both the current process and the subprocess30-const getIpcMethods = (anyProcess, isSubprocess, ipc) => ({30+const getIpcMethods = (anyProcess, isSubprocess, ipc, waitProcess = anyProcess) => ({31 sendMessage: sendMessage.bind(undefined, {32 anyProcess,33 channel: anyProcess.channel,34 isSubprocess,9 unmodified lines44 anyProcess,45 channel: anyProcess.channel,46 isSubprocess,47 ipc,48+ waitProcess,49 }),50 });modified:lib/ipc/outgoing.js+9 added-3 removed
1 import {createDeferred} from '../utils/deferred.js';2 import {getFdSpecificValue} from '../arguments/specific.js';3-import {SUBPROCESS_OPTIONS} from '../arguments/fd-options.js';3 import {validateStrictDeadlock} from './strict.js';4 5 // 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 lines33 }34 };35 36 const OUTGOING_MESSAGES = new WeakMap();37+const IPC_SUBPROCESS_OPTIONS = new WeakMap();38 39+export const setIpcSubprocessOptions = (subprocess, options) => {40+ IPC_SUBPROCESS_OPTIONS.set(subprocess, options);41+};42+43 // Whether any `message` listener is setup44 export const hasMessageListeners = (anyProcess, ipcEmitter) => ipcEmitter.listenerCount('message') > getMinListenerCount(anyProcess);45 46 // 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.44-const getMinListenerCount = anyProcess => SUBPROCESS_OPTIONS.has(anyProcess)45- && !getFdSpecificValue(SUBPROCESS_OPTIONS.get(anyProcess).options.buffer, 'ipc')48+const getMinListenerCount = anyProcess => getOptions(anyProcess) !== undefined49+ && !getFdSpecificValue(getOptions(anyProcess).buffer, 'ipc')50 ? 151 : 0;52+53+const getOptions = anyProcess => IPC_SUBPROCESS_OPTIONS.get(anyProcess);modified:lib/methods/main-async.js+49 added-9 removed
4 unmodified lines5 import {normalizeOptions} from '../arguments/options.js';6 import {SUBPROCESS_OPTIONS} from '../arguments/fd-options.js';7 import {concatenateShell} from '../arguments/shell.js';8 import {addIpcMethods} from '../ipc/methods.js';9+import {setIpcSubprocessOptions} from '../ipc/outgoing.js';10 import {makeError, makeSuccessResult} from '../return/result.js';11 import {handleResult} from '../return/reject.js';12 import {handleEarlyError} from '../return/early-error.js';13 import {handleStdioAsync} from '../stdio/handle-async.js';10 unmodified lines24 25 // Main shared logic for all async methods: `execa()`, `$`, `execaNode()`26 export 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 line34 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 lines101 setMaxListeners(Infinity, controller.signal);102 103 const originalStreams = [...subprocess.stdio];104 pipeOutputAsync(subprocess, fileDescriptors, controller);97- cleanupOnExit(subprocess, options, controller);105+ setIpcSubprocessOptions(subprocess, options);106 107 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);118 119 const promise = handlePromise({120 subprocess,121+ kill,122+ all,123 options,124 startTime,125 verboseInfo,126 fileDescriptors,3 unmodified lines130 context,131 onInternalError,132 controller,133 });125- return {subprocess, promise};134+ return {135+ subprocess,136+ promise,137+ kill,138+ all,139+ };140 };141 142+const 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+ }150+151+ addIpcMethods(subprocess, nodeChildProcess, options);152+ return subprocess;153+};154+155+const 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+});165+166 // Asynchronous logic, as opposed to the previous logic which can be run synchronously, i.e. can be returned to user right away129-const handlePromise = async ({subprocess, options, startTime, verboseInfo, fileDescriptors, originalStreams, command, escapedCommand, context, onInternalError, controller}) => {167+const 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 linesmodified:lib/methods/promise.js+2 added-15 removed
1-// The return value is a mixin of `subprocess` and `Promise`2-export 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-};8-9-// eslint-disable-next-line unicorn/prefer-top-level-await10-const nativePromisePrototype = (async () => {})().constructor.prototype;11-12-const 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.2+export const mergePromise = (promise, properties) => Object.assign(promise, properties);modified:lib/resolve/all-async.js+5 added-5 removed
5 unmodified lines6 ? mergeStreams([stdout, stderr].filter(Boolean))7 : undefined;8 9 // Read the contents of `subprocess.all` and|or wait for its completion10-export const waitForAllStream = ({subprocess, encoding, buffer, maxBuffer, lines, stripFinalNewline, verboseInfo, streamInfo}) => waitForSubprocessStream({11- ...getAllStream(subprocess, buffer),10+export 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 });21 22-const getAllStream = ({stdout, stderr, all}, [, bufferStdout, bufferStderr]) => {22+const getAllStream = ({stdout, stderr}, all, [, bufferStdout, bufferStderr]) => {23 const buffer = bufferStdout || bufferStderr;24 if (!buffer) {25 return {stream: all, buffer};26 }12 unmodified lines39 // 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.43-const getAllMixed = ({all, stdout, stderr}) => all43+const getAllMixed = ({stdout, stderr}, all) => all44 && stdout45 && stderr46 && stdout.readableObjectMode !== stderr.readableObjectMode;modified:lib/resolve/wait-subprocess.js+7 added-3 removed
14 unmodified lines15 16 // Retrieve result of subprocess: exit code, signal, error, streams (stdout/stderr/all)17 export const waitForSubprocessResult = async ({18 subprocess,19+ kill,20+ all,21 options: {22 encoding,23 buffer,24 maxBuffer,33 unmodified lines58 streamInfo,59 });60 const allPromise = waitForAllStream({61 subprocess,62+ all,63 encoding,64 buffer,65 maxBuffer,66 lines,20 unmodified lines87 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 linesmodified:lib/return/early-error.js+18 added-11 removed
13 unmodified lines14 export const handleEarlyError = ({error, command, escapedCommand, fileDescriptors, options, startTime, verboseInfo}) => {15 cleanupCustomStreams(fileDescriptors);16 17 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);19 20 const earlyError = makeEarlyError({21 error,22 command,3 unmodified lines26 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 };46 47 const createDummyStreams = (subprocess, fileDescriptors) => {48 const stdin = createDummyStream();5 unmodified lines54 Object.assign(subprocess, {55 stdin,56 stdout,57 stderr,52- all,58 stdio,59 });60+ return all;61 };62 63 const createDummyStream = () => {64 const stream = new PassThrough();6 unmodified lines71 const duplex = () => new Duplex({read() {}, write() {}});72 const readableStream = () => Readable.toWeb(readable());73 const writableStream = () => Writable.toWeb(writable());74 const transformStream = () => Duplex.toWeb(duplex());75+const iterable = async function * () {};76 77 const handleDummyPromise = async (error, verboseInfo, options) => handleResult(error, verboseInfo, options);modified:lib/terminate/cancel.js+4 added-4 removed
6 unmodified lines7 }8 };9 10 // Terminate the subprocess when aborting the `cancelSignal` option and `gracefulSignal` is `false`11-export const throwOnCancel = ({subprocess, cancelSignal, gracefulCancel, context, controller}) => cancelSignal === undefined || gracefulCancel11+export const throwOnCancel = ({kill, cancelSignal, gracefulCancel, context, controller}) => cancelSignal === undefined || gracefulCancel12 ? []13- : [terminateOnCancel(subprocess, cancelSignal, context, controller)];13+ : [terminateOnCancel(kill, cancelSignal, context, controller)];14 15-const terminateOnCancel = async (subprocess, cancelSignal, context, {signal}) => {15+const 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
1 import {addAbortListener} from 'node:events';2 import {onExit} from 'signal-exit';3 4 // If the `cleanup` option is used, call `subprocess.kill()` when the parent process exits5-export const cleanupOnExit = (subprocess, {cleanup, detached}, {signal}) => {5+export const cleanupOnExit = (kill, {cleanup, detached}, {signal}) => {6 if (!cleanup || detached) {7 return;8 }9 10 const removeExitHandler = onExit(() => {11- subprocess.kill();11+ kill();12 });13 addAbortListener(signal, () => {14 removeExitHandler();15 });1 unmodified linemodified:lib/terminate/graceful.js+4 added-2 removed
22 unmodified lines23 24 // Send abort reason to the subprocess when aborting the `cancelSignal` option and `gracefulCancel` is `true`25 export 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 : [];43 42-const sendOnAbort = async ({subprocess, cancelSignal, forceKillAfterDelay, context, controller: {signal}}) => {44+const 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 linesmodified:lib/terminate/timeout.js+4 added-4 removed
7 unmodified lines8 }9 };10 11 // Fails when the `timeout` option is exceeded12-export const throwOnTimeout = (subprocess, timeout, context, controller) => timeout === 0 || timeout === undefined12+export const throwOnTimeout = (kill, timeout, context, controller) => timeout === 0 || timeout === undefined13 ? []14- : [killAfterTimeout(subprocess, timeout, context, controller)];14+ : [killAfterTimeout(kill, timeout, context, controller)];15 16-const killAfterTimeout = async (subprocess, timeout, context, {signal}) => {16+const 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 lines180 subprocess.stdin.destroy();181 182 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 };192 193 test('subprocess.stdin abort -> .writable() error + subprocess fail', testStdinAbort, 'writable');194 test('subprocess.stdin abort -> .duplex() error + subprocess fail', testStdinAbort, 'duplex');205 unmodified linesmodified:test/fixtures/ipc-send-pid.js+14 added-1 removed
2 unmodified lines3 import {execa, sendMessage} from '../../index.js';4 5 const cleanup = process.argv[2] === 'true';6 const detached = process.argv[3] === 'true';7-const subprocess = execa('forever.js', {cleanup, detached});7+const file = process.argv[4] === 'no-killable' ? 'no-killable.js' : 'forever.js';8+const options = {9+ cleanup,10+ detached,11+ ...(file === 'no-killable.js' && {12+ ipc: true,13+ killSignal: 'SIGKILL',14+ }),15+};16+const subprocess = execa(file, options);17+if (options.ipc) {18+ await subprocess.getOneMessage();19+}20+21 await sendMessage(subprocess.pid);22 await subprocess;modified:test/helpers/ipc.js+2 added-1 removed
30 unmodified lines31 // However, I/O errors are seldom and hard to trigger predictably.32 // So we mock them.33 export 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 };39 40 return error;1 unmodified linemodified:test/ipc/forward.js+3 added-3 removed
9 unmodified lines10 const subprocess = execa('ipc-send.js', {ipc: true, buffer});11 12 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);16 17 const error = await t.throwsAsync(subprocess);18 t.is(error.exitCode, undefined);29 unmodified lines48 const subprocess = execa('ipc-send-twice.js', {ipc: true, buffer});49 50 const promise = iterateAllMessages(subprocess);51 const cause = new Error(foobarString);52- subprocess.emit('error', cause);52+ subprocess.nodeChildProcess.emit('error', cause);53 54 const error = await t.throwsAsync(subprocess);55 t.is(error, await t.throwsAsync(promise));56 t.is(error.exitCode, undefined);25 unmodified lines82 test('"error" event does not interrupt result.ipcOutput', async t => {83 const subprocess = execa('ipc-echo-twice.js', {ipcInput: foobarString});84 85 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 linesmodified:test/ipc/get-each.js+10 added-10 removed
141 unmodified lines142 test('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();147 148 const {stdout} = await subprocess;149 t.is(stdout, '.');150 });20 unmodified lines171 172 const testCleanupListeners = async (t, buffer) => {173 const subprocess = execa('ipc-send.js', {ipc: true, buffer});174 175- 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);177 178 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]);182 183- 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 };186 187 test('Cleans up subprocess.getEachMessage() listeners, buffer false', testCleanupListeners, false);188 test('Cleans up subprocess.getEachMessage() listeners, buffer true', testCleanupListeners, true);189 190 const 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 }195 196 // eslint-disable-next-line no-await-in-loop197 await scheduler.yield();3 unmodified lines201 test.serial('Handles buffered messages when disconnecting', async t => {202 const subprocess = execa('ipc-send-fail.js', {ipc: true, buffer: false});203 204 const promise = subprocess.getOneMessage();205- subprocess.emit('message', foobarString);205+ subprocess.nodeChildProcess.emit('message', foobarString);206 t.is(await promise, foobarString);207 sendContinuousMessages(subprocess);208 209 const {exitCode, isTerminated, ipcOutput} = await t.throwsAsync(iterateAllMessages(subprocess));4 unmodified linesmodified:test/ipc/get-one.js+7 added-7 removed
77 unmodified lines78 79 const testCleanupListeners = async (t, buffer, filter) => {80 const subprocess = execa('ipc-send.js', {ipc: true, buffer});81 82- 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);84 85 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);88 89 t.is(await promise, foobarString);90 await subprocess;91 92- 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 };95 96 test('Cleans up subprocess.getOneMessage() listeners, buffer false', testCleanupListeners, false, undefined);97 test('Cleans up subprocess.getOneMessage() listeners, buffer true', testCleanupListeners, true, undefined);4 unmodified lines102 const subprocess = execa('ipc-get-send-get.js', [`${filter}`], {ipc: true, buffer});103 await subprocess.sendMessage(foobarString);104 t.is(await subprocess.getOneMessage(), foobarString);105 106- subprocess.disconnect();106+ subprocess.nodeChildProcess.disconnect();107 108 const {exitCode, isTerminated, message} = await t.throwsAsync(subprocess);109 t.is(exitCode, 1);110 t.false(isTerminated);21 unmodified linesmodified:test/ipc/graceful.js+4 added-4 removed
87 unmodified lines88 89 test('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 lines104 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 lines117 test('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 lines128 129 test('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 linesmodified:test/ipc/outgoing.js+2 added-2 removed
15 unmodified lines16 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}), '.');23 24 const {ipcOutput} = await subprocess;26 unmodified lines51 await subprocess.sendMessage(0);52 t.is(await subprocess.getOneMessage({filter}), 0);53 54 const promise = subprocess.sendMessage(1);55- subprocess.emit('message', '.');55+ subprocess.nodeChildProcess.emit('message', '.');56 await promise;57 58 const messages = Array.from({length: PARALLEL_COUNT}, (_, index) => index + 2);59 for (const message of messages) {29 unmodified linesmodified:test/ipc/reference.js+5 added-5 removed
78 unmodified lines79 80 test('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();84 85 const {ipcOutput, stdout} = await subprocess;86 t.deepEqual(ipcOutput, ['.']);87 t.is(stdout, '.');2 unmodified lines90 test('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();95 96 const {ipcOutput, stdout} = await subprocess;97 t.deepEqual(ipcOutput, ['.', '.']);98 t.is(stdout, '.');2 unmodified lines101 test('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();106 107 const {ipcOutput, stdout} = await subprocess;108 t.deepEqual(ipcOutput, ['.']);109 t.is(stdout, '.');110 });111 112 test('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);116 117 await t.throwsAsync(subprocess.getOneMessage(), {118 message: /subprocess.getOneMessage\(\) could not complete/,119 });10 unmodified linesmodified:test/ipc/send.js+2 added-2 removed
48 unmodified lines49 50 test('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 lines123 test('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);129 130 const {exitCode, isTerminated, message, ipcOutput} = await t.throwsAsync(subprocess);131 t.is(exitCode, 1);12 unmodified linesmodified:test/ipc/strict.js+1 added-1 removed
111 unmodified lines112 });113 114 test('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 linesmodified:test/ipc/validation.js+1 added-1 removed
42 unmodified lines43 test('subprocess.getEachMessage() after disconnection', testPostDisconnection, 'getEachMessage');44 45 const 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 linesmodified:test/methods/main-async.js+36 added
1 import process from 'node:process';2+import {ChildProcess} from 'node:child_process';3 import test from 'ava';4 import {execa} from '../../index.js';5 import {setFixtureDirectory, FIXTURES_DIRECTORY} from '../helpers/fixtures-directory.js';6 34 unmodified lines41 const subprocess = execa('noop.js', ['foo']);42 t.is(typeof subprocess.pid, 'number');43 await subprocess;44 });45+46+test('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+});69+70+test('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 lines3 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';4 5 setFixtureDirectory();6 7-test('promise methods are not enumerable', t => {7+test('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 });11 12 test('finally function is executed on success', async t => {13 let isCalled = false;38 unmodified linesmodified:test/pipe/sequence.js+2 added-2 removed
283 unmodified lines284 const destination = execa('stdin.js');285 const pipePromise = source.pipe(destination);286 287 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);291 292 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 linesmodified:test/resolve/wait-subprocess.js+2 added-2 removed
17 unmodified lines18 test('stdio[*] is undefined if ignored - sync', testIgnore, 3, execaSync);19 20 const 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 };26 27 test('subprocess listeners are cleaned up on success', testSubprocessEventsCleanup, 'empty.js');28 test('subprocess listeners are cleaned up on failure', testSubprocessEventsCleanup, 'fail.js');21 unmodified linesmodified:test/return/early-error.js+36 added-2 removed
25 unmodified lines26 const 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 };34 35 test('child_process.spawn() early errors have correct shape', testEarlyErrorShape, true);76 unmodified lines112 test('child_process.spawn() early errors can use .readableStream()', testEarlyErrorWebConvertor, 'readableStream');113 test('child_process.spawn() early errors can use .writableStream()', testEarlyErrorWebConvertor, 'writableStream');114 test('child_process.spawn() early errors can use .transformStream()', testEarlyErrorWebConvertor, 'transformStream');115 116+const 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+};123+124+test('child_process.spawn() early errors can use .sendMessage()', testEarlyErrorIpc, subprocess => subprocess.sendMessage('.'));125+test('child_process.spawn() early errors can use .getOneMessage()', testEarlyErrorIpc, subprocess => subprocess.getOneMessage());126+test('child_process.spawn() early errors can use .getEachMessage()', testEarlyErrorIpc, subprocess => subprocess.getEachMessage());127+128+test('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+ }134+135+ t.deepEqual(lines, []);136+ await t.throwsAsync(subprocess);137+});138+139+test('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+ }145+146+ t.deepEqual(lines, []);147+ await t.throwsAsync(subprocess);148+});149+150 const testEarlyErrorStream = async (t, getStreamProperty, options) => {151 const subprocess = getEarlyErrorSubprocess(options);152 const stream = getStreamProperty(subprocess);153 stream.on('close', () => {});11 unmodified linesmodified:test/return/final-error.js+4 added-4 removed
11 unmodified lines12 setFixtureDirectory();13 14 const 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 lines33 test('error instance can be undefined', testUnusualError, undefined, 'undefined');34 35 test('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 });40 41 const 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 };46 47 const testErrorCopy = async (t, getPreviousArgument, argument = 'two') => {42 unmodified lines90 91 test('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 linesmodified:test/return/result.js+1 added-1 removed
112 unmodified lines113 114 test('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 linesmodified:test/terminate/cancel.js+2 added-2 removed
67 unmodified lines68 69 test('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 lines91 test('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 linesmodified:test/terminate/cleanup.js+19 added
71 unmodified lines72 test('spawnAndKill detached SIGKILL', spawnAndKill, ['SIGKILL', false, true, false]);73 test('spawnAndKill cleanup detached SIGTERM', spawnAndKill, ['SIGTERM', true, true, false]);74 test('spawnAndKill cleanup detached SIGKILL', spawnAndKill, ['SIGKILL', true, true, false]);75 76+if (!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});79+80+ const pid = await subprocess.getOneMessage();81+ t.true(Number.isInteger(pid));82+ t.true(isRunning(pid));83+84+ process.kill(subprocess.pid, 'SIGTERM');85+86+ 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+}94+95 // See #12896 test('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 linesmodified:test/terminate/graceful.js+2 added-2 removed
45 unmodified lines46 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 lines96 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 linesmodified:test/terminate/kill-error.js+1 added-1 removed
76 unmodified lines77 test('.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 lines110 111 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 lines144 });145 146 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 linesmodified:test/terminate/kill-signal.js+8 added-8 removed
87 unmodified lines88 89 test('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 lines99 });100 101 test('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 lines113 114 test('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 line128 });129 130 test('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 linesmodified:test/terminate/timeout.js+1 added-1 removed
67 unmodified lines68 69 test('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
1+import type {ChildProcess} from 'node:child_process';2 import {expectType, expectError, expectAssignable} from 'tsd';2-import {execa, type Subprocess} from '../../index.js';3+import {execa, type Result, type Subprocess} from '../../index.js';4 5 const subprocess = execa('unicorns');6 expectAssignable<Subprocess>(subprocess);7+expectType<Result<{}>>(await subprocess);8 9 expectType<number | undefined>(subprocess.pid);10+expectType<ChildProcess>(subprocess.nodeChildProcess);11+subprocess.nodeChildProcess.on('exit', () => undefined);12+subprocess.nodeChildProcess.once('exit', () => undefined);13+subprocess.nodeChildProcess.ref();14+subprocess.nodeChildProcess.unref();15+subprocess.nodeChildProcess.send('message');16+subprocess.nodeChildProcess.disconnect();17+expectType<boolean>(subprocess.nodeChildProcess.connected);18+expectType<number | null>(subprocess.nodeChildProcess.exitCode);19+expectType<NodeJS.Signals | null>(subprocess.nodeChildProcess.signalCode);20+expectType<boolean>(subprocess.nodeChildProcess.killed);21+expectType<string[]>(subprocess.nodeChildProcess.spawnargs);22+expectType<string>(subprocess.nodeChildProcess.spawnfile);23+expectError(subprocess.on('exit', () => undefined));24+expectError(subprocess.once('exit', () => undefined));25+expectError(subprocess.ref());26+expectError(subprocess.unref());27+expectError(subprocess.send('message'));28+expectError(subprocess.disconnect());29+expectError(subprocess.connected);30+expectError(subprocess.channel);31+expectError(subprocess.exitCode);32+expectError(subprocess.signalCode);33+expectError(subprocess.killed);34+expectError(subprocess.spawnargs);35+expectError(subprocess.spawnfile);36 37 expectType<boolean>(subprocess.kill());38 subprocess.kill('SIGKILL');39 subprocess.kill(undefined);14 unmodified lines54 expectError(subprocess.kill('SIGKILL', {}));55 expectError(subprocess.kill(null, new Error('test')));56 57 const ipcSubprocess = execa('unicorns', {ipc: true});30-expectAssignable<Subprocess>(subprocess);58+expectAssignable<Subprocess>(ipcSubprocess);modified:types/subprocess/subprocess.d.ts+12 added-6 removed
119 unmodified lines120 /**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;124+125+ /**126+ Underlying Node.js [`ChildProcess`](https://nodejs.org/api/child_process.html#class-childprocess) instance.127+128+ 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 };132 133 /**127-[`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess) with additional methods and properties.134+Subprocess with Execa-specific methods and properties. It is also a `Promise` either resolving with its successful `result`, or rejecting with its `error`.135 */136 export type Subprocess<OptionsType extends Options = Options> =130- & Omit<ChildProcess, keyof ExecaCustomSubprocess<OptionsType>>131- & ExecaCustomSubprocess<OptionsType>;137+ & ExecaCustomSubprocess<OptionsType>138+ & Promise<Result<OptionsType>>;139 140 /**141 The 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 */145 export type ResultPromise<OptionsType extends Options = Options> =139- & Subprocess<OptionsType>140- & Promise<Result<OptionsType>>;146+ Subprocess<OptionsType>;147 148 export {};