Skip to content
Myr

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

43 files+725 added−146 removed

modified:docs/api.md+10 added
465 unmodified lines
466Items are arrays when their corresponding `stdio` option is a [transform in object mode](transform.md#object-mode).467468[More info.](output.md#additional-file-descriptors)469470### result.ipc471472_Type_: `unknown[]`473474All the messages [sent by the subprocess](#sendmessagemessage) to the current process.475476This is empty unless the [`ipc`](#optionsipc) option is `true`. Also, this is empty if the [`buffer`](#optionsbuffer) option is `false`.477478[More info.](ipc.md#retrieve-all-messages)479480### result.pipedFrom481482_Type:_ [`Array<Result | ExecaError>`](#result)483
611 unmodified lines
modified:docs/errors.md+2 added-2 removed
modified:docs/ipc.md+28 added
65 unmodified lines
66 await sendMessage(message + 1);67}68```6970## Retrieve all messages7172The [`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).7374```js75// main.js76import {execaNode} from 'execa';7778const {ipc} = await execaNode`build.js`;79console.log(ipc[0]); // {kind: 'start', timestamp: date}80console.log(ipc[1]); // {kind: 'stop', timestamp: date}81```8283```js84// build.js85import {sendMessage} from 'execa';8687await sendMessage({kind: 'start', timestamp: new Date()});88await runBuild();89await sendMessage({kind: 'stop', timestamp: new Date()});90```9192## Message type9394By 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 lines
98```js99const subprocess = execaNode({serialization: 'json'})`child.js`;100```101102## Debugging103104When 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).105106Also, 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).107108<hr>109110[**Next**: 🐛 Debugging](debugging.md)\111[**Previous**: ⏳️ Streams](streams.md)\
1 unmodified line
modified:docs/output.md+26 added-3 removed
53 unmodified lines
54// Or:55await execa({stdout: 1, stderr: 1})`npm run build`;56```5758## Any output type5960If 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.6162```js63// main.js64import {execaNode} from 'execa';6566const {ipc} = await execaNode`build.js`;67console.log(ipc[0]); // {kind: 'start', timestamp: date}68console.log(ipc[1]); // {kind: 'stop', timestamp: date}69```7071```js72// build.js73import {sendMessage} from 'execa';7475await sendMessage({kind: 'start', timestamp: new Date()});76await runBuild();77await sendMessage({kind: 'stop', timestamp: new Date()});78```7980## Multiple targets8182The 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 lines
161## Big output162163To prevent high memory consumption, a maximum output size can be set using the [`maxBuffer`](api.md#optionsmaxbuffer) option. It defaults to 100MB.164143When 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).165When 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).166167This 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.173174```js175try {176 await execa({maxBuffer: 1_000_000})`npm run build`;
9 unmodified lines
186```187188## Low memory189167When 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.190When 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.191169This 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.192This 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.193194<hr>195196[**Next**: 📃 Text lines](lines.md)\
2 unmodified lines
modified:lib/io/max-buffer.js+18 added
1import {MaxBufferError} from 'get-stream';2import {disconnect} from '../ipc/validation.js';3import {getStreamName} from '../utils/standard-stream.js';45// 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 lines
3435 return 'characters';36};3738// Check the `maxBuffer` option with `result.ipc`39export const checkIpcMaxBuffer = (subprocess, ipcMessages, maxBuffer) => {40 if (ipcMessages.length !== maxBuffer) {41 return;42 }4344 disconnect(subprocess);45 const error = new MaxBufferError();46 error.maxBufferInfo = {fdNumber: 'ipc'};47 throw error;48};4950// Error message when `maxBuffer` is hit51export const getMaxBufferMessage = (error, maxBuffer) => {52 const {streamName, threshold, unit} = getMaxBufferInfo(error, maxBuffer);53 return `Command's ${streamName} was larger than ${threshold} ${unit}`;
5 unmodified lines
59 }6061 const {maxBufferInfo: {fdNumber, unit}} = error;62 delete error.maxBufferInfo;6364 if (fdNumber === 'ipc') {65 return {streamName: 'IPC output', threshold: maxBuffer.at(-1), unit: 'messages'};66 }6768 return {streamName: getStreamName(fdNumber), threshold: maxBuffer[fdNumber], unit};69};7071// The only way to apply `maxBuffer` with `spawnSync()` is to use the native `maxBuffer` option Node.js provides.
18 unmodified lines
modified:lib/ipc/get-each.js+12 added-2 removed
modified:lib/ipc/get-one.js+31 added-5 removed
1import {once} from 'node:events';2import {validateIpcOption, validateConnection} from './validation.js';2import {3 validateIpcOption,4 validateConnection,5 disconnect,6 throwOnEarlyDisconnect,7} from './validation.js';89// Like `[sub]process.once('message')` but promise-based10export const getOneMessage = ({anyProcess, isSubprocess, ipc}) => {11 const methodName = 'getOneMessage';12 validateIpcOption(methodName, isSubprocess, ipc);13 validateConnection(methodName, isSubprocess, anyProcess.channel !== null);1410 return onceMessage(anyProcess);15 return onceMessage(anyProcess, isSubprocess, methodName);16};1713const onceMessage = async anyProcess => {14 const [message] = await once(anyProcess, 'message');15 return message;18const 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};3839const 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
1import {checkIpcMaxBuffer} from '../io/max-buffer.js';2import {shouldLogIpc, logIpcMessage} from '../verbose/ipc.js';3import {loopOnMessages} from './get-each.js';45// Iterate through IPC messages sent by the subprocess5export const waitForIpcMessages = async (subprocess, ipc, verboseInfo) => {6 if (!ipc || !shouldLogIpc(verboseInfo)) {7 return;6export 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 }1718 const isVerbose = shouldLogIpc(verboseInfo);19 const buffer = bufferArray.at(-1);20 const maxBuffer = maxBufferArray.at(-1);2122 if (!isVerbose && !buffer) {23 return ipcMessages;24 }2526 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 }3637 if (isVerbose) {16 logIpcMessage(message, verboseInfo);38 logIpcMessage(message, verboseInfo);39 }40 }4142 return ipcMessages;43};
modified:lib/ipc/send.js+9 added-2 removed
1import {2 validateIpcOption,3 validateConnection,4 handleSerializationError,5 disconnect,6} from './validation.js';78// Like `[sub]process.send()` but promise-based.9// We do not `await subprocess` during `.sendMessage()` nor `.getOneMessage()` since those methods are transient.
3 unmodified lines
13 const methodName = 'sendMessage';14 validateIpcOption(methodName, isSubprocess, ipc);15 validateConnection(methodName, isSubprocess, anyProcess.connected);1616 return sendOneMessage(anyProcessSend, isSubprocess, message);17 return sendOneMessage({18 anyProcess,19 anyProcessSend,20 isSubprocess,21 message,22 });23};2419const sendOneMessage = async (anyProcessSend, isSubprocess, message) => {25const 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 lines
12 throw new Error(`${getNamespaceName(isSubprocess)}${methodName}() cannot be used: the ${getOtherProcessName(isSubprocess)} has already exited or disconnected.`);13 }14};1516// When `getOneMessage()` could not complete due to an early disconnection17export const throwOnEarlyDisconnect = (methodName, isSubprocess) => {18 throw new Error(`${getNamespaceName(isSubprocess)}${methodName}() could not complete: the ${getOtherProcessName(isSubprocess)} exited or disconnected.`);19};2021const getNamespaceName = isSubprocess => isSubprocess ? '' : 'subprocess.';2223const getOtherProcessName = isSubprocess => isSubprocess ? 'parent process' : 'subprocess';24
24 unmodified lines
49 'circular structure',50 // Message has cycles inside toJSON(), with `serialization: 'json'`51 'call stack size exceeded',52];5354// 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.57export const disconnect = anyProcess => {58 if (anyProcess.connected) {59 anyProcess.disconnect();60 }61};
modified:lib/methods/main-async.js+11 added-2 removed
130 unmodified lines
131// Asynchronous logic, as opposed to the previous logic which can be run synchronously, i.e. can be returned to user right away132const handlePromise = async ({subprocess, options, startTime, verboseInfo, fileDescriptors, originalStreams, command, escapedCommand, onInternalError, controller}) => {133 const context = {timedOut: false};134135 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 lines
158 exitCode,159 signal,160 stdio,161 all,162 ipcMessages,163 context,164 options,165 command,166 escapedCommand,
1 unmodified line
168 });169 return handleResult(result, verboseInfo, options);170};171165const getAsyncResult = ({errorInfo, exitCode, signal, stdio, all, context, options, command, escapedCommand, startTime}) => 'error' in errorInfo172const 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 lines
180 exitCode,181 signal,182 stdio,183 all,184 ipcMessages,185 options,186 startTime,187 isSync: false,188 })
1 unmodified line
190 command,191 escapedCommand,192 stdio,193 all,194 ipcMessages,195 options,196 startTime,197 });
modified:lib/methods/main-sync.js+2 added
139 unmodified lines
140 command,141 escapedCommand,142 stdio,143 all,144 ipcMessages: [],145 options,146 startTime,147 })148 : makeError({
6 unmodified lines
155 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 lines
57 stripFinalNewline,58 verboseInfo,59 streamInfo,60 });61 const ipcMessages = [];62 const originalPromises = waitForOriginalStreams(originalStreams, subprocess, streamInfo);63 const customStreamsEndPromises = waitForCustomStreamsEnd(fileDescriptors, streamInfo);6465 try {
2 unmodified lines
68 {},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 lines
89 {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 lines
modified:lib/return/message.js+12 added-1 removed
1import {inspect} from 'node:util';2import stripFinalNewline from 'strip-final-newline';3import {isUint8Array, uint8ArrayToString} from '../utils/uint-array.js';4import {fixCwdError} from '../arguments/cwd.js';5import {escapeLines} from '../arguments/escape.js';
3 unmodified lines
9// Computes `error.message`, `error.shortMessage` and `error.originalMessage`10export const createMessages = ({11 stdio,12 all,13 ipcMessages,14 originalError,15 signal,16 signalDescription,17 exitCode,
21 unmodified lines
39 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 lines
91 const escapedOriginalMessage = escapeLines(fixCwdError(originalMessage, cwd));92 return escapedOriginalMessage === '' ? undefined : escapedOriginalMessage;93};9495const serializeIpcMessage = ipcMessage => typeof ipcMessage === 'string'96 ? ipcMessage97 : inspect(ipcMessage);9899const serializeMessagePart = messagePart => Array.isArray(messagePart)100 ? messagePart.map(messageItem => stripFinalNewline(serializeMessageItem(messageItem))).filter(Boolean).join('\n')101 : serializeMessageItem(messagePart);102
11 unmodified lines
modified:lib/return/result.js+8 added
7 unmodified lines
8 command,9 escapedCommand,10 stdio,11 all,12 ipcMessages,13 options: {cwd},14 startTime,15}) => omitUndefinedProperties({16 command,
9 unmodified lines
26 stdout: stdio[1],27 stderr: stdio[2],28 all,29 stdio,30 ipc: ipcMessages,31 pipedFrom: [],32});3334// Object returned on subprocess failure before spawning
13 unmodified lines
48 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 lines
66 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 lines
101 signal,102 signalDescription,103 stdio,104 all,105 ipcMessages,106 cwd,107 originalMessage,108 shortMessage,109 }));
12 unmodified lines
122 signal,123 signalDescription,124 stdio,125 all,126 ipcMessages,127 cwd,128 originalMessage,129 shortMessage,130}) => omitUndefinedProperties({
15 unmodified lines
146 stdout: stdio[1],147 stderr: stdio[2],148 all,149 stdio,150 ipc: ipcMessages,151 pipedFrom: [],152});153154const omitUndefinedProperties = result => Object.fromEntries(Object.entries(result).filter(([, value]) => value !== undefined));
9 unmodified lines
added:test/fixtures/ipc-echo-fail.js+6 added
1#!/usr/bin/env node2import process from 'node:process';3import {sendMessage, getOneMessage} from '../../index.js';45await sendMessage(await getOneMessage());6process.exitCode = 1;
added:test/fixtures/ipc-echo-twice-fail.js+8 added
1#!/usr/bin/env node2import process from 'node:process';3import {sendMessage, getOneMessage} from '../../index.js';45const message = await getOneMessage();6await sendMessage(message);7await sendMessage(message);8process.exitCode = 1;
modified:test/fixtures/ipc-echo-twice.js+4 added-2 removed
1#!/usr/bin/env node2import {sendMessage, getOneMessage} from '../../index.js';34await sendMessage(await getOneMessage());5await sendMessage(await getOneMessage());4const message = await getOneMessage();5const secondMessagePromise = getOneMessage();6await sendMessage(message);7await sendMessage(await secondMessagePromise);
modified:test/fixtures/ipc-iterate-error.js+5 added-9 removed
1#!/usr/bin/env node2import process from 'node:process';3import {sendMessage, getEachMessage} from '../../index.js';3import {getEachMessage} from '../../index.js';4import {foobarString} from '../helpers/input.js';56// @todo: replace with Array.fromAsync(subprocess.getEachMessage()) after dropping support for Node <22.0.07const iterateAllMessages = async () => {
5 unmodified lines
13 return messages;14};1516const cause = new Error(foobarString);17try {18 await Promise.all([19 iterateAllMessages(),20 process.emit('error', cause),21 ]);17await 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 node2import process from 'node:process';3import {sendMessage, getEachMessage} from '../../index.js';4import {foobarString} from '../helpers/input.js';56await sendMessage(foobarString);78for await (const message of getEachMessage()) {9 if (message === foobarString) {10 break;11 }1213 process.stdout.write(`${message}`);14}
modified:test/fixtures/ipc-iterate-twice.js+2 added-3 removed
1#!/usr/bin/env node2import process from 'node:process';2import {sendMessage, getEachMessage} from '../../index.js';3import {foobarString} from '../helpers/input.js';45for (let index = 0; index < 2; index += 1) {
2 unmodified lines
8 if (message === foobarString) {9 break;10 }1113 process.stdout.write(message);12 await sendMessage(message);13 }1415 // 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 node2import process from 'node:process';3import {getEachMessage} from '../../index.js';2import {getEachMessage, sendMessage} from '../../index.js';3import {foobarString} from '../helpers/input.js';45for await (const message of getEachMessage()) {6 if (message === foobarString) {7 break;8 }911 process.stdout.write(`${message}`);10 await sendMessage(message);11}
modified:test/fixtures/ipc-process-error.js+5 added-9 removed
1#!/usr/bin/env node2import process from 'node:process';3import {sendMessage, getOneMessage} from '../../index.js';3import {getOneMessage} from '../../index.js';4import {foobarString} from '../helpers/input.js';56const cause = new Error(foobarString);7try {8 await Promise.all([9 getOneMessage(),10 process.emit('error', cause),11 ]);7await 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 node2import {sendMessage} from '../../index.js';34await sendMessage(0n);
deleted:test/fixtures/ipc-send-iterate.js-14 removed
1#!/usr/bin/env node2import process from 'node:process';3import {sendMessage, getEachMessage} from '../../index.js';4import {foobarString} from '../helpers/input.js';56await sendMessage(foobarString);78for await (const message of getEachMessage()) {9 if (message === foobarString) {10 break;11 }1213 process.stdout.write(`${message}`);14}
added:test/fixtures/ipc-send-twice-wait.js+7 added
1#!/usr/bin/env node2import {sendMessage, getOneMessage} from '../../index.js';3import {foobarString} from '../helpers/input.js';45await sendMessage(foobarString);6await sendMessage(foobarString);7await getOneMessage();
modified:test/helpers/input.js+2 added
1import {Buffer} from 'node:buffer';2import {inspect} from 'node:util';34const textEncoder = new TextEncoder();56export const foobarString = 'foobar';
10 unmodified lines
17export const foobarUppercaseUint8Array = textEncoder.encode(foobarUppercase);18export const foobarUppercaseHex = Buffer.from(foobarUppercase).toString('hex');19export const foobarObject = {foo: 'bar'};20export const foobarObjectString = JSON.stringify(foobarObject);21export 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.02export const iterateAllMessages = async subprocess => {3 const messages = [];4 for await (const message of subprocess.getEachMessage()) {5 messages.push(message);6 }78 return messages;9};
modified:test/io/max-buffer.js+25 added
4 unmodified lines
5import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6import {fullStdio} from '../helpers/stdio.js';7import {getEarlyErrorSubprocess} from '../helpers/early-error.js';8import {maxBuffer, assertErrorMessage} from '../helpers/max-buffer.js';9import {foobarString} from '../helpers/input.js';1011setFixtureDirectory();1213const maxBufferMessage = {message: /maxBuffer exceeded/};
252 unmodified lines
266 t.true(failed);267 t.false(isMaxBuffer);268});269270test('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});284285test('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);290291 const {ipc} = await subprocess;292 t.deepEqual(ipc, []);293});
modified:test/io/pipeline.js+3 added-1 removed
1import test from 'ava';2import {execa} from '../../index.js';3import {getStdio, STANDARD_STREAMS} from '../helpers/stdio.js';4import {setFixtureDirectory} from '../helpers/fixtures-directory.js';5import {getEarlyErrorSubprocess, expectedEarlyError} from '../helpers/early-error.js';67setFixtureDirectory();89const testDestroyStandard = async (t, fdNumber) => {
6 unmodified lines
16test('Does not destroy process.stdout on subprocess errors', testDestroyStandard, 1);17test('Does not destroy process.stderr on subprocess errors', testDestroyStandard, 2);1819const 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};2425test('Does not destroy process.stdin on subprocess early errors', testDestroyStandardSpawn, 0);
15 unmodified lines
modified:test/ipc/get-each.js+38 added-36 removed
1import test from 'ava';2import {execa} from '../../index.js';3import {setFixtureDirectory} from '../helpers/fixtures-directory.js';4import {foobarString, foobarArray} from '../helpers/input.js';5import {iterateAllMessages} from '../helpers/ipc.js';67setFixtureDirectory();88// @todo: replace with Array.fromAsync(subprocess.getEachMessage()) after dropping support for Node <22.0.09const iterateAllMessages = async subprocess => {10 const messages = [];11 for await (const message of subprocess.getEachMessage()) {12 messages.push(message);13 }1415 return messages;16};179test('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 }1516 const {ipc} = await subprocess;17 t.deepEqual(ipc, foobarArray);18});1920test('Can iterate over IPC messages in subprocess', async t => {21 const subprocess = execa('ipc-iterate.js', {ipc: true});
1 unmodified line
23 await subprocess.sendMessage('.');24 await subprocess.sendMessage('.');25 await subprocess.sendMessage(foobarString);2633 const {stdout} = await subprocess;34 t.is(stdout, '..');27 const {ipc} = await subprocess;28 t.deepEqual(ipc, ['.', '.']);29});3031test('Can iterate multiple times over IPC messages in subprocess', async t => {32 const subprocess = execa('ipc-iterate-twice.js', {ipc: true});3334 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);4247 const {stdout} = await subprocess;48 t.is(stdout, '..');43 const {ipc} = await subprocess;44 t.deepEqual(ipc, ['.', foobarString, '.', foobarString]);45});4647test('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 );5357 await subprocess;54 const {ipc} = await subprocess;55 t.deepEqual(ipc, foobarArray);56});5758const HIGH_CONCURRENCY_COUNT = 100;5960test('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);6465 const {ipc} = await subprocess;66 t.deepEqual(ipc, Array.from({length: HIGH_CONCURRENCY_COUNT}, (_, index) => index));67});6869test('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();7475 const {stdout} = await subprocess;76 t.is(stdout, '.');77});78
1 unmodified line
80 const subprocess = execa('ipc-send-disconnect.js', {ipc: true});81 for await (const message of subprocess.getEachMessage()) {82 t.is(message, foobarString);83 }8485 const {ipc} = await subprocess;86 t.deepEqual(ipc, [foobarString]);87});8889test('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 }9495 const {ipc} = await subprocess;96 t.deepEqual(ipc, [foobarString]);97});9899const loopAndBreak = async (t, subprocess) => {100 // eslint-disable-next-line no-unreachable-loop
4 unmodified lines
105};106107test('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});113108test('Cleans up subprocess.getEachMessage() listeners', async t => {109 const subprocess = execa('ipc-send.js', {ipc: true});114const testCleanupListeners = async (t, buffer) => {115 const subprocess = execa('ipc-send.js', {ipc: true, buffer});116 const bufferCount = buffer ? 1 : 0;117111 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);120121 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]);125126 t.is(subprocess.listenerCount('message'), 0);127 t.is(subprocess.listenerCount('disconnect'), 0);121});128};129123test('"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});130test('Cleans up subprocess.getEachMessage() listeners, buffer false', testCleanupListeners, false);131test('Cleans up subprocess.getEachMessage() listeners, buffer true', testCleanupListeners, true);
modified:test/ipc/get-one.js+137 added-30 removed
1import {once} from 'node:events';2import {setTimeout} from 'node:timers/promises';3import test from 'ava';4import {execa} from '../../index.js';5import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6import {foobarString} from '../helpers/input.js';7import {iterateAllMessages} from '../helpers/ipc.js';89setFixtureDirectory();109test('subprocess.getOneMessage() keeps the subprocess alive', async t => {10 const subprocess = execa('ipc-echo-twice.js', {ipc: true});11const getOneSubprocessMessage = subprocess => subprocess.getOneMessage();1213const 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};2118test('Buffers initial message to subprocess', async t => {19 const subprocess = execa('ipc-echo-wait.js', {ipc: true});22test('subprocess.getOneMessage() keeps the subprocess alive, buffer false', testKeepAlive, false);23test('subprocess.getOneMessage() keeps the subprocess alive, buffer true', testKeepAlive, true);2425const 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};3132test('Buffers initial message to subprocess, buffer false', testBufferInitial, false);33test('Buffers initial message to subprocess, buffer true', testBufferInitial, true);3425test('Buffers initial message to current process', async t => {26 const subprocess = execa('ipc-send-print.js', {ipc: true});35test('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});4344test('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});5354const HIGH_CONCURRENCY_COUNT = 100;5536test.serial('Can retrieve initial IPC messages under heavy load', async t => {56test.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});6546test('subprocess.getOneMessage() can be called twice at the same time', async t => {47 const subprocess = execa('ipc-send.js', {ipc: true});66test.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});7475const 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};8355test('Cleans up subprocess.getOneMessage() listeners', async t => {56 const subprocess = execa('ipc-send.js', {ipc: true});84test('subprocess.getOneMessage() can be called twice at the same time, buffer false', testTwice, false);85test('subprocess.getOneMessage() can be called twice at the same time, buffer true', testTwice, true);8658 t.is(subprocess.listenerCount('message'), 0);59 t.is(subprocess.listenerCount('disconnect'), 0);87const testCleanupListeners = async (t, buffer) => {88 const subprocess = execa('ipc-send.js', {ipc: true, buffer});89 const bufferCount = buffer ? 1 : 0;9091 t.is(subprocess.listenerCount('message'), bufferCount);92 t.is(subprocess.listenerCount('disconnect'), bufferCount);9394 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);9899 t.is(subprocess.listenerCount('message'), bufferCount);100 t.is(subprocess.listenerCount('disconnect'), bufferCount);101102 await subprocess;103104 t.is(subprocess.listenerCount('message'), 0);105 t.is(subprocess.listenerCount('disconnect'), 0);106};10769 await subprocess;70});108test('Cleans up subprocess.getOneMessage() listeners, buffer false', testCleanupListeners, false);109test('Cleans up subprocess.getOneMessage() listeners, buffer true', testCleanupListeners, true);11072test('"error" event interrupts subprocess.getOneMessage()', async t => {73 const subprocess = execa('ipc-echo.js', {ipc: true});111test('"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);115116 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});12280const testSubprocessError = async (t, fixtureName) => {81 const subprocess = execa(fixtureName, {ipc: true});82 t.like(await subprocess.getOneMessage(), {message: 'foobar'});123const 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);127128 subprocess.disconnect();129130 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};137138test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer false', testParentDisconnect, false);139test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer true', testParentDisconnect, true);140141const 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};14886test('"error" event interrupts exports.getOneMessage()', testSubprocessError, 'ipc-process-error.js');87test('"error" event interrupts exports.getEachMessage()', testSubprocessError, 'ipc-iterate-error.js');149test('Subprocess exit interrupts disconnect.getOneMessage(), buffer false', testSubprocessDisconnect, false);150test('Subprocess exit interrupts disconnect.getOneMessage(), buffer true', testSubprocessDisconnect, true);151152const 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);156157 const cause = new Error(foobarString);158 subprocess.emit('error', cause);159160 const ipcError = await t.throwsAsync(promise);161 t.is(useCause ? ipcError.cause : ipcError, cause);162163 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};171172test('"error" event interrupts subprocess.getOneMessage(), buffer false', testParentError, getOneSubprocessMessage, false, false);173test('"error" event interrupts subprocess.getOneMessage(), buffer true', testParentError, getOneSubprocessMessage, false, true);174test('"error" event interrupts subprocess.getEachMessage(), buffer false', testParentError, iterateAllMessages, true, false);175test('"error" event interrupts subprocess.getEachMessage(), buffer true', testParentError, iterateAllMessages, true, true);176177const testSubprocessError = async (t, fixtureName, buffer) => {178 const subprocess = execa(fixtureName, {ipc: true, buffer});179180 const ipcError = await t.throwsAsync(subprocess.getOneMessage());181 t.true(ipcError.message.includes('subprocess.getOneMessage() could not complete'));182183 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};190191test('"error" event interrupts exports.getOneMessage(), buffer false', testSubprocessError, 'ipc-process-error.js', false);192test('"error" event interrupts exports.getOneMessage(), buffer true', testSubprocessError, 'ipc-process-error.js', true);193test('"error" event interrupts exports.getEachMessage(), buffer false', testSubprocessError, 'ipc-iterate-error.js', false);194test('"error" event interrupts exports.getEachMessage(), buffer true', testSubprocessError, 'ipc-iterate-error.js', true);
added:test/ipc/messages.js+58 added
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDirectory} from '../helpers/fixtures-directory.js';4import {foobarString, foobarArray} from '../helpers/input.js';56setFixtureDirectory();78const testResultIpc = async (t, options) => {9 const {ipc} = await execa('ipc-send-twice.js', {...options, ipc: true});10 t.deepEqual(ipc, foobarArray);11};1213test('Sets result.ipc', testResultIpc, {});14test('Sets result.ipc, fd-specific buffer', testResultIpc, {buffer: {stdout: false}});1516const testResultNoBuffer = async (t, options) => {17 const {ipc} = await execa('ipc-send.js', {...options, ipc: true});18 t.deepEqual(ipc, []);19};2021test('Sets empty result.ipc if buffer is false', testResultNoBuffer, {buffer: false});22test('Sets empty result.ipc if buffer is false, fd-specific buffer', testResultNoBuffer, {buffer: {ipc: false}});2324test('Sets empty result.ipc if ipc is false', async t => {25 const {ipc} = await execa('empty.js');26 t.deepEqual(ipc, []);27});2829test('Sets empty result.ipc, sync', t => {30 const {ipc} = execaSync('empty.js');31 t.deepEqual(ipc, []);32});3334const testErrorIpc = async (t, options) => {35 const {ipc} = await t.throwsAsync(execa('ipc-send-fail.js', {...options, ipc: true}));36 t.deepEqual(ipc, [foobarString]);37};3839test('Sets error.ipc', testErrorIpc, {});40test('Sets error.ipc, fd-specific buffer', testErrorIpc, {buffer: {stdout: false}});4142const testErrorNoBuffer = async (t, options) => {43 const {ipc} = await t.throwsAsync(execa('ipc-send-fail.js', {...options, ipc: true}));44 t.deepEqual(ipc, []);45};4647test('Sets empty error.ipc if buffer is false', testErrorNoBuffer, {buffer: false});48test('Sets empty error.ipc if buffer is false, fd-specific buffer', testErrorNoBuffer, {buffer: {ipc: false}});4950test('Sets empty error.ipc if ipc is false', async t => {51 const {ipc} = await t.throwsAsync(execa('fail.js'));52 t.deepEqual(ipc, []);53});5455test('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 lines
38test('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});4546test('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);5051 await t.throwsAsync(subprocess.sendMessage(0n), {52 message: /subprocess.sendMessage\(\)'s argument type is invalid/,53 });5455 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});6061test('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'));6566 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 lines
296});297298test('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
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDirectory} from '../helpers/fixtures-directory.js';4import {fullStdio, getStdio} from '../helpers/stdio.js';5import {foobarString} from '../helpers/input.js';5import {foobarString, foobarObject, foobarObjectInspect} from '../helpers/input.js';6import {QUOTE} from '../helpers/verbose.js';7import {noopGenerator, outputObjectGenerator} from '../helpers/generator.js';89setFixtureDirectory();
83 unmodified lines
93test('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});9798const 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};107108test('error.message contains IPC messages, single string', testIpcMessage, false, foobarString, foobarString);109test('error.message contains IPC messages, two strings', testIpcMessage, true, foobarString, foobarString);110test('error.message contains IPC messages, single object', testIpcMessage, false, foobarObject, foobarObjectInspect);111test('error.message contains IPC messages, two objects', testIpcMessage, true, foobarObject, foobarObjectInspect);112test('error.message contains IPC messages, multiline string', testIpcMessage, false, `${foobarString}\n${foobarString}`, `${foobarString}\n${foobarString}`);113test('error.message contains IPC messages, control characters', testIpcMessage, false, '\0', '\\u0000');114115test('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 line
2import {execa, execaSync} from '../../index.js';3import {setFixtureDirectory} from '../helpers/fixtures-directory.js';4import {fullStdio, getStdio} from '../helpers/stdio.js';5import {foobarString} from '../helpers/input.js';6import {7 getEarlyErrorSubprocess,8 getEarlyErrorSubprocessSync,9 expectedEarlyError,10 expectedEarlyErrorSync,11} from '../helpers/early-error.js';1213setFixtureDirectory();1415const testOutput = async (t, fdNumber, execaMethod) => {
72 unmodified lines
88 const {stdio} = await t.throwsAsync(execa('fail.js', {input: 'test'}));89 t.is(stdio[0], undefined);90});9186// `error.code` is OS-specific here87const SPAWN_ERROR_CODES = new Set(['EINVAL', 'ENOTSUP', 'EPERM']);8889const 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));92const 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};9898test('stdout/stderr/all/stdio on subprocess spawning errors', testSpawnError, execa);99test('stdout/stderr/all/stdio on subprocess spawning errors, sync', testSpawnError, execaSync);99test('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});104105test('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});110111const 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 lines
117};118119test('error.stdout/stderr/stdio is defined', testErrorOutput, execa);120test('error.stdout/stderr/stdio is defined, sync', testErrorOutput, execaSync);121122test('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});127128const testEarlyErrorNoIpc = async (t, options) => {129 const error = await t.throwsAsync(getEarlyErrorSubprocess(options));130 t.like(error, expectedEarlyError);131 t.deepEqual(error.ipc, []);132};133134test('ipc on subprocess spawning errors, ipc false', testEarlyErrorNoIpc, {ipc: false});135test('ipc on subprocess spawning errors, buffer false', testEarlyErrorNoIpc, {buffer: false});
modified:test/return/result.js+2 added
23 unmodified lines
24 'stdout',25 'stderr',26 'all',27 'stdio',28 'ipc',29 'pipedFrom',30 ]);31};32
20 unmodified lines
53 'stdout',54 'stderr',55 'all',56 'stdio',57 'ipc',58 'pipedFrom',59 ]);60};61
82 unmodified lines
modified:test/stdio/node-stream-custom.js+3 added-1 removed
9 unmodified lines
10import {setFixtureDirectory} from '../helpers/fixtures-directory.js';11import {getStdio} from '../helpers/stdio.js';12import {foobarString} from '../helpers/input.js';13import {noopReadable, noopWritable} from '../helpers/stream.js';14import {getEarlyErrorSubprocess, expectedEarlyError} from '../helpers/early-error.js';1516setFixtureDirectory();1718const testLazyFileReadable = async (t, fdNumber) => {
68 unmodified lines
87 t.is(error.cause, cause);88});8990const 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};9596test('Input streams are canceled on early subprocess exit', testStreamEarlyExit, noopReadable(), 'stdin');
64 unmodified lines
modified:test/transform/generator-error.js+3 added-1 removed
3 unmodified lines
4import {foobarString} from '../helpers/input.js';5import {noopGenerator, infiniteGenerator, convertTransformToFinal} from '../helpers/generator.js';6import {generatorsMap} from '../helpers/map.js';7import {setFixtureDirectory} from '../helpers/fixtures-directory.js';8import {getEarlyErrorSubprocess, expectedEarlyError} from '../helpers/early-error.js';910setFixtureDirectory();1112const assertProcessError = async (t, type, execaMethod, getSubprocess) => {
72 unmodified lines
85test('Generators are destroyed on subprocess error, sync', testGeneratorDestroy, noopGenerator(false));86test('Generators are destroyed on subprocess error, async', testGeneratorDestroy, infiniteGenerator());8788test('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
1import {expectAssignable, expectType} from 'tsd';2import {3 execa,4 execaSync,5 type Result,6 type SyncResult,7 type ExecaError,8 type ExecaSyncError,9} from '../../index.js';1011const ipcResult = await execa('unicorns', {ipc: true});12expectType<unknown[]>(ipcResult.ipc);1314const ipcFdResult = await execa('unicorns', {ipc: true, buffer: {stdout: false}});15expectType<unknown[]>(ipcFdResult.ipc);1617const falseIpcResult = await execa('unicorns', {ipc: false});18expectType<[]>(falseIpcResult.ipc);1920const noIpcResult = await execa('unicorns');21expectType<[]>(noIpcResult.ipc);2223const noBufferResult = await execa('unicorns', {ipc: true, buffer: false});24expectType<[]>(noBufferResult.ipc);2526const noBufferFdResult = await execa('unicorns', {ipc: true, buffer: {ipc: false}});27expectType<[]>(noBufferFdResult.ipc);2829const syncResult = execaSync('unicorns');30expectType<[]>(syncResult.ipc);3132expectType<unknown[] | []>({} as Result['ipc']);33expectAssignable<unknown[]>({} as Result['ipc']);34expectType<[]>({} as unknown as SyncResult['ipc']);3536const ipcError = new Error('.') as ExecaError<{ipc: true}>;37expectType<unknown[]>(ipcError.ipc);3839const ipcFalseError = new Error('.') as ExecaError<{ipc: false}>;40expectType<[]>(ipcFalseError.ipc);4142const asyncError = new Error('.') as ExecaError;43expectType<unknown[] | []>(asyncError.ipc);44expectAssignable<unknown[]>(asyncError.ipc);4546const syncError = new Error('.') as ExecaSyncError;47expectType<[]>(syncError.ipc);
added:types/return/result-ipc.d.ts+21 added
1import type {FdSpecificOption} from '../arguments/specific.js';2import type {CommonOptions} from '../arguments/options.js';34// `result.ipc`5// This is empty unless the `ipc` option is `true`.6// Also, this is empty if the `buffer` option is `false`.7export type ResultIpc<8 IsSync extends boolean,9 OptionsType extends CommonOptions,10> = IsSync extends true11 ? []12 : ResultIpcAsync<FdSpecificOption<OptionsType['buffer'], 'ipc'>, OptionsType['ipc']>;1314type 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 lines
4import type {ErrorProperties} from './final-error.js';5import type {ResultAll} from './result-all.js';6import type {ResultStdioArray} from './result-stdio.js';7import type {ResultStdioNotAll} from './result-stdout.js';8import type {ResultIpc} from './result-ipc.js';910export declare abstract class CommonResult<11 IsSync extends boolean,12 OptionsType extends CommonOptions,
36 unmodified lines
49 */50 stdio: ResultStdioArray<OptionsType>;5152 /**53 All the messages sent by the subprocess to the current process.5455 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>;5859 /**60 Results of the other subprocesses that were piped into this subprocess.6162 This array is initially empty and is populated each time the `subprocess.pipe()` method resolves.63 */
130 unmodified lines