Add `result.ipc`/`error.ipc` (#1067)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent 839c2fe · Browse files · 43 files·+725 added−146 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
43 files+725 added−146 removed
- tests:+427 added−124 removed
- other:+298 added−22 removed
Provenance
- Commit
3ab34de- Tree
55f8efb- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
839c2fe
43 files changed+725 added−146 removed
modified:docs/api.md+10 added
465 unmodified lines466 Items are arrays when their corresponding `stdio` option is a [transform in object mode](transform.md#object-mode).467 468 [More info.](output.md#additional-file-descriptors)469 470+### result.ipc471+472+_Type_: `unknown[]`473+474+All the messages [sent by the subprocess](#sendmessagemessage) to the current process.475+476+This is empty unless the [`ipc`](#optionsipc) option is `true`. Also, this is empty if the [`buffer`](#optionsbuffer) option is `false`.477+478+[More info.](ipc.md#retrieve-all-messages)479+480 ### result.pipedFrom481 482 _Type:_ [`Array<Result | ExecaError>`](#result)483 611 unmodified linesmodified:docs/errors.md+2 added-2 removed
75 unmodified lines7677787980808182828384858635 unmodified lines75 unmodified lines## Error message
For better [debugging](debugging.md), [`error.message`](api.md#errormessage) includes both:- The command and the [reason it failed](#failure-reason).- Its [`stdout`, `stderr`](output.md#stdout-and-stderr) and [other file descriptors'](output.md#additional-file-descriptors) output, separated with newlines and not [interleaved](output.md#interleaved-output).- Its [`stdout`, `stderr`](output.md#stdout-and-stderr), [other file descriptors'](output.md#additional-file-descriptors) output and [IPC messages](ipc.md), separated with newlines and not [interleaved](output.md#interleaved-output).
[`error.shortMessage`](api.md#errorshortmessage) is the same but without `stdout`/`stderr`.[`error.shortMessage`](api.md#errorshortmessage) is the same but without `stdout`, `stderr` nor IPC messages.
[`error.originalMessage`](api.md#errororiginalmessage) is the same but also without the command. This exists only in specific instances, such as when calling [`subprocess.kill(error)`](termination.md#error-message-and-stack-trace), using the [`cancelSignal`](termination.md#canceling) option, passing an invalid command or [option](api.md#options), or throwing an exception in a [stream](streams.md) or [transform](transform.md).
```js35 unmodified linesmodified:docs/ipc.md+28 added
65 unmodified lines66 await sendMessage(message + 1);67 }68 ```69 70+## Retrieve all messages71+72+The [`result.ipc`](api.md#resultipc) array contains all the messages sent by the subprocess. In many situations, this is simpler than using [`subprocess.getOneMessage()`](api.md#subprocessgetonemessage) and [`subprocess.getEachMessage()`](api.md#subprocessgeteachmessage).73+74+```js75+// main.js76+import {execaNode} from 'execa';77+78+const {ipc} = await execaNode`build.js`;79+console.log(ipc[0]); // {kind: 'start', timestamp: date}80+console.log(ipc[1]); // {kind: 'stop', timestamp: date}81+```82+83+```js84+// build.js85+import {sendMessage} from 'execa';86+87+await sendMessage({kind: 'start', timestamp: new Date()});88+await runBuild();89+await sendMessage({kind: 'stop', timestamp: new Date()});90+```91+92 ## Message type93 94 By default, messages are serialized using [`structuredClone()`](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm). This supports most types including objects, arrays, `Error`, `Date`, `RegExp`, `Map`, `Set`, `bigint`, `Uint8Array`, and circular references. This throws when passing functions, symbols or promises (including inside an object or array).95 2 unmodified lines98 ```js99 const subprocess = execaNode({serialization: 'json'})`child.js`;100 ```101 102+## Debugging103+104+When the [`verbose`](api.md#optionsverbose) option is `'full'`, the IPC messages sent by the subprocess to the current process are [printed on the console](debugging.md#full-mode).105+106+Also, when the subprocess [failed](errors.md#subprocess-failure), [`error.ipc`](api.md) contains all the messages sent by the subprocess. Those are also shown at the end of the [error message](errors.md#error-message).107+108 <hr>109 110 [**Next**: 🐛 Debugging](debugging.md)\111 [**Previous**: ⏳️ Streams](streams.md)\1 unmodified linemodified:docs/output.md+26 added-3 removed
53 unmodified lines54 // Or:55 await execa({stdout: 1, stderr: 1})`npm run build`;56 ```57 58+## Any output type59+60+If the subprocess uses Node.js, [IPC](ipc.md) can be used to return [almost any type](ipc.md#message-type) from the subprocess. The [`result.ipc`](api.md#resultipc) array contains all the messages sent by the subprocess.61+62+```js63+// main.js64+import {execaNode} from 'execa';65+66+const {ipc} = await execaNode`build.js`;67+console.log(ipc[0]); // {kind: 'start', timestamp: date}68+console.log(ipc[1]); // {kind: 'stop', timestamp: date}69+```70+71+```js72+// build.js73+import {sendMessage} from 'execa';74+75+await sendMessage({kind: 'start', timestamp: new Date()});76+await runBuild();77+await sendMessage({kind: 'stop', timestamp: new Date()});78+```79+80 ## Multiple targets81 82 The output can be redirected to multiple targets by setting the [`stdout`](api.md#optionsstdout) or [`stderr`](api.md#optionsstderr) option to an array of values. This also allows specifying multiple inputs with the [`stdin`](api.md#optionsstdin) option.83 77 unmodified lines161 ## Big output162 163 To prevent high memory consumption, a maximum output size can be set using the [`maxBuffer`](api.md#optionsmaxbuffer) option. It defaults to 100MB.164 143-When this threshold is hit, the subprocess fails and [`error.isMaxBuffer`](api.md#errorismaxbuffer) becomes `true`. The truncated output is still available using [`error.stdout`](api.md#resultstdout) and [`error.stderr`](api.md#resultstderr).165+When this threshold is hit, the subprocess fails and [`error.isMaxBuffer`](api.md#errorismaxbuffer) becomes `true`. The truncated output is still available using [`error.stdout`](api.md#resultstdout), [`error.stderr`](api.md#resultstderr) and [`error.ipc`](api.md#resultipc).166 167 This is measured:168 - By default: in [characters](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length).169 - If the [`encoding`](binary.md#encoding) option is `'buffer'`: in bytes.170 - If the [`lines`](lines.md#simple-splitting) option is `true`: in lines.171 - If a [transform in object mode](transform.md#object-mode) is used: in objects.172+- With [`error.ipc`](ipc.md#retrieve-all-messages): in messages.173 174 ```js175 try {176 await execa({maxBuffer: 1_000_000})`npm run build`;9 unmodified lines186 ```187 188 ## Low memory189 167-When the [`buffer`](api.md#optionsbuffer) option is `false`, [`result.stdout`](api.md#resultstdout), [`result.stderr`](api.md#resultstderr), [`result.all`](api.md#resultall) and [`result.stdio[*]`](api.md#resultstdio) properties are not set.190+When the [`buffer`](api.md#optionsbuffer) option is `false`, [`result.stdout`](api.md#resultstdout), [`result.stderr`](api.md#resultstderr), [`result.all`](api.md#resultall), [`result.stdio[*]`](api.md#resultstdio) and [`result.ipc`](api.md#resultipc) properties are empty.191 169-This prevents high memory consumption when the output is big. However, the output must be either ignored, [redirected](#file-output) or [streamed](streams.md). If streamed, this should be done right away to avoid missing any data.192+This prevents high memory consumption when the output is big. However, the output must be either ignored, [redirected](#file-output), [streamed](streams.md) or [listened to](ipc.md#listening-to-messages). If streamed, this should be done right away to avoid missing any data.193 194 <hr>195 196 [**Next**: 📃 Text lines](lines.md)\2 unmodified linesmodified:lib/io/max-buffer.js+18 added
1 import {MaxBufferError} from 'get-stream';2+import {disconnect} from '../ipc/validation.js';3 import {getStreamName} from '../utils/standard-stream.js';4 5 // When the `maxBuffer` option is hit, a MaxBufferError is thrown.6 // The stream is aborted, then specific information is kept for the error message.27 unmodified lines34 35 return 'characters';36 };37 38+// Check the `maxBuffer` option with `result.ipc`39+export const checkIpcMaxBuffer = (subprocess, ipcMessages, maxBuffer) => {40+ if (ipcMessages.length !== maxBuffer) {41+ return;42+ }43+44+ disconnect(subprocess);45+ const error = new MaxBufferError();46+ error.maxBufferInfo = {fdNumber: 'ipc'};47+ throw error;48+};49+50 // Error message when `maxBuffer` is hit51 export const getMaxBufferMessage = (error, maxBuffer) => {52 const {streamName, threshold, unit} = getMaxBufferInfo(error, maxBuffer);53 return `Command's ${streamName} was larger than ${threshold} ${unit}`;5 unmodified lines59 }60 61 const {maxBufferInfo: {fdNumber, unit}} = error;62 delete error.maxBufferInfo;63+64+ if (fdNumber === 'ipc') {65+ return {streamName: 'IPC output', threshold: maxBuffer.at(-1), unit: 'messages'};66+ }67+68 return {streamName: getStreamName(fdNumber), threshold: maxBuffer[fdNumber], unit};69 };70 71 // The only way to apply `maxBuffer` with `spawnSync()` is to use the native `maxBuffer` option Node.js provides.18 unmodified linesmodified:lib/ipc/get-each.js+12 added-2 removed
122345615 unmodified lines2223242526262728293031322 unmodified lines353637383940414243443 unmodified lines48495051525354555657import {once, on} from 'node:events';import {validateIpcOption, validateConnection} from './validation.js';import {validateIpcOption, validateConnection, disconnect} from './validation.js';
// Like `[sub]process.on('message')` but promise-basedexport const getEachMessage = ({anyProcess, isSubprocess, ipc}) => loopOnMessages({ anyProcess,15 unmodified lines
const stopOnExit = async (anyProcess, controller) => { try { await once(anyProcess, 'disconnect', {signal: controller.signal}); } catch {} finally { } catch { disconnectOnProcessError(anyProcess, controller); } finally { controller.abort(); }};
2 unmodified lines for await (const [message] of on(anyProcess, 'message', {signal: controller.signal})) { yield message; } } catch (error) { disconnectOnProcessError(anyProcess, controller);
if (!controller.signal.aborted) { throw error; } } finally {3 unmodified lines await anyProcess; } }};
const disconnectOnProcessError = (anyProcess, {signal}) => { if (!signal.aborted) { disconnect(anyProcess); }};modified:lib/ipc/get-one.js+31 added-5 removed
1 import {once} from 'node:events';2-import {validateIpcOption, validateConnection} from './validation.js';2+import {3+ validateIpcOption,4+ validateConnection,5+ disconnect,6+ throwOnEarlyDisconnect,7+} from './validation.js';8 9 // Like `[sub]process.once('message')` but promise-based10 export const getOneMessage = ({anyProcess, isSubprocess, ipc}) => {11 const methodName = 'getOneMessage';12 validateIpcOption(methodName, isSubprocess, ipc);13 validateConnection(methodName, isSubprocess, anyProcess.channel !== null);14 10- return onceMessage(anyProcess);15+ return onceMessage(anyProcess, isSubprocess, methodName);16 };17 13-const onceMessage = async anyProcess => {14- const [message] = await once(anyProcess, 'message');15- return message;18+const onceMessage = async (anyProcess, isSubprocess, methodName) => {19+ const controller = new AbortController();20+ try {21+ const [message] = await Promise.race([22+ once(anyProcess, 'message', {signal: controller.signal}),23+ throwOnDisconnect({24+ anyProcess,25+ isSubprocess,26+ methodName,27+ controller,28+ }),29+ ]);30+ return message;31+ } catch (error) {32+ disconnect(anyProcess);33+ throw error;34+ } finally {35+ controller.abort();36+ }37 };38+39+const throwOnDisconnect = async ({anyProcess, isSubprocess, methodName, controller: {signal}}) => {40+ await once(anyProcess, 'disconnect', {signal});41+ throwOnEarlyDisconnect(methodName, isSubprocess);42+};modified:lib/ipc/messages.js+29 added-4 removed
1+import {checkIpcMaxBuffer} from '../io/max-buffer.js';2 import {shouldLogIpc, logIpcMessage} from '../verbose/ipc.js';3 import {loopOnMessages} from './get-each.js';4 5 // Iterate through IPC messages sent by the subprocess5-export const waitForIpcMessages = async (subprocess, ipc, verboseInfo) => {6- if (!ipc || !shouldLogIpc(verboseInfo)) {7- return;6+export const waitForIpcMessages = async ({7+ subprocess,8+ buffer: bufferArray,9+ maxBuffer: maxBufferArray,10+ ipc,11+ ipcMessages,12+ verboseInfo,13+}) => {14+ if (!ipc) {15+ return ipcMessages;16 }17 18+ const isVerbose = shouldLogIpc(verboseInfo);19+ const buffer = bufferArray.at(-1);20+ const maxBuffer = maxBufferArray.at(-1);21+22+ if (!isVerbose && !buffer) {23+ return ipcMessages;24+ }25+26 for await (const message of loopOnMessages({27 anyProcess: subprocess,28 isSubprocess: false,29 ipc,30 shouldAwait: false,31 })) {32+ if (buffer) {33+ checkIpcMaxBuffer(subprocess, ipcMessages, maxBuffer);34+ ipcMessages.push(message);35+ }36+37+ if (isVerbose) {16- logIpcMessage(message, verboseInfo);38+ logIpcMessage(message, verboseInfo);39+ }40 }41+42+ return ipcMessages;43 };modified:lib/ipc/send.js+9 added-2 removed
1 import {2 validateIpcOption,3 validateConnection,4 handleSerializationError,5+ disconnect,6 } from './validation.js';7 8 // Like `[sub]process.send()` but promise-based.9 // We do not `await subprocess` during `.sendMessage()` nor `.getOneMessage()` since those methods are transient.3 unmodified lines13 const methodName = 'sendMessage';14 validateIpcOption(methodName, isSubprocess, ipc);15 validateConnection(methodName, isSubprocess, anyProcess.connected);16 16- return sendOneMessage(anyProcessSend, isSubprocess, message);17+ return sendOneMessage({18+ anyProcess,19+ anyProcessSend,20+ isSubprocess,21+ message,22+ });23 };24 19-const sendOneMessage = async (anyProcessSend, isSubprocess, message) => {25+const sendOneMessage = async ({anyProcess, anyProcessSend, isSubprocess, message}) => {26 try {27 await anyProcessSend(message);28 } catch (error) {29+ disconnect(anyProcess);30 handleSerializationError(error, isSubprocess, message);31 throw error;32 }33 };modified:lib/ipc/validation.js+14 added
11 unmodified lines12 throw new Error(`${getNamespaceName(isSubprocess)}${methodName}() cannot be used: the ${getOtherProcessName(isSubprocess)} has already exited or disconnected.`);13 }14 };15 16+// When `getOneMessage()` could not complete due to an early disconnection17+export const throwOnEarlyDisconnect = (methodName, isSubprocess) => {18+ throw new Error(`${getNamespaceName(isSubprocess)}${methodName}() could not complete: the ${getOtherProcessName(isSubprocess)} exited or disconnected.`);19+};20+21 const getNamespaceName = isSubprocess => isSubprocess ? '' : 'subprocess.';22 23 const getOtherProcessName = isSubprocess => isSubprocess ? 'parent process' : 'subprocess';24 24 unmodified lines49 'circular structure',50 // Message has cycles inside toJSON(), with `serialization: 'json'`51 'call stack size exceeded',52 ];53+54+// When any error arises, we disconnect the IPC.55+// Otherwise, it is likely that one of the processes will stop sending/receiving messages.56+// This would leave the other process hanging.57+export const disconnect = anyProcess => {58+ if (anyProcess.connected) {59+ anyProcess.disconnect();60+ }61+};modified:lib/methods/main-async.js+11 added-2 removed
130 unmodified lines131 // Asynchronous logic, as opposed to the previous logic which can be run synchronously, i.e. can be returned to user right away132 const handlePromise = async ({subprocess, options, startTime, verboseInfo, fileDescriptors, originalStreams, command, escapedCommand, onInternalError, controller}) => {133 const context = {timedOut: false};134 135- const [errorInfo, [exitCode, signal], stdioResults, allResult] = await waitForSubprocessResult({135+ const [136+ errorInfo,137+ [exitCode, signal],138+ stdioResults,139+ allResult,140+ ipcMessages,141+ ] = await waitForSubprocessResult({142 subprocess,143 options,144 context,145 verboseInfo,12 unmodified lines158 exitCode,159 signal,160 stdio,161 all,162+ ipcMessages,163 context,164 options,165 command,166 escapedCommand,1 unmodified line168 });169 return handleResult(result, verboseInfo, options);170 };171 165-const getAsyncResult = ({errorInfo, exitCode, signal, stdio, all, context, options, command, escapedCommand, startTime}) => 'error' in errorInfo172+const getAsyncResult = ({errorInfo, exitCode, signal, stdio, all, ipcMessages, context, options, command, escapedCommand, startTime}) => 'error' in errorInfo173 ? makeError({174 error: errorInfo.error,175 command,176 escapedCommand,3 unmodified lines180 exitCode,181 signal,182 stdio,183 all,184+ ipcMessages,185 options,186 startTime,187 isSync: false,188 })1 unmodified line190 command,191 escapedCommand,192 stdio,193 all,194+ ipcMessages,195 options,196 startTime,197 });modified:lib/methods/main-sync.js+2 added
139 unmodified lines140 command,141 escapedCommand,142 stdio,143 all,144+ ipcMessages: [],145 options,146 startTime,147 })148 : makeError({6 unmodified lines155 exitCode,156 signal,157 stdio,158 all,159+ ipcMessages: [],160 options,161 startTime,162 isSync: true,163 });modified:lib/resolve/wait-subprocess.js+10 added-1 removed
56 unmodified lines57 stripFinalNewline,58 verboseInfo,59 streamInfo,60 });61+ const ipcMessages = [];62 const originalPromises = waitForOriginalStreams(originalStreams, subprocess, streamInfo);63 const customStreamsEndPromises = waitForCustomStreamsEnd(fileDescriptors, streamInfo);64 65 try {2 unmodified lines68 {},69 waitForSuccessfulExit(exitPromise),70 Promise.all(stdioPromises),71 allPromise,71- waitForIpcMessages(subprocess, ipc, verboseInfo),72+ waitForIpcMessages({73+ subprocess,74+ buffer,75+ maxBuffer,76+ ipc,77+ ipcMessages,78+ verboseInfo,79+ }),80 ...originalPromises,81 ...customStreamsEndPromises,82 ]),83 onInternalError,5 unmodified lines89 {error},90 exitPromise,91 Promise.all(stdioPromises.map(stdioPromise => getBufferedData(stdioPromise))),92 getBufferedData(allPromise),93+ ipcMessages,94 Promise.allSettled(originalPromises),95 Promise.allSettled(customStreamsEndPromises),96 ]);97 }24 unmodified linesmodified:lib/return/message.js+12 added-1 removed
1+import {inspect} from 'node:util';2 import stripFinalNewline from 'strip-final-newline';3 import {isUint8Array, uint8ArrayToString} from '../utils/uint-array.js';4 import {fixCwdError} from '../arguments/cwd.js';5 import {escapeLines} from '../arguments/escape.js';3 unmodified lines9 // Computes `error.message`, `error.shortMessage` and `error.originalMessage`10 export const createMessages = ({11 stdio,12 all,13+ ipcMessages,14 originalError,15 signal,16 signalDescription,17 exitCode,21 unmodified lines39 const originalMessage = getOriginalMessage(originalError, cwd);40 const suffix = originalMessage === undefined ? '' : `\n${originalMessage}`;41 const shortMessage = `${prefix}: ${escapedCommand}${suffix}`;42 const messageStdio = all === undefined ? [stdio[2], stdio[1]] : [all];41- const message = [shortMessage, ...messageStdio, ...stdio.slice(3)]43+ const message = [44+ shortMessage,45+ ...messageStdio,46+ ...stdio.slice(3),47+ ipcMessages.map(ipcMessage => serializeIpcMessage(ipcMessage)).join('\n'),48+ ]49 .map(messagePart => escapeLines(stripFinalNewline(serializeMessagePart(messagePart))))50 .filter(Boolean)51 .join('\n\n');52 return {originalMessage, shortMessage, message};38 unmodified lines91 const escapedOriginalMessage = escapeLines(fixCwdError(originalMessage, cwd));92 return escapedOriginalMessage === '' ? undefined : escapedOriginalMessage;93 };94 95+const serializeIpcMessage = ipcMessage => typeof ipcMessage === 'string'96+ ? ipcMessage97+ : inspect(ipcMessage);98+99 const serializeMessagePart = messagePart => Array.isArray(messagePart)100 ? messagePart.map(messageItem => stripFinalNewline(serializeMessageItem(messageItem))).filter(Boolean).join('\n')101 : serializeMessageItem(messagePart);102 11 unmodified linesmodified:lib/return/result.js+8 added
7 unmodified lines8 command,9 escapedCommand,10 stdio,11 all,12+ ipcMessages,13 options: {cwd},14 startTime,15 }) => omitUndefinedProperties({16 command,9 unmodified lines26 stdout: stdio[1],27 stderr: stdio[2],28 all,29 stdio,30+ ipc: ipcMessages,31 pipedFrom: [],32 });33 34 // Object returned on subprocess failure before spawning13 unmodified lines48 timedOut: false,49 isCanceled: false,50 isMaxBuffer: false,51 stdio: Array.from({length: fileDescriptors.length}),52+ ipcMessages: [],53 options,54 isSync,55 });56 9 unmodified lines66 exitCode: rawExitCode,67 signal: rawSignal,68 stdio,69 all,70+ ipcMessages,71 options: {timeoutDuration, timeout = timeoutDuration, cwd, maxBuffer},72 isSync,73 }) => {74 const {exitCode, signal, signalDescription} = normalizeExitPayload(rawExitCode, rawSignal);75 const {originalMessage, shortMessage, message} = createMessages({76 stdio,77 all,78+ ipcMessages,79 originalError,80 signal,81 signalDescription,82 exitCode,18 unmodified lines101 signal,102 signalDescription,103 stdio,104 all,105+ ipcMessages,106 cwd,107 originalMessage,108 shortMessage,109 }));12 unmodified lines122 signal,123 signalDescription,124 stdio,125 all,126+ ipcMessages,127 cwd,128 originalMessage,129 shortMessage,130 }) => omitUndefinedProperties({15 unmodified lines146 stdout: stdio[1],147 stderr: stdio[2],148 all,149 stdio,150+ ipc: ipcMessages,151 pipedFrom: [],152 });153 154 const omitUndefinedProperties = result => Object.fromEntries(Object.entries(result).filter(([, value]) => value !== undefined));9 unmodified linesadded:test/fixtures/ipc-echo-fail.js+6 added
1+#!/usr/bin/env node2+import process from 'node:process';3+import {sendMessage, getOneMessage} from '../../index.js';4+5+await sendMessage(await getOneMessage());6+process.exitCode = 1;added:test/fixtures/ipc-echo-twice-fail.js+8 added
1+#!/usr/bin/env node2+import process from 'node:process';3+import {sendMessage, getOneMessage} from '../../index.js';4+5+const message = await getOneMessage();6+await sendMessage(message);7+await sendMessage(message);8+process.exitCode = 1;modified:test/fixtures/ipc-echo-twice.js+4 added-2 removed
1 #!/usr/bin/env node2 import {sendMessage, getOneMessage} from '../../index.js';3 4-await sendMessage(await getOneMessage());5-await sendMessage(await getOneMessage());4+const message = await getOneMessage();5+const secondMessagePromise = getOneMessage();6+await sendMessage(message);7+await sendMessage(await secondMessagePromise);modified:test/fixtures/ipc-iterate-error.js+5 added-9 removed
1 #!/usr/bin/env node2 import process from 'node:process';3-import {sendMessage, getEachMessage} from '../../index.js';3+import {getEachMessage} from '../../index.js';4 import {foobarString} from '../helpers/input.js';5 6 // @todo: replace with Array.fromAsync(subprocess.getEachMessage()) after dropping support for Node <22.0.07 const iterateAllMessages = async () => {5 unmodified lines13 return messages;14 };15 16 const cause = new Error(foobarString);17-try {18- await Promise.all([19- iterateAllMessages(),20- process.emit('error', cause),21- ]);17+await Promise.all([18+ iterateAllMessages(),19+ process.emit('error', cause),20+]);22-} catch (error) {23- await sendMessage(error);24-}added:test/fixtures/ipc-iterate-print.js+14 added
1+#!/usr/bin/env node2+import process from 'node:process';3+import {sendMessage, getEachMessage} from '../../index.js';4+import {foobarString} from '../helpers/input.js';5+6+await sendMessage(foobarString);7+8+for await (const message of getEachMessage()) {9+ if (message === foobarString) {10+ break;11+ }12+13+ process.stdout.write(`${message}`);14+}modified:test/fixtures/ipc-iterate-twice.js+2 added-3 removed
1 #!/usr/bin/env node2-import process from 'node:process';2 import {sendMessage, getEachMessage} from '../../index.js';3 import {foobarString} from '../helpers/input.js';4 5 for (let index = 0; index < 2; index += 1) {2 unmodified lines8 if (message === foobarString) {9 break;10 }11 13- process.stdout.write(message);12+ await sendMessage(message);13 }14 15 // eslint-disable-next-line no-await-in-loop17- await sendMessage('.');16+ await sendMessage(foobarString);17 }modified:test/fixtures/ipc-iterate.js+2 added-3 removed
1 #!/usr/bin/env node2-import process from 'node:process';3-import {getEachMessage} from '../../index.js';2+import {getEachMessage, sendMessage} from '../../index.js';3 import {foobarString} from '../helpers/input.js';4 5 for await (const message of getEachMessage()) {6 if (message === foobarString) {7 break;8 }9 11- process.stdout.write(`${message}`);10+ await sendMessage(message);11 }modified:test/fixtures/ipc-process-error.js+5 added-9 removed
1 #!/usr/bin/env node2 import process from 'node:process';3-import {sendMessage, getOneMessage} from '../../index.js';3+import {getOneMessage} from '../../index.js';4 import {foobarString} from '../helpers/input.js';5 6 const cause = new Error(foobarString);7-try {8- await Promise.all([9- getOneMessage(),10- process.emit('error', cause),11- ]);7+await Promise.all([8+ getOneMessage(),9+ process.emit('error', cause),10+]);12-} catch (error) {13- await sendMessage(error);14-}added:test/fixtures/ipc-send-error.js+4 added
1+#!/usr/bin/env node2+import {sendMessage} from '../../index.js';3+4+await sendMessage(0n);deleted:test/fixtures/ipc-send-iterate.js-14 removed
1-#!/usr/bin/env node2-import process from 'node:process';3-import {sendMessage, getEachMessage} from '../../index.js';4-import {foobarString} from '../helpers/input.js';5-6-await sendMessage(foobarString);7-8-for await (const message of getEachMessage()) {9- if (message === foobarString) {10- break;11- }12-13- process.stdout.write(`${message}`);14-}added:test/fixtures/ipc-send-twice-wait.js+7 added
1+#!/usr/bin/env node2+import {sendMessage, getOneMessage} from '../../index.js';3+import {foobarString} from '../helpers/input.js';4+5+await sendMessage(foobarString);6+await sendMessage(foobarString);7+await getOneMessage();modified:test/helpers/input.js+2 added
1 import {Buffer} from 'node:buffer';2+import {inspect} from 'node:util';3 4 const textEncoder = new TextEncoder();5 6 export const foobarString = 'foobar';10 unmodified lines17 export const foobarUppercaseUint8Array = textEncoder.encode(foobarUppercase);18 export const foobarUppercaseHex = Buffer.from(foobarUppercase).toString('hex');19 export const foobarObject = {foo: 'bar'};20 export const foobarObjectString = JSON.stringify(foobarObject);21+export const foobarObjectInspect = inspect(foobarObject);added:test/helpers/ipc.js+9 added
1+// @todo: replace with Array.fromAsync(subprocess.getEachMessage()) after dropping support for Node <22.0.02+export const iterateAllMessages = async subprocess => {3+ const messages = [];4+ for await (const message of subprocess.getEachMessage()) {5+ messages.push(message);6+ }7+8+ return messages;9+};modified:test/io/max-buffer.js+25 added
4 unmodified lines5 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6 import {fullStdio} from '../helpers/stdio.js';7 import {getEarlyErrorSubprocess} from '../helpers/early-error.js';8 import {maxBuffer, assertErrorMessage} from '../helpers/max-buffer.js';9+import {foobarString} from '../helpers/input.js';10 11 setFixtureDirectory();12 13 const maxBufferMessage = {message: /maxBuffer exceeded/};252 unmodified lines266 t.true(failed);267 t.false(isMaxBuffer);268 });269 270+test('maxBuffer works with result.ipc', async t => {271+ const {272+ isMaxBuffer,273+ shortMessage,274+ message,275+ stderr,276+ ipc,277+ } = await t.throwsAsync(execa('ipc-send-twice-wait.js', {ipc: true, maxBuffer: {ipc: 1}}));278+ t.true(isMaxBuffer);279+ t.is(shortMessage, 'Command\'s IPC output was larger than 1 messages: ipc-send-twice-wait.js\nmaxBuffer exceeded');280+ t.true(message.endsWith(`\n\n${foobarString}`));281+ t.true(stderr.includes('Error: getOneMessage() could not complete'));282+ t.deepEqual(ipc, [foobarString]);283+});284+285+test('maxBuffer is ignored with result.ipc if buffer is false', async t => {286+ const subprocess = execa('ipc-send-twice-wait.js', {ipc: true, maxBuffer: {ipc: 1}, buffer: false});287+ t.is(await subprocess.getOneMessage(), foobarString);288+ t.is(await subprocess.getOneMessage(), foobarString);289+ await subprocess.sendMessage(foobarString);290+291+ const {ipc} = await subprocess;292+ t.deepEqual(ipc, []);293+});modified:test/io/pipeline.js+3 added-1 removed
1 import test from 'ava';2 import {execa} from '../../index.js';3 import {getStdio, STANDARD_STREAMS} from '../helpers/stdio.js';4 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';5+import {getEarlyErrorSubprocess, expectedEarlyError} from '../helpers/early-error.js';6 7 setFixtureDirectory();8 9 const testDestroyStandard = async (t, fdNumber) => {6 unmodified lines16 test('Does not destroy process.stdout on subprocess errors', testDestroyStandard, 1);17 test('Does not destroy process.stderr on subprocess errors', testDestroyStandard, 2);18 19 const testDestroyStandardSpawn = async (t, fdNumber) => {19- await t.throwsAsync(execa('forever.js', {...getStdio(fdNumber, [STANDARD_STREAMS[fdNumber], 'pipe']), uid: -1}));20+ const error = await t.throwsAsync(getEarlyErrorSubprocess(getStdio(fdNumber, [STANDARD_STREAMS[fdNumber], 'pipe'])));21+ t.like(error, expectedEarlyError);22 t.false(STANDARD_STREAMS[fdNumber].destroyed);23 };24 25 test('Does not destroy process.stdin on subprocess early errors', testDestroyStandardSpawn, 0);15 unmodified linesmodified:test/ipc/get-each.js+38 added-36 removed
1 import test from 'ava';2 import {execa} from '../../index.js';3 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';4 import {foobarString, foobarArray} from '../helpers/input.js';5+import {iterateAllMessages} from '../helpers/ipc.js';6 7 setFixtureDirectory();8 8-// @todo: replace with Array.fromAsync(subprocess.getEachMessage()) after dropping support for Node <22.0.09-const iterateAllMessages = async subprocess => {10- const messages = [];11- for await (const message of subprocess.getEachMessage()) {12- messages.push(message);13- }14-15- return messages;16-};17-9 test('Can iterate over IPC messages', async t => {10 let count = 0;11 const subprocess = execa('ipc-send-twice.js', {ipc: true});12 for await (const message of subprocess.getEachMessage()) {13 t.is(message, foobarArray[count++]);14 }15+16+ const {ipc} = await subprocess;17+ t.deepEqual(ipc, foobarArray);18 });19 20 test('Can iterate over IPC messages in subprocess', async t => {21 const subprocess = execa('ipc-iterate.js', {ipc: true});1 unmodified line23 await subprocess.sendMessage('.');24 await subprocess.sendMessage('.');25 await subprocess.sendMessage(foobarString);26 33- const {stdout} = await subprocess;34- t.is(stdout, '..');27+ const {ipc} = await subprocess;28+ t.deepEqual(ipc, ['.', '.']);29 });30 31 test('Can iterate multiple times over IPC messages in subprocess', async t => {32 const subprocess = execa('ipc-iterate-twice.js', {ipc: true});33 34 await subprocess.sendMessage('.');41- await subprocess.sendMessage(foobarString);35 t.is(await subprocess.getOneMessage(), '.');43- await subprocess.sendMessage('.');36 await subprocess.sendMessage(foobarString);37+ t.is(await subprocess.getOneMessage(), foobarString);38+ await subprocess.sendMessage('.');39 t.is(await subprocess.getOneMessage(), '.');40+ await subprocess.sendMessage(foobarString);41+ t.is(await subprocess.getOneMessage(), foobarString);42 47- const {stdout} = await subprocess;48- t.is(stdout, '..');43+ const {ipc} = await subprocess;44+ t.deepEqual(ipc, ['.', foobarString, '.', foobarString]);45 });46 47 test('subprocess.getEachMessage() can be called twice at the same time', async t => {48 const subprocess = execa('ipc-send-twice.js', {ipc: true});49 t.deepEqual(50 await Promise.all([iterateAllMessages(subprocess), iterateAllMessages(subprocess)]),51 [foobarArray, foobarArray],52 );53+57- await subprocess;54+ const {ipc} = await subprocess;55+ t.deepEqual(ipc, foobarArray);56 });57 58 const HIGH_CONCURRENCY_COUNT = 100;59 60 test('Can send many messages at once with exports.getEachMessage()', async t => {61 const subprocess = execa('ipc-iterate.js', {ipc: true});62 await Promise.all(Array.from({length: HIGH_CONCURRENCY_COUNT}, (_, index) => subprocess.sendMessage(index)));63 await subprocess.sendMessage(foobarString);66- const {stdout} = await subprocess;67- const expectedStdout = Array.from({length: HIGH_CONCURRENCY_COUNT}, (_, index) => `${index}`).join('');68- t.is(stdout, expectedStdout);64+65+ const {ipc} = await subprocess;66+ t.deepEqual(ipc, Array.from({length: HIGH_CONCURRENCY_COUNT}, (_, index) => index));67 });68 69 test('Disconnecting in the current process stops exports.getEachMessage()', async t => {72- const subprocess = execa('ipc-send-iterate.js', {ipc: true});70+ const subprocess = execa('ipc-iterate-print.js', {ipc: true});71 t.is(await subprocess.getOneMessage(), foobarString);72 await subprocess.sendMessage('.');73 subprocess.disconnect();74+75 const {stdout} = await subprocess;76 t.is(stdout, '.');77 });78 1 unmodified line80 const subprocess = execa('ipc-send-disconnect.js', {ipc: true});81 for await (const message of subprocess.getEachMessage()) {82 t.is(message, foobarString);83 }84+85+ const {ipc} = await subprocess;86+ t.deepEqual(ipc, [foobarString]);87 });88 89 test('Exiting the subprocess stops subprocess.getEachMessage()', async t => {90 const subprocess = execa('ipc-send.js', {ipc: true});91 for await (const message of subprocess.getEachMessage()) {92 t.is(message, foobarString);93 }94+95+ const {ipc} = await subprocess;96+ t.deepEqual(ipc, [foobarString]);97 });98 99 const loopAndBreak = async (t, subprocess) => {100 // eslint-disable-next-line no-unreachable-loop4 unmodified lines105 };106 107 test('Breaking from subprocess.getEachMessage() awaits the subprocess', async t => {108 const subprocess = execa('ipc-send-fail.js', {ipc: true});104- const {exitCode} = await t.throwsAsync(loopAndBreak(t, subprocess));109+ const {exitCode, ipc} = await t.throwsAsync(loopAndBreak(t, subprocess));110 t.is(exitCode, 1);111+ t.deepEqual(ipc, [foobarString]);112 });113 108-test('Cleans up subprocess.getEachMessage() listeners', async t => {109- const subprocess = execa('ipc-send.js', {ipc: true});114+const testCleanupListeners = async (t, buffer) => {115+ const subprocess = execa('ipc-send.js', {ipc: true, buffer});116+ const bufferCount = buffer ? 1 : 0;117 111- t.is(subprocess.listenerCount('message'), 0);112- t.is(subprocess.listenerCount('disconnect'), 0);118+ t.is(subprocess.listenerCount('message'), bufferCount);119+ t.is(subprocess.listenerCount('disconnect'), bufferCount);120 121 const promise = iterateAllMessages(subprocess);115- t.is(subprocess.listenerCount('message'), 1);116- t.is(subprocess.listenerCount('disconnect'), 1);122+ t.is(subprocess.listenerCount('message'), bufferCount + 1);123+ t.is(subprocess.listenerCount('disconnect'), bufferCount + 1);124 t.deepEqual(await promise, [foobarString]);125 126 t.is(subprocess.listenerCount('message'), 0);127 t.is(subprocess.listenerCount('disconnect'), 0);121-});128+};129 123-test('"error" event interrupts subprocess.getEachMessage()', async t => {124- const subprocess = execa('ipc-echo.js', {ipc: true});125- await subprocess.sendMessage(foobarString);126- const cause = new Error(foobarString);127- t.like(await t.throwsAsync(Promise.all([iterateAllMessages(subprocess), subprocess.emit('error', cause)])), {cause});128- t.like(await t.throwsAsync(subprocess), {cause});129-});130+test('Cleans up subprocess.getEachMessage() listeners, buffer false', testCleanupListeners, false);131+test('Cleans up subprocess.getEachMessage() listeners, buffer true', testCleanupListeners, true);modified:test/ipc/get-one.js+137 added-30 removed
1 import {once} from 'node:events';2+import {setTimeout} from 'node:timers/promises';3 import test from 'ava';4 import {execa} from '../../index.js';5 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6 import {foobarString} from '../helpers/input.js';7+import {iterateAllMessages} from '../helpers/ipc.js';8 9 setFixtureDirectory();10 9-test('subprocess.getOneMessage() keeps the subprocess alive', async t => {10- const subprocess = execa('ipc-echo-twice.js', {ipc: true});11+const getOneSubprocessMessage = subprocess => subprocess.getOneMessage();12+13+const testKeepAlive = async (t, buffer) => {14+ const subprocess = execa('ipc-echo-twice.js', {ipc: true, buffer});15 await subprocess.sendMessage(foobarString);16 t.is(await subprocess.getOneMessage(), foobarString);17 await subprocess.sendMessage(foobarString);18 t.is(await subprocess.getOneMessage(), foobarString);19 await subprocess;16-});20+};21 18-test('Buffers initial message to subprocess', async t => {19- const subprocess = execa('ipc-echo-wait.js', {ipc: true});22+test('subprocess.getOneMessage() keeps the subprocess alive, buffer false', testKeepAlive, false);23+test('subprocess.getOneMessage() keeps the subprocess alive, buffer true', testKeepAlive, true);24+25+const testBufferInitial = async (t, buffer) => {26+ const subprocess = execa('ipc-echo-wait.js', {ipc: true, buffer});27 await subprocess.sendMessage(foobarString);28 t.is(await subprocess.getOneMessage(), foobarString);29 await subprocess;23-});30+};31 32+test('Buffers initial message to subprocess, buffer false', testBufferInitial, false);33+test('Buffers initial message to subprocess, buffer true', testBufferInitial, true);34+25-test('Buffers initial message to current process', async t => {26- const subprocess = execa('ipc-send-print.js', {ipc: true});35+test('Buffers initial message to current process, buffer false', async t => {36+ const subprocess = execa('ipc-send-print.js', {ipc: true, buffer: false});37 const [chunk] = await once(subprocess.stdout, 'data');38 t.is(chunk.toString(), '.');39 t.is(await subprocess.getOneMessage(), foobarString);40 await subprocess.sendMessage('.');41 await subprocess;42 });43 44+test('Does not buffer initial message to current process, buffer true', async t => {45+ const subprocess = execa('ipc-send-print.js', {ipc: true});46+ const [chunk] = await once(subprocess.stdout, 'data');47+ t.is(chunk.toString(), '.');48+ t.is(await Promise.race([setTimeout(1e3), subprocess.getOneMessage()]), undefined);49+ await subprocess.sendMessage('.');50+ const {ipc} = await subprocess;51+ t.deepEqual(ipc, [foobarString]);52+});53+54 const HIGH_CONCURRENCY_COUNT = 100;55 36-test.serial('Can retrieve initial IPC messages under heavy load', async t => {56+test.serial('Can retrieve initial IPC messages under heavy load, buffer false', async t => {57 await Promise.all(58 Array.from({length: HIGH_CONCURRENCY_COUNT}, async (_, index) => {39- const subprocess = execa('ipc-send-argv.js', [`${index}`], {ipc: true});59+ const subprocess = execa('ipc-send-argv.js', [`${index}`], {ipc: true, buffer: false});60 t.is(await subprocess.getOneMessage(), `${index}`);61 await subprocess;62 }),63 );64 });65 46-test('subprocess.getOneMessage() can be called twice at the same time', async t => {47- const subprocess = execa('ipc-send.js', {ipc: true});66+test.serial('Can retrieve initial IPC messages under heavy load, buffer true', async t => {67+ await Promise.all(68+ Array.from({length: HIGH_CONCURRENCY_COUNT}, async (_, index) => {69+ const {ipc} = await execa('ipc-send-argv.js', [`${index}`], {ipc: true});70+ t.deepEqual(ipc, [`${index}`]);71+ }),72+ );73+});74+75+const testTwice = async (t, buffer) => {76+ const subprocess = execa('ipc-send.js', {ipc: true, buffer});77 t.deepEqual(78 await Promise.all([subprocess.getOneMessage(), subprocess.getOneMessage()]),79 [foobarString, foobarString],80 );81 await subprocess;53-});82+};83 55-test('Cleans up subprocess.getOneMessage() listeners', async t => {56- const subprocess = execa('ipc-send.js', {ipc: true});84+test('subprocess.getOneMessage() can be called twice at the same time, buffer false', testTwice, false);85+test('subprocess.getOneMessage() can be called twice at the same time, buffer true', testTwice, true);86 58- t.is(subprocess.listenerCount('message'), 0);59- t.is(subprocess.listenerCount('disconnect'), 0);87+const testCleanupListeners = async (t, buffer) => {88+ const subprocess = execa('ipc-send.js', {ipc: true, buffer});89+ const bufferCount = buffer ? 1 : 0;90 91+ t.is(subprocess.listenerCount('message'), bufferCount);92+ t.is(subprocess.listenerCount('disconnect'), bufferCount);93+94 const promise = subprocess.getOneMessage();62- t.is(subprocess.listenerCount('message'), 1);63- t.is(subprocess.listenerCount('disconnect'), 0);95+ t.is(subprocess.listenerCount('message'), bufferCount + 1);96+ t.is(subprocess.listenerCount('disconnect'), bufferCount + 1);97 t.is(await promise, foobarString);98 99+ t.is(subprocess.listenerCount('message'), bufferCount);100+ t.is(subprocess.listenerCount('disconnect'), bufferCount);101+102+ await subprocess;103+104 t.is(subprocess.listenerCount('message'), 0);105 t.is(subprocess.listenerCount('disconnect'), 0);106+};107 69- await subprocess;70-});108+test('Cleans up subprocess.getOneMessage() listeners, buffer false', testCleanupListeners, false);109+test('Cleans up subprocess.getOneMessage() listeners, buffer true', testCleanupListeners, true);110 72-test('"error" event interrupts subprocess.getOneMessage()', async t => {73- const subprocess = execa('ipc-echo.js', {ipc: true});111+test('"error" event interrupts result.ipc', async t => {112+ const subprocess = execa('ipc-echo-twice.js', {ipc: true});113 await subprocess.sendMessage(foobarString);114+ t.is(await subprocess.getOneMessage(), foobarString);115+116 const cause = new Error(foobarString);76- t.is(await t.throwsAsync(Promise.all([subprocess.getOneMessage(), subprocess.emit('error', cause)])), cause);77- t.like(await t.throwsAsync(subprocess), {cause});117+ subprocess.emit('error', cause);118+ const error = await t.throwsAsync(subprocess);119+ t.is(error.cause, cause);120+ t.deepEqual(error.ipc, [foobarString]);121 });122 80-const testSubprocessError = async (t, fixtureName) => {81- const subprocess = execa(fixtureName, {ipc: true});82- t.like(await subprocess.getOneMessage(), {message: 'foobar'});123+const testParentDisconnect = async (t, buffer) => {124+ const subprocess = execa('ipc-echo-twice.js', {ipc: true, buffer});125+ await subprocess.sendMessage(foobarString);126+ t.is(await subprocess.getOneMessage(), foobarString);127+128+ subprocess.disconnect();129+130+ const {exitCode, isTerminated, message} = await t.throwsAsync(subprocess);131+ t.is(exitCode, 1);132+ t.false(isTerminated);133+ if (buffer) {134+ t.true(message.includes('Error: getOneMessage() could not complete'));135+ }136+};137+138+test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer false', testParentDisconnect, false);139+test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer true', testParentDisconnect, true);140+141+const testSubprocessDisconnect = async (t, buffer) => {142+ const subprocess = execa('empty.js', {ipc: true, buffer});143+ await t.throwsAsync(subprocess.getOneMessage(), {144+ message: /subprocess\.getOneMessage\(\) could not complete/,145+ });146 await subprocess;147 };148 86-test('"error" event interrupts exports.getOneMessage()', testSubprocessError, 'ipc-process-error.js');87-test('"error" event interrupts exports.getEachMessage()', testSubprocessError, 'ipc-iterate-error.js');149+test('Subprocess exit interrupts disconnect.getOneMessage(), buffer false', testSubprocessDisconnect, false);150+test('Subprocess exit interrupts disconnect.getOneMessage(), buffer true', testSubprocessDisconnect, true);151+152+const testParentError = async (t, getMessages, useCause, buffer) => {153+ const subprocess = execa('ipc-echo.js', {ipc: true, buffer});154+ await subprocess.sendMessage(foobarString);155+ const promise = getMessages(subprocess);156+157+ const cause = new Error(foobarString);158+ subprocess.emit('error', cause);159+160+ const ipcError = await t.throwsAsync(promise);161+ t.is(useCause ? ipcError.cause : ipcError, cause);162+163+ const error = await t.throwsAsync(subprocess);164+ t.is(error.exitCode, 1);165+ t.false(error.isTerminated);166+ t.is(error.cause, cause);167+ if (buffer) {168+ t.true(error.message.includes('Error: getOneMessage() cannot be used'));169+ }170+};171+172+test('"error" event interrupts subprocess.getOneMessage(), buffer false', testParentError, getOneSubprocessMessage, false, false);173+test('"error" event interrupts subprocess.getOneMessage(), buffer true', testParentError, getOneSubprocessMessage, false, true);174+test('"error" event interrupts subprocess.getEachMessage(), buffer false', testParentError, iterateAllMessages, true, false);175+test('"error" event interrupts subprocess.getEachMessage(), buffer true', testParentError, iterateAllMessages, true, true);176+177+const testSubprocessError = async (t, fixtureName, buffer) => {178+ const subprocess = execa(fixtureName, {ipc: true, buffer});179+180+ const ipcError = await t.throwsAsync(subprocess.getOneMessage());181+ t.true(ipcError.message.includes('subprocess.getOneMessage() could not complete'));182+183+ const {exitCode, isTerminated, message} = await t.throwsAsync(subprocess);184+ t.is(exitCode, 1);185+ t.false(isTerminated);186+ if (buffer) {187+ t.true(message.includes(`Error: ${foobarString}`));188+ }189+};190+191+test('"error" event interrupts exports.getOneMessage(), buffer false', testSubprocessError, 'ipc-process-error.js', false);192+test('"error" event interrupts exports.getOneMessage(), buffer true', testSubprocessError, 'ipc-process-error.js', true);193+test('"error" event interrupts exports.getEachMessage(), buffer false', testSubprocessError, 'ipc-iterate-error.js', false);194+test('"error" event interrupts exports.getEachMessage(), buffer true', testSubprocessError, 'ipc-iterate-error.js', true);added:test/ipc/messages.js+58 added
1+import test from 'ava';2+import {execa, execaSync} from '../../index.js';3+import {setFixtureDirectory} from '../helpers/fixtures-directory.js';4+import {foobarString, foobarArray} from '../helpers/input.js';5+6+setFixtureDirectory();7+8+const testResultIpc = async (t, options) => {9+ const {ipc} = await execa('ipc-send-twice.js', {...options, ipc: true});10+ t.deepEqual(ipc, foobarArray);11+};12+13+test('Sets result.ipc', testResultIpc, {});14+test('Sets result.ipc, fd-specific buffer', testResultIpc, {buffer: {stdout: false}});15+16+const testResultNoBuffer = async (t, options) => {17+ const {ipc} = await execa('ipc-send.js', {...options, ipc: true});18+ t.deepEqual(ipc, []);19+};20+21+test('Sets empty result.ipc if buffer is false', testResultNoBuffer, {buffer: false});22+test('Sets empty result.ipc if buffer is false, fd-specific buffer', testResultNoBuffer, {buffer: {ipc: false}});23+24+test('Sets empty result.ipc if ipc is false', async t => {25+ const {ipc} = await execa('empty.js');26+ t.deepEqual(ipc, []);27+});28+29+test('Sets empty result.ipc, sync', t => {30+ const {ipc} = execaSync('empty.js');31+ t.deepEqual(ipc, []);32+});33+34+const testErrorIpc = async (t, options) => {35+ const {ipc} = await t.throwsAsync(execa('ipc-send-fail.js', {...options, ipc: true}));36+ t.deepEqual(ipc, [foobarString]);37+};38+39+test('Sets error.ipc', testErrorIpc, {});40+test('Sets error.ipc, fd-specific buffer', testErrorIpc, {buffer: {stdout: false}});41+42+const testErrorNoBuffer = async (t, options) => {43+ const {ipc} = await t.throwsAsync(execa('ipc-send-fail.js', {...options, ipc: true}));44+ t.deepEqual(ipc, []);45+};46+47+test('Sets empty error.ipc if buffer is false', testErrorNoBuffer, {buffer: false});48+test('Sets empty error.ipc if buffer is false, fd-specific buffer', testErrorNoBuffer, {buffer: {ipc: false}});49+50+test('Sets empty error.ipc if ipc is false', async t => {51+ const {ipc} = await t.throwsAsync(execa('fail.js'));52+ t.deepEqual(ipc, []);53+});54+55+test('Sets empty error.ipc, sync', t => {56+ const {ipc} = t.throws(() => execaSync('fail.js'));57+ t.deepEqual(ipc, []);58+});modified:test/ipc/send.js+28 added-2 removed
37 unmodified lines38 test('Handles backpressure', async t => {39 const subprocess = execa('ipc-iterate.js', {ipc: true});40 await subprocess.sendMessage(BIG_PAYLOAD_SIZE);41 t.true(subprocess.send(foobarString));42- const {stdout} = await subprocess;43- t.is(stdout, BIG_PAYLOAD_SIZE);42+ const {ipc} = await subprocess;43+ t.deepEqual(ipc, [BIG_PAYLOAD_SIZE]);44 });45+46+test('Disconnects IPC on exports.sendMessage() error', async t => {47+ const subprocess = execa('ipc-echo-twice.js', {ipc: true});48+ await subprocess.sendMessage(foobarString);49+ t.is(await subprocess.getOneMessage(), foobarString);50+51+ await t.throwsAsync(subprocess.sendMessage(0n), {52+ message: /subprocess.sendMessage\(\)'s argument type is invalid/,53+ });54+55+ const {exitCode, isTerminated, stderr} = await t.throwsAsync(subprocess);56+ t.is(exitCode, 1);57+ t.false(isTerminated);58+ t.true(stderr.includes('Error: getOneMessage() could not complete'));59+});60+61+test('Disconnects IPC on subprocess.sendMessage() error', async t => {62+ const subprocess = execa('ipc-send-error.js', {ipc: true});63+ const ipcError = await t.throwsAsync(subprocess.getOneMessage());64+ t.true(ipcError.message.includes('subprocess.getOneMessage() could not complete'));65+66+ const {exitCode, isTerminated, stderr} = await t.throwsAsync(subprocess);67+ t.is(exitCode, 1);68+ t.false(isTerminated);69+ t.true(stderr.includes('sendMessage()\'s argument type is invalid'));70+});modified:test/methods/node.js+2 added-4 removed
295 unmodified lines296 });297 298 test('The "serialization" option can be set to "json"', async t => {299 const subprocess = execa('node', ['ipc-echo.js'], {ipc: true, serialization: 'json'});300- await t.throwsAsync(() => subprocess.sendMessage([0n]), {message: /serialize a BigInt/});301- await subprocess.sendMessage(0);302- t.is(await subprocess.getOneMessage(), 0);303- await subprocess;300+ await t.throwsAsync(subprocess.sendMessage([0n]), {message: /serialize a BigInt/});301+ await t.throwsAsync(subprocess);302 });modified:test/return/message.js+27 added-1 removed
1 import test from 'ava';2 import {execa, execaSync} from '../../index.js';3 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';4 import {fullStdio, getStdio} from '../helpers/stdio.js';5-import {foobarString} from '../helpers/input.js';5+import {foobarString, foobarObject, foobarObjectInspect} from '../helpers/input.js';6 import {QUOTE} from '../helpers/verbose.js';7 import {noopGenerator, outputObjectGenerator} from '../helpers/generator.js';8 9 setFixtureDirectory();83 unmodified lines93 test('Original error.message is kept', async t => {94 const {originalMessage} = await t.throwsAsync(execa('noop.js', {uid: true}));95 t.is(originalMessage, 'The "options.uid" property must be int32. Received type boolean (true)');96 });97+98+const testIpcMessage = async (t, doubles, input, returnedMessage) => {99+ const fixtureName = doubles ? 'ipc-echo-twice-fail.js' : 'ipc-echo-fail.js';100+ const subprocess = execa(fixtureName, {ipc: true});101+ await subprocess.sendMessage(input);102+ const {exitCode, message, ipc} = await t.throwsAsync(subprocess);103+ t.is(exitCode, 1);104+ t.true(message.endsWith(`\n\n${doubles ? `${returnedMessage}\n${returnedMessage}` : returnedMessage}`));105+ t.deepEqual(ipc, doubles ? [input, input] : [input]);106+};107+108+test('error.message contains IPC messages, single string', testIpcMessage, false, foobarString, foobarString);109+test('error.message contains IPC messages, two strings', testIpcMessage, true, foobarString, foobarString);110+test('error.message contains IPC messages, single object', testIpcMessage, false, foobarObject, foobarObjectInspect);111+test('error.message contains IPC messages, two objects', testIpcMessage, true, foobarObject, foobarObjectInspect);112+test('error.message contains IPC messages, multiline string', testIpcMessage, false, `${foobarString}\n${foobarString}`, `${foobarString}\n${foobarString}`);113+test('error.message contains IPC messages, control characters', testIpcMessage, false, '\0', '\\u0000');114+115+test('error.message does not contain IPC messages, buffer false', async t => {116+ const subprocess = execa('ipc-echo-fail.js', {ipc: true, buffer: false});117+ await subprocess.sendMessage(foobarString);118+ const {exitCode, message, ipc} = await t.throwsAsync(subprocess);119+ t.is(exitCode, 1);120+ t.true(message.endsWith('ipc-echo-fail.js'));121+ t.deepEqual(ipc, []);122+});modified:test/return/output.js+33 added-8 removed
1 unmodified line2 import {execa, execaSync} from '../../index.js';3 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';4 import {fullStdio, getStdio} from '../helpers/stdio.js';5 import {foobarString} from '../helpers/input.js';6+import {7+ getEarlyErrorSubprocess,8+ getEarlyErrorSubprocessSync,9+ expectedEarlyError,10+ expectedEarlyErrorSync,11+} from '../helpers/early-error.js';12 13 setFixtureDirectory();14 15 const testOutput = async (t, fdNumber, execaMethod) => {72 unmodified lines88 const {stdio} = await t.throwsAsync(execa('fail.js', {input: 'test'}));89 t.is(stdio[0], undefined);90 });91 86-// `error.code` is OS-specific here87-const SPAWN_ERROR_CODES = new Set(['EINVAL', 'ENOTSUP', 'EPERM']);88-89-const testSpawnError = async (t, execaMethod) => {90- const {code, stdout, stderr, stdio, all} = await execaMethod('empty.js', {uid: -1, all: true, reject: false});91- t.true(SPAWN_ERROR_CODES.has(code));92+const validateSpawnErrorStdio = (t, {stdout, stderr, stdio, all}) => {93 t.is(stdout, undefined);94 t.is(stderr, undefined);95 t.is(all, undefined);96 t.deepEqual(stdio, [undefined, undefined, undefined]);97 };98 98-test('stdout/stderr/all/stdio on subprocess spawning errors', testSpawnError, execa);99-test('stdout/stderr/all/stdio on subprocess spawning errors, sync', testSpawnError, execaSync);99+test('stdout/stderr/all/stdio on subprocess spawning errors', async t => {100+ const error = await t.throwsAsync(getEarlyErrorSubprocess({all: true}));101+ t.like(error, expectedEarlyError);102+ validateSpawnErrorStdio(t, error);103+});104 105+test('stdout/stderr/all/stdio on subprocess spawning errors, sync', t => {106+ const error = t.throws(() => getEarlyErrorSubprocessSync({all: true}));107+ t.like(error, expectedEarlyErrorSync);108+ validateSpawnErrorStdio(t, error);109+});110+111 const testErrorOutput = async (t, execaMethod) => {112 const {failed, stdout, stderr, stdio} = await execaMethod('echo-fail.js', {...fullStdio, reject: false});113 t.true(failed);114 t.is(stdout, 'stdout');2 unmodified lines117 };118 119 test('error.stdout/stderr/stdio is defined', testErrorOutput, execa);120 test('error.stdout/stderr/stdio is defined, sync', testErrorOutput, execaSync);121+122+test('ipc on subprocess spawning errors', async t => {123+ const error = await t.throwsAsync(getEarlyErrorSubprocess({ipc: true}));124+ t.like(error, expectedEarlyError);125+ t.deepEqual(error.ipc, []);126+});127+128+const testEarlyErrorNoIpc = async (t, options) => {129+ const error = await t.throwsAsync(getEarlyErrorSubprocess(options));130+ t.like(error, expectedEarlyError);131+ t.deepEqual(error.ipc, []);132+};133+134+test('ipc on subprocess spawning errors, ipc false', testEarlyErrorNoIpc, {ipc: false});135+test('ipc on subprocess spawning errors, buffer false', testEarlyErrorNoIpc, {buffer: false});modified:test/return/result.js+2 added
23 unmodified lines24 'stdout',25 'stderr',26 'all',27 'stdio',28+ 'ipc',29 'pipedFrom',30 ]);31 };32 20 unmodified lines53 'stdout',54 'stderr',55 'all',56 'stdio',57+ 'ipc',58 'pipedFrom',59 ]);60 };61 82 unmodified linesmodified:test/stdio/node-stream-custom.js+3 added-1 removed
9 unmodified lines10 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';11 import {getStdio} from '../helpers/stdio.js';12 import {foobarString} from '../helpers/input.js';13 import {noopReadable, noopWritable} from '../helpers/stream.js';14+import {getEarlyErrorSubprocess, expectedEarlyError} from '../helpers/early-error.js';15 16 setFixtureDirectory();17 18 const testLazyFileReadable = async (t, fdNumber) => {68 unmodified lines87 t.is(error.cause, cause);88 });89 90 const testStreamEarlyExit = async (t, stream, streamName) => {90- await t.throwsAsync(execa('noop.js', {[streamName]: [stream, 'pipe'], uid: -1}));91+ const error = await t.throwsAsync(getEarlyErrorSubprocess({[streamName]: [stream, 'pipe']}));92+ t.like(error, expectedEarlyError);93 t.true(stream.destroyed);94 };95 96 test('Input streams are canceled on early subprocess exit', testStreamEarlyExit, noopReadable(), 'stdin');64 unmodified linesmodified:test/transform/generator-error.js+3 added-1 removed
3 unmodified lines4 import {foobarString} from '../helpers/input.js';5 import {noopGenerator, infiniteGenerator, convertTransformToFinal} from '../helpers/generator.js';6 import {generatorsMap} from '../helpers/map.js';7 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';8+import {getEarlyErrorSubprocess, expectedEarlyError} from '../helpers/early-error.js';9 10 setFixtureDirectory();11 12 const assertProcessError = async (t, type, execaMethod, getSubprocess) => {72 unmodified lines85 test('Generators are destroyed on subprocess error, sync', testGeneratorDestroy, noopGenerator(false));86 test('Generators are destroyed on subprocess error, async', testGeneratorDestroy, infiniteGenerator());87 88 test('Generators are destroyed on early subprocess exit', async t => {88- await t.throwsAsync(execa('noop.js', {stdout: infiniteGenerator(), uid: -1}));89+ const error = await t.throwsAsync(getEarlyErrorSubprocess({stdout: infiniteGenerator()}));90+ t.like(error, expectedEarlyError);91 });added:test-d/return/result-ipc.ts+47 added
1+import {expectAssignable, expectType} from 'tsd';2+import {3+ execa,4+ execaSync,5+ type Result,6+ type SyncResult,7+ type ExecaError,8+ type ExecaSyncError,9+} from '../../index.js';10+11+const ipcResult = await execa('unicorns', {ipc: true});12+expectType<unknown[]>(ipcResult.ipc);13+14+const ipcFdResult = await execa('unicorns', {ipc: true, buffer: {stdout: false}});15+expectType<unknown[]>(ipcFdResult.ipc);16+17+const falseIpcResult = await execa('unicorns', {ipc: false});18+expectType<[]>(falseIpcResult.ipc);19+20+const noIpcResult = await execa('unicorns');21+expectType<[]>(noIpcResult.ipc);22+23+const noBufferResult = await execa('unicorns', {ipc: true, buffer: false});24+expectType<[]>(noBufferResult.ipc);25+26+const noBufferFdResult = await execa('unicorns', {ipc: true, buffer: {ipc: false}});27+expectType<[]>(noBufferFdResult.ipc);28+29+const syncResult = execaSync('unicorns');30+expectType<[]>(syncResult.ipc);31+32+expectType<unknown[] | []>({} as Result['ipc']);33+expectAssignable<unknown[]>({} as Result['ipc']);34+expectType<[]>({} as unknown as SyncResult['ipc']);35+36+const ipcError = new Error('.') as ExecaError<{ipc: true}>;37+expectType<unknown[]>(ipcError.ipc);38+39+const ipcFalseError = new Error('.') as ExecaError<{ipc: false}>;40+expectType<[]>(ipcFalseError.ipc);41+42+const asyncError = new Error('.') as ExecaError;43+expectType<unknown[] | []>(asyncError.ipc);44+expectAssignable<unknown[]>(asyncError.ipc);45+46+const syncError = new Error('.') as ExecaSyncError;47+expectType<[]>(syncError.ipc);added:types/return/result-ipc.d.ts+21 added
1+import type {FdSpecificOption} from '../arguments/specific.js';2+import type {CommonOptions} from '../arguments/options.js';3+4+// `result.ipc`5+// This is empty unless the `ipc` option is `true`.6+// Also, this is empty if the `buffer` option is `false`.7+export type ResultIpc<8+ IsSync extends boolean,9+ OptionsType extends CommonOptions,10+> = IsSync extends true11+ ? []12+ : ResultIpcAsync<FdSpecificOption<OptionsType['buffer'], 'ipc'>, OptionsType['ipc']>;13+14+type ResultIpcAsync<15+ BufferOption extends boolean | undefined,16+ IpcOption extends boolean | undefined,17+> = BufferOption extends false18+ ? []19+ : IpcOption extends true20+ ? unknown[]21+ : [];modified:types/return/result.d.ts+8 added
3 unmodified lines4 import type {ErrorProperties} from './final-error.js';5 import type {ResultAll} from './result-all.js';6 import type {ResultStdioArray} from './result-stdio.js';7 import type {ResultStdioNotAll} from './result-stdout.js';8+import type {ResultIpc} from './result-ipc.js';9 10 export declare abstract class CommonResult<11 IsSync extends boolean,12 OptionsType extends CommonOptions,36 unmodified lines49 */50 stdio: ResultStdioArray<OptionsType>;51 52 /**53+ All the messages sent by the subprocess to the current process.54+55+ This is empty unless the `ipc` option is `true`. Also, this is empty if the `buffer` option is `false`.56+ */57+ ipc: ResultIpc<IsSync, OptionsType>;58+59+ /**60 Results of the other subprocesses that were piped into this subprocess.61 62 This array is initially empty and is populated each time the `subprocess.pipe()` method resolves.63 */130 unmodified lines