Add promise-based IPC (#1059)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent 39790a4 · Browse files · 57 files·+1100 added−136 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
57 files+1100 added−136 removed
- tests:+517 added−75 removed
- other:+583 added−61 removed
Provenance
- Commit
acc2b68- Tree
3b46e48- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
39790a4
57 files changed+1100 added−136 removed
modified:docs/api.md+51 added-14 removed
90 unmodified lines91 Split a `command` string into an array. For example, `'npm run build'` returns `['npm', 'run', 'build']` and `'argument otherArgument'` returns `['argument', 'otherArgument']`.92 93 [More info.](escaping.md#user-defined-input)94 95+### sendMessage(message)96+97+`message`: [`Message`](ipc.md#message-type)\98+_Returns_: `Promise<void>`99+100+Send a `message` to the parent process.101+102+This requires the [`ipc`](#optionsipc) option to be `true`. The [type](ipc.md#message-type) of `message` depends on the [`serialization`](#optionsserialization) option.103+104+[More info.](ipc.md#exchanging-messages)105+106+### getOneMessage()107+108+_Returns_: [`Promise<Message>`](ipc.md#message-type)109+110+Receive a single `message` from the parent process.111+112+This requires the [`ipc`](#optionsipc) option to be `true`. The [type](ipc.md#message-type) of `message` depends on the [`serialization`](#optionsserialization) option.113+114+[More info.](ipc.md#exchanging-messages)115+116+### getEachMessage()117+118+_Returns_: [`AsyncIterable<Message>`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols)119+120+Iterate over each `message` from the parent process.121+122+This requires the [`ipc`](#optionsipc) option to be `true`. The [type](ipc.md#message-type) of `message` depends on the [`serialization`](#optionsserialization) option.123+124+[More info.](ipc.md#listening-to-messages)125+126 ## Return value127 128 _TypeScript:_ [`ResultPromise`](typescript.md)\129 _Type:_ `Promise<object> | Subprocess`117 unmodified lines247 This is `undefined` if the subprocess failed to spawn.248 249 [More info.](termination.md#inter-process-termination)250 220-### subprocess.send(message)251+### subprocess.sendMessage(message)252 222-`message`: `unknown`\223-_Returns_: `boolean`253+`message`: [`Message`](ipc.md#message-type)\254+_Returns_: `Promise<void>`255 225-Send a `message` to the subprocess. The type of `message` depends on the [`serialization`](#optionsserialization) option.226-The subprocess receives it as a [`message` event](https://nodejs.org/api/process.html#event-message).256+Send a `message` to the subprocess.257 228-This returns `true` on success.258+This requires the [`ipc`](#optionsipc) option to be `true`. The [type](ipc.md#message-type) of `message` depends on the [`serialization`](#optionsserialization) option.259 230-This requires the [`ipc`](#optionsipc) option to be `true`.231-260 [More info.](ipc.md#exchanging-messages)261 234-### subprocess.on('message', (message) => void)262+### subprocess.getOneMessage()263 236-`message`: `unknown`264+_Returns_: [`Promise<Message>`](ipc.md#message-type)265 238-Receives a `message` from the subprocess. The type of `message` depends on the [`serialization`](#optionsserialization) option.239-The subprocess sends it using [`process.send(message)`](https://nodejs.org/api/process.html#processsendmessage-sendhandle-options-callback).266+Receive a single `message` from the subprocess.267 241-This requires the [`ipc`](#optionsipc) option to be `true`.268+This requires the [`ipc`](#optionsipc) option to be `true`. The [type](ipc.md#message-type) of `message` depends on the [`serialization`](#optionsserialization) option.269 270 [More info.](ipc.md#exchanging-messages)271 272+### subprocess.getEachMessage()273+274+_Returns_: [`AsyncIterable<Message>`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols)275+276+Iterate over each `message` from the subprocess.277+278+This requires the [`ipc`](#optionsipc) option to be `true`. The [type](ipc.md#message-type) of `message` depends on the [`serialization`](#optionsserialization) option.279+280+[More info.](ipc.md#listening-to-messages)281+282 ### subprocess.stdin283 284 _Type:_ [`Writable | null`](https://nodejs.org/api/stream.html#class-streamwritable)285 603 unmodified lines889 890 _Type:_ `boolean`\891 _Default:_ `true` if the [`node`](#optionsnode) option is enabled, `false` otherwise892 856-Enables exchanging messages with the subprocess using [`subprocess.send(message)`](#subprocesssendmessage) and [`subprocess.on('message', (message) => {})`](#subprocessonmessage-message--void).893+Enables exchanging messages with the subprocess using [`subprocess.sendMessage(message)`](#subprocesssendmessagemessage), [`subprocess.getOneMessage()`](#subprocessgetonemessage) and [`subprocess.getEachMessage()`](#subprocessgeteachmessage).894 895 [More info.](ipc.md)896 897 ### options.serialization187 unmodified linesmodified:docs/bash.md+3 added-3 removed
790 unmodified lines791 ```792 793 ```js794 // Execa795-const subprocess = $({ipc: true})`node script.js`;795+const subprocess = $({node: true})`script.js`;796 797-subprocess.on('message', message => {797+for await (const message of subprocess.getEachMessage()) {798 if (message === 'ping') {799- subprocess.send('pong');799+ await subprocess.sendMessage('pong');800 }801 });802 ```803 91 unmodified linesmodified:docs/ipc.md+41 added-11 removed
10 unmodified lines11121314151516171718192021222324252627282930313233343536373839404142434424252627454647484950515253545556325758343536375960616263646566676869707113 unmodified lines10 unmodified linesWhen the [`ipc`](api.md#optionsipc) option is `true`, the current process and subprocess can exchange messages. This only works if the subprocess is a Node.js file.
The `ipc` option defaults to `true` when using [`execaNode()`](node.md#run-nodejs-files) or the [`node`](node.md#run-nodejs-files) option.
The current process sends messages with [`subprocess.send(message)`](api.md#subprocesssendmessage) and receives them with [`subprocess.on('message', (message) => {})`](api.md#subprocessonmessage-message--void). The subprocess sends messages with [`process.send(message)`](https://nodejs.org/api/process.html#processsendmessage-sendhandle-options-callback) and [`process.on('message', (message) => {})`](https://nodejs.org/api/process.html#event-message).The current process sends messages with [`subprocess.sendMessage(message)`](api.md#subprocesssendmessagemessage) and receives them with [`subprocess.getOneMessage()`](api.md#subprocessgetonemessage). The subprocess uses [`sendMessage(message)`](api.md#sendmessagemessage) and [`getOneMessage()`](api.md#getonemessage) instead.
More info on [sending](https://nodejs.org/api/child_process.html#subprocesssendmessage-sendhandle-options-callback) and [receiving](https://nodejs.org/api/child_process.html#event-message) messages.```js// parent.jsimport {execaNode} from 'execa';
const subprocess = execaNode`child.js`;console.log(await subprocess.getOneMessage()); // 'Hello from child'await subprocess.sendMessage('Hello from parent');```
```js// child.jsimport {sendMessage, getOneMessage} from 'execa';
await sendMessage('Hello from child');console.log(await getOneMessage()); // 'Hello from parent'```
## Listening to messages
[`subprocess.getOneMessage()`](api.md#subprocessgetonemessage) and [`getOneMessage()`](api.md#getonemessage) read a single message. To listen to multiple messages in a row, [`subprocess.getEachMessage()`](api.md#subprocessgeteachmessage) and [`getEachMessage()`](api.md#geteachmessage) should be used instead.
[`subprocess.getEachMessage()`](api.md#subprocessgeteachmessage) waits for the subprocess to end (even when using [`break`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/break) or [`return`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return)). It throws if the subprocess [fails](api.md#result). This means you do not need to `await` the subprocess' [promise](execution.md#result).
```js// parent.jsimport {execaNode} from 'execa';
const subprocess = execaNode`child.js`;subprocess.on('message', messageFromChild => { /* ... */});subprocess.send('Hello from parent');await subprocess.sendMessage(0);
// This loop ends when the subprocess exits.// It throws if the subprocess fails.for await (const message of subprocess.getEachMessage()) { console.log(message); // 1, 3, 5, 7, 9 await subprocess.sendMessage(message + 1);}```
```js// child.jsimport process from 'node:process';import {sendMessage, getEachMessage} from 'execa';
process.on('message', messageFromParent => { /* ... */});process.send('Hello from child');// The subprocess exits when hitting `break`for await (const message of getEachMessage()) { if (message === 10) { break }
console.log(message); // 0, 2, 4, 6, 8 await sendMessage(message + 1);}```
## Message type
13 unmodified linesmodified:docs/typescript.md+8 added-1 removed
6 unmodified lines7 # 🤓 TypeScript8 9 ## Available types10 11-The following types can be imported: [`ResultPromise`](api.md#return-value), [`Subprocess`](api.md#subprocess), [`Result`](api.md#result), [`ExecaError`](api.md#execaerror), [`Options`](api.md#options), [`StdinOption`](api.md#optionsstdin), [`StdoutStderrOption`](api.md#optionsstdout) and [`TemplateExpression`](api.md#execacommand).11+The following types can be imported: [`ResultPromise`](api.md#return-value), [`Subprocess`](api.md#subprocess), [`Result`](api.md#result), [`ExecaError`](api.md#execaerror), [`Options`](api.md#options), [`StdinOption`](api.md#optionsstdin), [`StdoutStderrOption`](api.md#optionsstdout), [`TemplateExpression`](api.md#execacommand) and [`Message`](api.md#subprocesssendmessagemessage).12 13 ```ts14 import {15 execa,3 unmodified lines19 type Options,20 type StdinOption,21 type StdoutStderrOption,22 type TemplateExpression,23+ type Message,24 } from 'execa';25 26 const options: Options = {27 stdin: 'inherit' satisfies StdinOption,28 stdout: 'pipe' satisfies StdoutStderrOption,29 stderr: 'pipe' satisfies StdoutStderrOption,30 timeout: 1000,31+ ipc: true,32 };33 const task: TemplateExpression = 'build';34+const message: Message = 'hello world';35 36 try {37 const subprocess: ResultPromise = execa(options)`npm run ${task}`;38+ await subprocess.sendMessage(message);39 const result: Result = await subprocess;40 console.log(result.stdout);41 } catch (error) {42 if (error instanceof ExecaError) {54 unmodified lines97 stdin: 'inherit',98 stdout: 'pipe',99 stderr: 'pipe',100 timeout: 1000,101+ ipc: true,102 } as const;103 const task = 'build';104+const message = 'hello world';105 106 try {107 const subprocess = execa(options)`npm run ${task}`;108+ await subprocess.sendMessage(message);109 const result = await subprocess;110 printResultStdout(result);111 } catch (error) {112 if (error instanceof ExecaError) {59 unmodified linesadded:lib/ipc/array.js+4 added
1234// The `ipc` option adds an `ipc` item to the `stdio` optionexport const normalizeIpcStdioArray = (stdioArray, ipc) => ipc && !stdioArray.includes('ipc') ? [...stdioArray, 'ipc'] : stdioArray;added:lib/ipc/get-each.js+43 added
12345678910111213141516171819202122232425262728293031323334353637383940414243import {once, on} from 'node:events';import {validateIpcOption, validateConnection} from './validation.js';
// Like `[sub]process.on('message')` but promise-basedexport const getEachMessage = function ({anyProcess, isSubprocess, ipc}) { const methodName = 'getEachMessage'; validateIpcOption(methodName, isSubprocess, ipc); validateConnection(methodName, isSubprocess, anyProcess.channel !== null);
const controller = new AbortController(); stopOnExit(anyProcess, isSubprocess, controller);
return iterateOnMessages(anyProcess, isSubprocess, controller);};
const stopOnExit = async (anyProcess, isSubprocess, controller) => { try { const onDisconnect = once(anyProcess, 'disconnect', {signal: controller.signal}); await (isSubprocess ? onDisconnect : Promise.race([onDisconnect, anyProcess])); } catch {} finally { controller.abort(); }};
const iterateOnMessages = async function * (anyProcess, isSubprocess, controller) { try { for await (const [message] of on(anyProcess, 'message', {signal: controller.signal})) { yield message; } } catch (error) { if (!controller.signal.aborted) { throw error; } } finally { if (!isSubprocess) { await anyProcess; }
controller.abort(); }};added:lib/ipc/get-one.js+16 added
12345678910111213141516import {once} from 'node:events';import {validateIpcOption, validateConnection} from './validation.js';
// Like `[sub]process.once('message')` but promise-basedexport const getOneMessage = ({anyProcess, isSubprocess, ipc}) => { const methodName = 'getOneMessage'; validateIpcOption(methodName, isSubprocess, ipc); validateConnection(methodName, isSubprocess, anyProcess.channel !== null);
return onceMessage(anyProcess);};
const onceMessage = async anyProcess => { const [message] = await once(anyProcess, 'message'); return message;};added:lib/ipc/methods.js+30 added
123456789101112131415161718192021222324252627282930import process from 'node:process';import {promisify} from 'node:util';import {sendMessage} from './send.js';import {getOneMessage} from './get-one.js';import {getEachMessage} from './get-each.js';
// Add promise-based IPC methods in current processexport const addIpcMethods = (subprocess, {ipc}) => { Object.assign(subprocess, getIpcMethods(subprocess, false, ipc));};
// Get promise-based IPC in the subprocessexport const getIpcExport = () => getIpcMethods(process, true, process.channel !== undefined);
// Retrieve the `ipc` shared by both the current process and the subprocessconst getIpcMethods = (anyProcess, isSubprocess, ipc) => { const anyProcessSend = anyProcess.send === undefined ? undefined : promisify(anyProcess.send.bind(anyProcess)); return { sendMessage: sendMessage.bind(undefined, { anyProcess, anyProcessSend, isSubprocess, ipc, }), getOneMessage: getOneMessage.bind(undefined, {anyProcess, isSubprocess, ipc}), getEachMessage: getEachMessage.bind(undefined, {anyProcess, isSubprocess, ipc}), };};added:lib/ipc/send.js+26 added
1+import {2+ validateIpcOption,3+ validateConnection,4+ handleSerializationError,5+} from './validation.js';6+7+// Like `[sub]process.send()` but promise-based.8+// We do not `await subprocess` during `.sendMessage()` nor `.getOneMessage()` since those methods are transient.9+// Users would still need to `await subprocess` after the method is done.10+// Also, this would prevent `unhandledRejection` event from being emitted, making it silent.11+export const sendMessage = ({anyProcess, anyProcessSend, isSubprocess, ipc}, message) => {12+ const methodName = 'sendMessage';13+ validateIpcOption(methodName, isSubprocess, ipc);14+ validateConnection(methodName, isSubprocess, anyProcess.connected);15+16+ return sendOneMessage(anyProcessSend, isSubprocess, message);17+};18+19+const sendOneMessage = async (anyProcessSend, isSubprocess, message) => {20+ try {21+ await anyProcessSend(message);22+ } catch (error) {23+ handleSerializationError(error, isSubprocess, message);24+ throw error;25+ }26+};added:lib/ipc/validation.js+46 added
1+// Better error message when forgetting to set `ipc: true` and using the IPC methods2+export const validateIpcOption = (methodName, isSubprocess, ipc) => {3+ if (!ipc) {4+ throw new Error(`${getNamespaceName(isSubprocess)}${methodName}() can only be used if the \`ipc\` option is \`true\`.`);5+ }6+};7+8+// Better error message when one process does not send/receive messages once the other process has disconnected9+export const validateConnection = (methodName, isSubprocess, isConnected) => {10+ if (!isConnected) {11+ throw new Error(`${getNamespaceName(isSubprocess)}${methodName}() cannot be used: the ${getOtherProcessName(isSubprocess)} has already exited or disconnected.`);12+ }13+};14+15+const getNamespaceName = isSubprocess => isSubprocess ? '' : 'subprocess.';16+17+const getOtherProcessName = isSubprocess => isSubprocess ? 'parent process' : 'subprocess';18+19+// Better error message when sending messages which cannot be serialized.20+// Works with both `serialization: 'advanced'` and `serialization: 'json'`.21+export const handleSerializationError = (error, isSubprocess, message) => {22+ if (isSerializationError(error)) {23+ error.message = `${getNamespaceName(isSubprocess)}sendMessage()'s argument type is invalid: the message cannot be serialized: ${String(message)}.\n${error.message}`;24+ }25+};26+27+const isSerializationError = ({code, message}) => SERIALIZATION_ERROR_CODES.has(code)28+ || SERIALIZATION_ERROR_MESSAGES.some(serializationErrorMessage => message.includes(serializationErrorMessage));29+30+// `error.code` set by Node.js when it failed to serialize the message31+const SERIALIZATION_ERROR_CODES = new Set([32+ // Message is `undefined`33+ 'ERR_MISSING_ARGS',34+ // Message is a function, a bigint, a symbol35+ 'ERR_INVALID_ARG_TYPE',36+]);37+38+// `error.message` set by Node.js when it failed to serialize the message39+const SERIALIZATION_ERROR_MESSAGES = [40+ // Message is a promise or a proxy, with `serialization: 'advanced'`41+ 'could not be cloned',42+ // Message has cycles, with `serialization: 'json'`43+ 'circular structure',44+ // Message has cycles inside toJSON(), with `serialization: 'json'`45+ 'call stack size exceeded',46+];modified:lib/methods/main-async.js+2 added
2 unmodified lines3 import {MaxBufferError} from 'get-stream';4 import {handleCommand} from '../arguments/command.js';5 import {normalizeOptions} from '../arguments/options.js';6 import {SUBPROCESS_OPTIONS} from '../arguments/fd-options.js';7+import {addIpcMethods} from '../ipc/methods.js';8 import {makeError, makeSuccessResult} from '../return/result.js';9 import {handleResult} from '../return/reject.js';10 import {handleEarlyError} from '../return/early-error.js';11 import {handleStdioAsync} from '../stdio/handle-async.js';98 unmodified lines110 controller,111 });112 subprocess.all = makeAllStream(subprocess, options);113 addConvertedStreams(subprocess, options);114+ addIpcMethods(subprocess, options);115 116 const promise = handlePromise({117 subprocess,118 options,70 unmodified linesmodified:lib/stdio/stdio-option.js+4 added-6 removed
1 import {STANDARD_STREAMS_ALIASES} from '../utils/standard-stream.js';2+import {normalizeIpcStdioArray} from '../ipc/array.js';3 4 // Add support for `stdin`/`stdout`/`stderr` as an alias for `stdio`.5 // Also normalize the `stdio` option.6 export const normalizeStdioOption = ({stdio, ipc, buffer, verbose, ...options}, isSync) => {7 const stdioArray = getStdioArray(stdio, options).map((stdioOption, fdNumber) => addDefaultValue(stdioOption, fdNumber));7- return isSync ? normalizeStdioSync(stdioArray, buffer, verbose) : normalizeStdioAsync(stdioArray, ipc);8+ return isSync9+ ? normalizeStdioSync(stdioArray, buffer, verbose)10+ : normalizeIpcStdioArray(stdioArray, ipc);11 };12 13 const getStdioArray = (stdio, options) => {14 if (stdio === undefined) {41 unmodified lines56 : stdioOption);57 58 const isOutputPipeOnly = stdioOption => stdioOption === 'pipe'59 || (Array.isArray(stdioOption) && stdioOption.every(item => item === 'pipe'));57-58-// The `ipc` option adds an `ipc` item to the `stdio` option59-const normalizeStdioAsync = (stdioArray, ipc) => ipc && !stdioArray.includes('ipc')60- ? [...stdioArray, 'ipc']61- : stdioArray;modified:test/convert/readable.js+8 added-8 removed
112 unmodified lines113 await assertSubprocessError(t, subprocess, error);114 });115 116 const testStdoutAbort = async (t, methodName) => {117- const subprocess = execa('ipc-exit.js', {ipc: true});117+ const subprocess = execa('ipc-echo.js', {ipc: true});118 const stream = subprocess[methodName]();119 120 subprocess.stdout.destroy();121- subprocess.send(foobarString);121+ await subprocess.sendMessage(foobarString);122 123- const [error, [message]] = await Promise.all([123+ const [error, message] = await Promise.all([124 t.throwsAsync(finishedStream(stream)),125- once(subprocess, 'message'),125+ subprocess.getOneMessage(),126 ]);127 t.like(error, prematureClose);128 t.is(message, foobarString);129 assertWritableAborted(t, subprocess.stdin);5 unmodified lines135 test('subprocess.stdout abort + no more writes -> .readable() error + subprocess success', testStdoutAbort, 'readable');136 test('subprocess.stdout abort + no more writes -> .duplex() error + subprocess success', testStdoutAbort, 'duplex');137 138 const testStdoutError = async (t, methodName) => {139- const subprocess = execa('ipc-exit.js', {ipc: true});139+ const subprocess = execa('ipc-echo.js', {ipc: true});140 const stream = subprocess[methodName]();141 142 const cause = new Error(foobarString);143 subprocess.stdout.destroy(cause);144- subprocess.send(foobarString);144+ await subprocess.sendMessage(foobarString);145 146- const [error, [message]] = await Promise.all([146+ const [error, message] = await Promise.all([147 t.throwsAsync(finishedStream(stream)),148- once(subprocess, 'message'),148+ subprocess.getOneMessage(),149 ]);150 t.is(message, foobarString);151 t.is(error.cause, cause);152 assertProcessNormalExit(t, error);307 unmodified linesadded:test/fixtures/ipc-any.js+6 added
1+#!/usr/bin/env node2+import process from 'node:process';3+import * as execaExports from '../../index.js';4+5+const methodName = process.argv[2];6+await execaExports[methodName]();added:test/fixtures/ipc-disconnect.js+12 added
1+#!/usr/bin/env node2+import process from 'node:process';3+import {once} from 'node:events';4+import * as execaExports from '../../index.js';5+6+const methodName = process.argv[2];7+8+if (process.channel !== null) {9+ await once(process, 'disconnect');10+}11+12+await execaExports[methodName]();added:test/fixtures/ipc-echo-item.js+5 added
1+#!/usr/bin/env node2+import {sendMessage, getOneMessage} from '../../index.js';3+4+const [message] = await getOneMessage();5+await sendMessage(message);added:test/fixtures/ipc-echo-twice.js+5 added
1+#!/usr/bin/env node2+import {sendMessage, getOneMessage} from '../../index.js';3+4+await sendMessage(await getOneMessage());5+await sendMessage(await getOneMessage());added:test/fixtures/ipc-echo-wait.js+6 added
1+#!/usr/bin/env node2+import {setTimeout} from 'node:timers/promises';3+import {sendMessage, getOneMessage} from '../../index.js';4+5+await setTimeout(1e3);6+await sendMessage(await getOneMessage());modified:test/fixtures/ipc-echo.js+2 added-4 removed
1 #!/usr/bin/env node2-import process from 'node:process';2+import {sendMessage, getOneMessage} from '../../index.js';3 4-process.once('message', message => {5- process.send(message);6-});4+await sendMessage(await getOneMessage());deleted:test/fixtures/ipc-exit.js-6 removed
1-#!/usr/bin/env node2-import process from 'node:process';3-4-process.once('message', message => {5- process.send(message);6-});added:test/fixtures/ipc-iterate-error.js+24 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+// @todo: replace with Array.fromAsync(subprocess.getEachMessage()) after dropping support for Node <22.0.07+const iterateAllMessages = async () => {8+ const messages = [];9+ for await (const message of getEachMessage()) {10+ messages.push(message);11+ }12+13+ return messages;14+};15+16+const cause = new Error(foobarString);17+try {18+ await Promise.all([19+ iterateAllMessages(),20+ process.emit('error', cause),21+ ]);22+} catch (error) {23+ await sendMessage(error);24+}added:test/fixtures/ipc-iterate-twice.js+18 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+for (let index = 0; index < 2; index += 1) {7+ // eslint-disable-next-line no-await-in-loop8+ for await (const message of getEachMessage()) {9+ if (message === foobarString) {10+ break;11+ }12+13+ process.stdout.write(message);14+ }15+16+ // eslint-disable-next-line no-await-in-loop17+ await sendMessage('.');18+}added:test/fixtures/ipc-iterate.js+12 added
1+#!/usr/bin/env node2+import process from 'node:process';3+import {getEachMessage} from '../../index.js';4+import {foobarString} from '../helpers/input.js';5+6+for await (const message of getEachMessage()) {7+ if (message === foobarString) {8+ break;9+ }10+11+ process.stdout.write(`${message}`);12+}added:test/fixtures/ipc-process-error.js+14 added
1+#!/usr/bin/env node2+import process from 'node:process';3+import {sendMessage, 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+ ]);12+} catch (error) {13+ await sendMessage(error);14+}added:test/fixtures/ipc-send-disconnect.js+8 added
1+#!/usr/bin/env node2+import process from 'node:process';3+import {sendMessage} from '../../index.js';4+import {foobarString} from '../helpers/input.js';5+6+await sendMessage(foobarString);7+8+process.disconnect();added:test/fixtures/ipc-send-fail.js+7 added
1+#!/usr/bin/env node2+import process from 'node:process';3+import {sendMessage} from '../../index.js';4+import {foobarString} from '../helpers/input.js';5+6+await sendMessage(foobarString);7+process.exitCode = 1;added:test/fixtures/ipc-send-iterate.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+}added:test/fixtures/ipc-send-pid.js+9 added
1+#!/usr/bin/env node2+import process from 'node:process';3+import {execa, sendMessage} from '../../index.js';4+5+const cleanup = process.argv[2] === 'true';6+const detached = process.argv[3] === 'true';7+const subprocess = execa('forever.js', {cleanup, detached});8+await sendMessage(subprocess.pid);9+await subprocess;added:test/fixtures/ipc-send-twice.js+6 added
1+#!/usr/bin/env node2+import {sendMessage} from '../../index.js';3+import {foobarArray} from '../helpers/input.js';4+5+await sendMessage(foobarArray[0]);6+await sendMessage(foobarArray[1]);added:test/fixtures/ipc-send.js+5 added
1+#!/usr/bin/env node2+import {sendMessage} from '../../index.js';3+import {foobarString} from '../helpers/input.js';4+5+await sendMessage(foobarString);modified:test/fixtures/nested-sync.js+3 added-3 removed
1 #!/usr/bin/env node2 import process from 'node:process';3-import {execaSync} from '../../index.js';3+import {execaSync, sendMessage} from '../../index.js';4 5 const [options, file, ...commandArguments] = process.argv.slice(2);6 try {7 const result = execaSync(file, commandArguments, JSON.parse(options));8- process.send({result});8+ await sendMessage({result});9 } catch (error) {10- process.send({error});10+ await sendMessage({error});11 }modified:test/fixtures/nested.js+3 added-3 removed
1 #!/usr/bin/env node2 import process from 'node:process';3-import {execa} from '../../index.js';3+import {execa, sendMessage} from '../../index.js';4 5 const [options, file, ...commandArguments] = process.argv.slice(2);6 try {7 const result = await execa(file, commandArguments, JSON.parse(options));8- process.send({result});8+ await sendMessage({result});9 } catch (error) {10- process.send({error});10+ await sendMessage({error});11 }modified:test/fixtures/no-killable.js+2 added-1 removed
1 #!/usr/bin/env node2 import process from 'node:process';3+import {sendMessage} from '../../index.js';4 5 const noop = () => {};6 7 process.on('SIGTERM', noop);8 process.on('SIGINT', noop);9 9-process.send('');10+await sendMessage('');11 console.log('.');12 13 setTimeout(noop, 1e8);modified:test/fixtures/noop-fd-ipc.js+5 added-3 removed
1 #!/usr/bin/env node2 import process from 'node:process';3+import {promisify} from 'node:util';4+import {sendMessage} from '../../index.js';5 import {getWriteStream} from '../helpers/fs.js';6 import {foobarString} from '../helpers/input.js';7 8 const fdNumber = Number(process.argv[2]);9 const bytes = process.argv[3] || foobarString;8-getWriteStream(fdNumber).write(bytes, () => {9- process.send('');10-});10+const stream = getWriteStream(fdNumber);11+await promisify(stream.write.bind(stream))(bytes);12+await sendMessage('');deleted:test/fixtures/send.js-8 removed
1-#!/usr/bin/env node2-import process from 'node:process';3-4-process.once('message', message => {5- console.log(message);6-});7-8-process.send('');deleted:test/fixtures/subprocess.js-9 removed
1-#!/usr/bin/env node2-import process from 'node:process';3-import {execa} from '../../index.js';4-5-const cleanup = process.argv[2] === 'true';6-const detached = process.argv[3] === 'true';7-const subprocess = execa('forever.js', {cleanup, detached});8-process.send(subprocess.pid);9-await subprocess;modified:test/fixtures/worker.js+1 added-2 removed
1-import {once} from 'node:events';1 import {workerData, parentPort} from 'node:worker_threads';2 import {execa} from '../../index.js';3 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';4 1 unmodified line6 7 const {nodeFile, commandArguments, options} = workerData;8 try {9 const subprocess = execa(nodeFile, commandArguments, options);11- const [parentResult, [{result, error}]] = await Promise.all([subprocess, once(subprocess, 'message')]);10+ const [parentResult, {result, error}] = await Promise.all([subprocess, subprocess.getOneMessage()]);11 parentPort.postMessage({parentResult, result, error});12 } catch (parentError) {13 parentPort.postMessage({parentError});14 }added:test/ipc/get-each.js+120 added
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+6+setFixtureDirectory();7+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+18+test('Can iterate over IPC messages', async t => {19+ let count = 0;20+ const subprocess = execa('ipc-send-twice.js', {ipc: true});21+ for await (const message of subprocess.getEachMessage()) {22+ t.is(message, foobarArray[count++]);23+ }24+});25+26+test('Can iterate over IPC messages in subprocess', async t => {27+ const subprocess = execa('ipc-iterate.js', {ipc: true});28+29+ await subprocess.sendMessage('.');30+ await subprocess.sendMessage('.');31+ await subprocess.sendMessage(foobarString);32+33+ const {stdout} = await subprocess;34+ t.is(stdout, '..');35+});36+37+test('Can iterate multiple times over IPC messages in subprocess', async t => {38+ const subprocess = execa('ipc-iterate-twice.js', {ipc: true});39+40+ await subprocess.sendMessage('.');41+ await subprocess.sendMessage(foobarString);42+ t.is(await subprocess.getOneMessage(), '.');43+ await subprocess.sendMessage('.');44+ await subprocess.sendMessage(foobarString);45+ t.is(await subprocess.getOneMessage(), '.');46+47+ const {stdout} = await subprocess;48+ t.is(stdout, '..');49+});50+51+const HIGH_CONCURRENCY_COUNT = 100;52+53+test('Can send many messages at once with exports.getEachMessage()', async t => {54+ const subprocess = execa('ipc-iterate.js', {ipc: true});55+ await Promise.all(Array.from({length: HIGH_CONCURRENCY_COUNT}, (_, index) => subprocess.sendMessage(index)));56+ await subprocess.sendMessage(foobarString);57+ const {stdout} = await subprocess;58+ const expectedStdout = Array.from({length: HIGH_CONCURRENCY_COUNT}, (_, index) => `${index}`).join('');59+ t.is(stdout, expectedStdout);60+});61+62+test('Disconnecting in the current process stops exports.getEachMessage()', async t => {63+ const subprocess = execa('ipc-send-iterate.js', {ipc: true});64+ t.is(await subprocess.getOneMessage(), foobarString);65+ await subprocess.sendMessage('.');66+ subprocess.disconnect();67+ const {stdout} = await subprocess;68+ t.is(stdout, '.');69+});70+71+test('Disconnecting in the subprocess stops subprocess.getEachMessage()', async t => {72+ const subprocess = execa('ipc-send-disconnect.js', {ipc: true});73+ for await (const message of subprocess.getEachMessage()) {74+ t.is(message, foobarString);75+ }76+});77+78+test('Exiting the subprocess stops subprocess.getEachMessage()', async t => {79+ const subprocess = execa('ipc-send.js', {ipc: true});80+ for await (const message of subprocess.getEachMessage()) {81+ t.is(message, foobarString);82+ }83+});84+85+const loopAndBreak = async (t, subprocess) => {86+ // eslint-disable-next-line no-unreachable-loop87+ for await (const message of subprocess.getEachMessage()) {88+ t.is(message, foobarString);89+ break;90+ }91+};92+93+test('Breaking from subprocess.getEachMessage() awaits the subprocess', async t => {94+ const subprocess = execa('ipc-send-fail.js', {ipc: true});95+ const {exitCode} = await t.throwsAsync(loopAndBreak(t, subprocess));96+ t.is(exitCode, 1);97+});98+99+test('Cleans up subprocess.getEachMessage() listeners', async t => {100+ const subprocess = execa('ipc-send.js', {ipc: true});101+102+ t.is(subprocess.listenerCount('message'), 0);103+ t.is(subprocess.listenerCount('disconnect'), 0);104+105+ const promise = iterateAllMessages(subprocess);106+ t.is(subprocess.listenerCount('message'), 1);107+ t.is(subprocess.listenerCount('disconnect'), 1);108+ t.deepEqual(await promise, [foobarString]);109+110+ t.is(subprocess.listenerCount('message'), 0);111+ t.is(subprocess.listenerCount('disconnect'), 0);112+});113+114+test('"error" event interrupts subprocess.getEachMessage()', async t => {115+ const subprocess = execa('ipc-echo.js', {ipc: true});116+ await subprocess.sendMessage(foobarString);117+ const cause = new Error(foobarString);118+ t.like(await t.throwsAsync(Promise.all([iterateAllMessages(subprocess), subprocess.emit('error', cause)])), {cause});119+ t.like(await t.throwsAsync(subprocess), {cause});120+});added:test/ipc/get-one.js+56 added
1+import test from 'ava';2+import {execa} from '../../index.js';3+import {setFixtureDirectory} from '../helpers/fixtures-directory.js';4+import {foobarString} from '../helpers/input.js';5+6+setFixtureDirectory();7+8+test('subprocess.getOneMessage() keeps the subprocess alive', async t => {9+ const subprocess = execa('ipc-echo-twice.js', {ipc: true});10+ await subprocess.sendMessage(foobarString);11+ t.is(await subprocess.getOneMessage(), foobarString);12+ await subprocess.sendMessage(foobarString);13+ t.is(await subprocess.getOneMessage(), foobarString);14+ await subprocess;15+});16+17+test('Buffers initial message to subprocess', async t => {18+ const subprocess = execa('ipc-echo-wait.js', {ipc: true});19+ await subprocess.sendMessage(foobarString);20+ t.is(await subprocess.getOneMessage(), foobarString);21+ await subprocess;22+});23+24+test('Cleans up subprocess.getOneMessage() listeners', async t => {25+ const subprocess = execa('ipc-send.js', {ipc: true});26+27+ t.is(subprocess.listenerCount('message'), 0);28+ t.is(subprocess.listenerCount('disconnect'), 0);29+30+ const promise = subprocess.getOneMessage();31+ t.is(subprocess.listenerCount('message'), 1);32+ t.is(subprocess.listenerCount('disconnect'), 0);33+ t.is(await promise, foobarString);34+35+ t.is(subprocess.listenerCount('message'), 0);36+ t.is(subprocess.listenerCount('disconnect'), 0);37+38+ await subprocess;39+});40+41+test('"error" event interrupts subprocess.getOneMessage()', async t => {42+ const subprocess = execa('ipc-echo.js', {ipc: true});43+ await subprocess.sendMessage(foobarString);44+ const cause = new Error(foobarString);45+ t.is(await t.throwsAsync(Promise.all([subprocess.getOneMessage(), subprocess.emit('error', cause)])), cause);46+ t.like(await t.throwsAsync(subprocess), {cause});47+});48+49+const testSubprocessError = async (t, fixtureName) => {50+ const subprocess = execa(fixtureName, {ipc: true});51+ t.like(await subprocess.getOneMessage(), {message: 'foobar'});52+ await subprocess;53+};54+55+test('"error" event interrupts exports.getOneMessage()', testSubprocessError, 'ipc-process-error.js');56+test('"error" event interrupts exports.getEachMessage()', testSubprocessError, 'ipc-iterate-error.js');added:test/ipc/send.js+44 added
1+import test from 'ava';2+import {execa} from '../../index.js';3+import {setFixtureDirectory} from '../helpers/fixtures-directory.js';4+import {foobarString} from '../helpers/input.js';5+6+setFixtureDirectory();7+8+test('Can exchange IPC messages', async t => {9+ const subprocess = execa('ipc-echo.js', {ipc: true});10+ await subprocess.sendMessage(foobarString);11+ t.is(await subprocess.getOneMessage(), foobarString);12+ await subprocess;13+});14+15+const HIGH_CONCURRENCY_COUNT = 100;16+17+test.serial('Can exchange IPC messages under heavy load', async t => {18+ await Promise.all(19+ Array.from({length: HIGH_CONCURRENCY_COUNT}, async (_, index) => {20+ const subprocess = execa('ipc-echo.js', {ipc: true});21+ await subprocess.sendMessage(index);22+ t.is(await subprocess.getOneMessage(), index);23+ await subprocess;24+ }),25+ );26+});27+28+test('Can use "serialization: json" option', async t => {29+ const subprocess = execa('ipc-echo.js', {ipc: true, serialization: 'json'});30+ const date = new Date();31+ await subprocess.sendMessage(date);32+ t.is(await subprocess.getOneMessage(), date.toJSON());33+ await subprocess;34+});35+36+const BIG_PAYLOAD_SIZE = '.'.repeat(1e6);37+38+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);44+});added:test/ipc/validation.js+92 added
1+import test from 'ava';2+import {execa} from '../../index.js';3+import {setFixtureDirectory} from '../helpers/fixtures-directory.js';4+import {foobarString} from '../helpers/input.js';5+import {getStdio} from '../helpers/stdio.js';6+7+setFixtureDirectory();8+9+const stdioIpc = getStdio(3, 'ipc');10+11+const testRequiredIpcSubprocess = async (t, methodName, options) => {12+ const subprocess = execa('empty.js', options);13+ const {message} = await t.throws(() => subprocess[methodName]());14+ t.true(message.includes(`subprocess.${methodName}() can only be used`));15+ await subprocess;16+};17+18+test('Cannot use subprocess.sendMessage() without ipc option', testRequiredIpcSubprocess, 'sendMessage', {});19+test('Cannot use subprocess.sendMessage() with ipc: false', testRequiredIpcSubprocess, 'sendMessage', {ipc: false});20+test('Cannot use subprocess.sendMessage() with stdio: [..., "ipc"]', testRequiredIpcSubprocess, 'sendMessage', stdioIpc);21+test('Cannot use subprocess.getOneMessage() without ipc option', testRequiredIpcSubprocess, 'getOneMessage', {});22+test('Cannot use subprocess.getOneMessage() with ipc: false', testRequiredIpcSubprocess, 'getOneMessage', {ipc: false});23+test('Cannot use subprocess.getOneMessage() with stdio: [..., "ipc"]', testRequiredIpcSubprocess, 'getOneMessage', stdioIpc);24+test('Cannot use subprocess.getEachMessage() without ipc option', testRequiredIpcSubprocess, 'getEachMessage', {});25+test('Cannot use subprocess.getEachMessage() with ipc: false', testRequiredIpcSubprocess, 'getEachMessage', {ipc: false});26+test('Cannot use subprocess.getEachMessage() with stdio: [..., "ipc"]', testRequiredIpcSubprocess, 'getEachMessage', stdioIpc);27+28+const testRequiredIpcExports = async (t, methodName, options) => {29+ const {message} = await t.throwsAsync(execa('ipc-any.js', [methodName], options));30+ t.true(message.includes(`${methodName}() can only be used`));31+};32+33+test('Cannot use exports.sendMessage() without ipc option', testRequiredIpcExports, 'sendMessage', {});34+test('Cannot use exports.sendMessage() with ipc: false', testRequiredIpcExports, 'sendMessage', {ipc: false});35+test('Cannot use exports.getOneMessage() without ipc option', testRequiredIpcExports, 'getOneMessage', {});36+test('Cannot use exports.getOneMessage() with ipc: false', testRequiredIpcExports, 'getOneMessage', {ipc: false});37+test('Cannot use exports.getEachMessage() without ipc option', testRequiredIpcExports, 'getEachMessage', {});38+test('Cannot use exports.getEachMessage() with ipc: false', testRequiredIpcExports, 'getEachMessage', {ipc: false});39+40+const testPostDisconnection = async (t, methodName) => {41+ const subprocess = execa('empty.js', {ipc: true});42+ await subprocess;43+ const {message} = t.throws(() => subprocess[methodName](foobarString));44+ t.true(message.includes(`subprocess.${methodName}() cannot be used`));45+};46+47+test('subprocess.sendMessage() after disconnection', testPostDisconnection, 'sendMessage');48+test('subprocess.getOneMessage() after disconnection', testPostDisconnection, 'getOneMessage');49+test('subprocess.getEachMessage() after disconnection', testPostDisconnection, 'getEachMessage');50+51+const testPostDisconnectionSubprocess = async (t, methodName) => {52+ const subprocess = execa('ipc-disconnect.js', [methodName], {ipc: true});53+ subprocess.disconnect();54+ const {message} = await t.throwsAsync(subprocess);55+ t.true(message.includes(`${methodName}() cannot be used`));56+};57+58+test('exports.sendMessage() after disconnection', testPostDisconnectionSubprocess, 'sendMessage');59+test('exports.getOneMessage() after disconnection', testPostDisconnectionSubprocess, 'getOneMessage');60+test('exports.getEachMessage() after disconnection', testPostDisconnectionSubprocess, 'getEachMessage');61+62+const testInvalidPayload = async (t, serialization, message) => {63+ const subprocess = execa('empty.js', {ipc: true, serialization});64+ await t.throwsAsync(subprocess.sendMessage(message), {message: /type is invalid/});65+ await subprocess;66+};67+68+const cycleObject = {};69+cycleObject.self = cycleObject;70+const toJsonCycle = {toJSON: () => ({test: true, toJsonCycle})};71+72+test('subprocess.sendMessage() cannot send undefined', testInvalidPayload, 'advanced', undefined);73+test('subprocess.sendMessage() cannot send bigints', testInvalidPayload, 'advanced', 0n);74+test('subprocess.sendMessage() cannot send symbols', testInvalidPayload, 'advanced', Symbol('test'));75+test('subprocess.sendMessage() cannot send functions', testInvalidPayload, 'advanced', () => {});76+test('subprocess.sendMessage() cannot send promises', testInvalidPayload, 'advanced', Promise.resolve());77+test('subprocess.sendMessage() cannot send proxies', testInvalidPayload, 'advanced', new Proxy({}, {}));78+test('subprocess.sendMessage() cannot send Intl', testInvalidPayload, 'advanced', new Intl.Collator());79+test('subprocess.sendMessage() cannot send undefined, JSON', testInvalidPayload, 'json', undefined);80+test('subprocess.sendMessage() cannot send bigints, JSON', testInvalidPayload, 'json', 0n);81+test('subprocess.sendMessage() cannot send symbols, JSON', testInvalidPayload, 'json', Symbol('test'));82+test('subprocess.sendMessage() cannot send functions, JSON', testInvalidPayload, 'json', () => {});83+test('subprocess.sendMessage() cannot send cycles, JSON', testInvalidPayload, 'json', cycleObject);84+test('subprocess.sendMessage() cannot send cycles in toJSON(), JSON', testInvalidPayload, 'json', toJsonCycle);85+86+test('exports.sendMessage() validates payload', async t => {87+ const subprocess = execa('ipc-echo-item.js', {ipc: true});88+ await subprocess.sendMessage([undefined]);89+ await t.throwsAsync(subprocess, {90+ message: /sendMessage\(\)'s argument type is invalid/,91+ });92+});modified:test/methods/node.js+19 added-20 removed
1-import {once} from 'node:events';1 import {dirname, relative} from 'node:path';2 import process, {version} from 'node:process';3 import {pathToFileURL} from 'node:url';4 import test from 'ava';5 import getNode from 'get-node';7-import {pEvent} from 'p-event';6 import {execa, execaSync, execaNode} from '../../index.js';7 import {FIXTURES_DIRECTORY} from '../helpers/fixtures-directory.js';8 import {identity, fullStdio} from '../helpers/stdio.js';9 import {foobarString} from '../helpers/input.js';212 unmodified lines222 test.serial('The "nodeOptions" option forbids --inspect with the same port when defined by current process - execaNode()', testInspectSamePort, 'execaNode');223 test.serial('The "nodeOptions" option forbids --inspect with the same port when defined by current process - "node" option', testInspectSamePort, 'nodeOption');224 225 const testIpc = async (t, execaMethod, options) => {228- const subprocess = execaMethod('send.js', [], options);229- await pEvent(subprocess, 'message');230- subprocess.send(foobarString);231- const {stdout, stdio} = await subprocess;232- t.is(stdout, foobarString);226+ const subprocess = execaMethod('ipc-echo.js', [], options);227+228+ await subprocess.sendMessage(foobarString);229+ t.is(await subprocess.getOneMessage(), foobarString);230+231+ const {stdio} = await subprocess;232 t.is(stdio.length, 4);233 t.is(stdio[3], undefined);234 };235 4 unmodified lines240 test('The "ipc" option works with "stdio: [\'pipe\', \'pipe\', \'pipe\']"', testIpc, runWithIpc, {stdio: ['pipe', 'pipe', 'pipe']});241 test('The "ipc" option works with "stdio: [\'pipe\', \'pipe\', \'pipe\', \'ipc\']"', testIpc, runWithIpc, {stdio: ['pipe', 'pipe', 'pipe', 'ipc']});242 test('The "ipc" option works with "stdout: \'pipe\'"', testIpc, runWithIpc, {stdout: 'pipe'});243 244+const NO_SEND_MESSAGE = 'sendMessage() can only be used';245+246 test('No ipc channel is added by default', async t => {246- const {stdio} = await t.throwsAsync(execa('node', ['send.js']), {message: /process.send is not a function/});247+ const {message, stdio} = await t.throwsAsync(execa('node', ['ipc-send.js']));248+ t.true(message.includes(NO_SEND_MESSAGE));249 t.is(stdio.length, 3);250 });251 252 const testDisableIpc = async (t, execaMethod) => {251- const {failed, message, stdio} = await execaMethod('send.js', [], {ipc: false, reject: false});253+ const {failed, message, stdio} = await execaMethod('ipc-send.js', [], {ipc: false, reject: false});254 t.true(failed);253- t.true(message.includes('process.send is not a function'));255+ t.true(message.includes(NO_SEND_MESSAGE));256 t.is(stdio.length, 3);257 };258 259 test('Can disable "ipc" - execaNode()', testDisableIpc, execaNode);3 unmodified lines263 const NO_IPC_MESSAGE = /The "ipc: true" option cannot be used/;264 265 const testNoIpcSync = (t, node) => {266 t.throws(() => {265- execaSync('node', ['send.js'], {ipc: true, node});267+ execaSync('node', ['ipc-send.js'], {ipc: true, node});268 }, {message: NO_IPC_MESSAGE});269 };270 271 test('Cannot use "ipc: true" with execaSync()', testNoIpcSync, undefined);272 test('Cannot use "ipc: true" with execaSync() - "node: false"', testNoIpcSync, false);273 274 test('Cannot use "ipc: true" with execaSync() - "node: true"', t => {275 t.throws(() => {274- execaSync('send.js', {ipc: true, node: true});276+ execaSync('ipc-send.js', {ipc: true, node: true});277 }, {message: NO_IPC_MESSAGE});278 });279 280 const testNoShell = async (t, execaMethod) => {7 unmodified lines288 test('Cannot use "shell: true" - "node" option sync', testNoShell, runWithNodeOptionSync);289 290 test('The "serialization" option defaults to "advanced"', async t => {291 const subprocess = execa('node', ['ipc-echo.js'], {ipc: true});290- subprocess.send([0n]);291- const [message] = await once(subprocess, 'message');292+ await subprocess.sendMessage([0n]);293+ const message = await subprocess.getOneMessage();294 t.is(message[0], 0n);295 await subprocess;296 });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'});298- t.throws(() => {299- subprocess.send([0n]);300- }, {message: /serialize a BigInt/});301- subprocess.send(0);302- const [message] = await once(subprocess, 'message');303- t.is(message, 0);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;304 });modified:test/resolve/no-buffer.js+8 added-3 removed
1 unmodified line2 import test from 'ava';3 import getStream from 'get-stream';4 import {execa, execaSync} from '../../index.js';5 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6-import {fullStdio, getStdio} from '../helpers/stdio.js';6+import {fullStdio} from '../helpers/stdio.js';7 import {foobarString, foobarUppercase, foobarUppercaseUint8Array} from '../helpers/input.js';8 import {resultGenerator, uppercaseGenerator, uppercaseBufferGenerator} from '../helpers/generator.js';9 10 setFixtureDirectory();11 12 const testLateStream = async (t, fdNumber, all) => {13- const subprocess = execa('noop-fd-ipc.js', [`${fdNumber}`, foobarString], {...getStdio(4, 'ipc', 4), buffer: false, all});14- await once(subprocess, 'message');13+ const subprocess = execa('noop-fd-ipc.js', [`${fdNumber}`, foobarString], {14+ ...fullStdio,15+ ipc: true,16+ buffer: false,17+ all,18+ });19+ await subprocess.getOneMessage();20 const [output, allOutput] = await Promise.all([21 getStream(subprocess.stdio[fdNumber]),22 all ? getStream(subprocess.all) : undefined,23 subprocess,174 unmodified linesmodified:test/terminate/cleanup.js+2 added-3 removed
1 import process from 'node:process';2 import {setTimeout} from 'node:timers/promises';3 import test from 'ava';4-import {pEvent} from 'p-event';4 import isRunning from 'is-running';5 import {execa, execaSync} from '../../index.js';6 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';7 import {nestedExecaAsync, nestedWorker} from '../helpers/nested.js';19 unmodified lines27 test('spawnAndExit cleanup detached, worker', spawnAndExit, nestedWorker, true, true);28 29 // When current process exits before subprocess30 const spawnAndKill = async (t, [signal, cleanup, detached, isKilled]) => {32- const subprocess = execa('subprocess.js', [cleanup, detached], {stdio: 'ignore', ipc: true});31+ const subprocess = execa('ipc-send-pid.js', [cleanup, detached], {stdio: 'ignore', ipc: true});32 34- const pid = await pEvent(subprocess, 'message');33+ const pid = await subprocess.getOneMessage();34 t.true(Number.isInteger(pid));35 t.true(isRunning(pid));36 37 process.kill(subprocess.pid, signal);64 unmodified linesmodified:test/terminate/kill-force.js+1 added-2 removed
1 unmodified line2 import {once, defaultMaxListeners} from 'node:events';3 import {constants} from 'node:os';4 import {setTimeout} from 'node:timers/promises';5 import test from 'ava';6-import {pEvent} from 'p-event';6 import isRunning from 'is-running';7 import {execa} from '../../index.js';8 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';9 import {assertMaxListeners} from '../helpers/listeners.js';7 unmodified lines17 ipc: true,18 forceKillAfterDelay,19 ...options,20 });22- await pEvent(subprocess, 'message');21+ await subprocess.getOneMessage();22 return {subprocess};23 };24 25 const spawnNoKillableSimple = options => execa('forever.js', {killSignal: 'SIGWINCH', forceKillAfterDelay: 1, ...options});116 unmodified linesadded:test-d/ipc/get-each.test-d.ts+23 added
1+import {expectType, expectError} from 'tsd';2+import {getEachMessage, execa, type Message} from '../../index.js';3+4+for await (const message of getEachMessage()) {5+ expectType<Message>(message);6+}7+8+expectError(getEachMessage(''));9+10+const subprocess = execa('test', {ipc: true});11+12+for await (const message of subprocess.getEachMessage()) {13+ expectType<Message<'advanced'>>(message);14+}15+16+for await (const message of execa('test', {ipc: true, serialization: 'json'}).getEachMessage()) {17+ expectType<Message<'json'>>(message);18+}19+20+expectError(subprocess.getEachMessage(''));21+expectError(await execa('test').getEachMessage());22+expectError(await execa('test', {ipc: false}).getEachMessage());23+added:test-d/ipc/get-one.test-d.ts+13 added
1+import {expectType, expectError} from 'tsd';2+import {getOneMessage, execa, type Message} from '../../index.js';3+4+expectType<Promise<Message>>(getOneMessage());5+expectError(await getOneMessage(''));6+7+const subprocess = execa('test', {ipc: true});8+expectType<Message<'advanced'>>(await subprocess.getOneMessage());9+expectType<Message<'json'>>(await execa('test', {ipc: true, serialization: 'json'}).getOneMessage());10+11+expectError(await subprocess.getOneMessage(''));12+expectError(await execa('test').getOneMessage());13+expectError(await execa('test', {ipc: false}).getOneMessage());added:test-d/ipc/message.test-d.ts+133 added
1+import {File} from 'node:buffer';2+import {expectAssignable, expectNotAssignable} from 'tsd';3+import {sendMessage, type Message} from '../../index.js';4+5+await sendMessage('');6+expectAssignable<Message>('');7+expectAssignable<Message<'advanced'>>('');8+expectAssignable<Message<'json'>>('');9+10+await sendMessage(0);11+expectAssignable<Message>(0);12+expectAssignable<Message<'advanced'>>(0);13+expectAssignable<Message<'json'>>(0);14+15+await sendMessage(true);16+expectAssignable<Message>(true);17+expectAssignable<Message<'advanced'>>(true);18+expectAssignable<Message<'json'>>(true);19+20+await sendMessage([] as const);21+expectAssignable<Message>([] as const);22+expectAssignable<Message<'advanced'>>([] as const);23+expectAssignable<Message<'json'>>([] as const);24+25+await sendMessage([true] as const);26+expectAssignable<Message>([true] as const);27+expectAssignable<Message<'advanced'>>([true] as const);28+expectAssignable<Message<'json'>>([true] as const);29+30+await sendMessage([undefined] as const);31+expectAssignable<Message>([undefined] as const);32+expectAssignable<Message<'advanced'>>([undefined] as const);33+expectNotAssignable<Message<'json'>>([undefined] as const);34+35+await sendMessage([0n] as const);36+expectAssignable<Message>([0n] as const);37+expectAssignable<Message<'advanced'>>([0n] as const);38+expectNotAssignable<Message<'json'>>([0n] as const);39+40+await sendMessage({} as const);41+expectAssignable<Message>({} as const);42+expectAssignable<Message<'advanced'>>({} as const);43+expectAssignable<Message<'json'>>({} as const);44+45+await sendMessage({test: true} as const);46+expectAssignable<Message>({test: true} as const);47+expectAssignable<Message<'advanced'>>({test: true} as const);48+expectAssignable<Message<'json'>>({test: true} as const);49+50+await sendMessage({test: undefined} as const);51+expectAssignable<Message>({test: undefined} as const);52+expectAssignable<Message<'advanced'>>({test: undefined} as const);53+expectNotAssignable<Message<'json'>>({test: undefined} as const);54+55+await sendMessage({test: 0n} as const);56+expectAssignable<Message>({test: 0n} as const);57+expectAssignable<Message<'advanced'>>({test: 0n} as const);58+expectNotAssignable<Message<'json'>>({test: 0n} as const);59+60+await sendMessage(null);61+expectAssignable<Message>(null);62+expectAssignable<Message<'advanced'>>(null);63+expectAssignable<Message<'json'>>(null);64+65+await sendMessage(Number.NaN);66+expectAssignable<Message>(Number.NaN);67+expectAssignable<Message<'advanced'>>(Number.NaN);68+expectAssignable<Message<'json'>>(Number.NaN);69+70+await sendMessage(Number.POSITIVE_INFINITY);71+expectAssignable<Message>(Number.POSITIVE_INFINITY);72+expectAssignable<Message<'advanced'>>(Number.POSITIVE_INFINITY);73+expectAssignable<Message<'json'>>(Number.POSITIVE_INFINITY);74+75+await sendMessage(new Map());76+expectAssignable<Message>(new Map());77+expectAssignable<Message<'advanced'>>(new Map());78+expectNotAssignable<Message<'json'>>(new Map());79+80+await sendMessage(new Set());81+expectAssignable<Message>(new Set());82+expectAssignable<Message<'advanced'>>(new Set());83+expectNotAssignable<Message<'json'>>(new Set());84+85+await sendMessage(new Date());86+expectAssignable<Message>(new Date());87+expectAssignable<Message<'advanced'>>(new Date());88+expectNotAssignable<Message<'json'>>(new Date());89+90+await sendMessage(/regexp/);91+expectAssignable<Message>(/regexp/);92+expectAssignable<Message<'advanced'>>(/regexp/);93+expectNotAssignable<Message<'json'>>(/regexp/);94+95+await sendMessage(new Blob());96+expectAssignable<Message>(new Blob());97+expectAssignable<Message<'advanced'>>(new Blob());98+expectNotAssignable<Message<'json'>>(new Blob());99+100+await sendMessage(new File([], ''));101+expectAssignable<Message>(new File([], ''));102+expectAssignable<Message<'advanced'>>(new File([], ''));103+expectNotAssignable<Message<'json'>>(new File([], ''));104+105+await sendMessage(new DataView(new ArrayBuffer(0)));106+expectAssignable<Message>(new DataView(new ArrayBuffer(0)));107+expectAssignable<Message<'advanced'>>(new DataView(new ArrayBuffer(0)));108+expectNotAssignable<Message<'json'>>(new DataView(new ArrayBuffer(0)));109+110+await sendMessage(new ArrayBuffer(0));111+expectAssignable<Message>(new ArrayBuffer(0));112+expectAssignable<Message<'advanced'>>(new ArrayBuffer(0));113+expectNotAssignable<Message<'json'>>(new ArrayBuffer(0));114+115+await sendMessage(new SharedArrayBuffer(0));116+expectAssignable<Message>(new SharedArrayBuffer(0));117+expectAssignable<Message<'advanced'>>(new SharedArrayBuffer(0));118+expectNotAssignable<Message<'json'>>(new SharedArrayBuffer(0));119+120+await sendMessage(new Uint8Array());121+expectAssignable<Message>(new Uint8Array());122+expectAssignable<Message<'advanced'>>(new Uint8Array());123+expectNotAssignable<Message<'json'>>(new Uint8Array());124+125+await sendMessage(AbortSignal.abort());126+expectAssignable<Message>(AbortSignal.abort());127+expectAssignable<Message<'advanced'>>(AbortSignal.abort());128+expectNotAssignable<Message<'json'>>(AbortSignal.abort());129+130+await sendMessage(new Error('test'));131+expectAssignable<Message>(new Error('test'));132+expectAssignable<Message<'advanced'>>(new Error('test'));133+expectNotAssignable<Message<'json'>>(new Error('test'));added:test-d/ipc/send.test-d.ts+16 added
1+import {expectType, expectError} from 'tsd';2+import {sendMessage, execa} from '../../index.js';3+4+expectType<Promise<void>>(sendMessage(''));5+6+expectError(await sendMessage());7+expectError(await sendMessage(undefined));8+expectError(await sendMessage(0n));9+expectError(await sendMessage(Symbol('test')));10+11+const subprocess = execa('test', {ipc: true});12+expectType<void>(await subprocess.sendMessage(''));13+14+expectError(await subprocess.sendMessage());15+expectError(await execa('test').sendMessage(''));16+expectError(await execa('test', {ipc: false}).sendMessage(''));modified:test-d/subprocess/subprocess.test-d.ts-10 removed
26 unmodified lines27 expectError(subprocess.kill(null, new Error('test')));28 29 const ipcSubprocess = execa('unicorns', {ipc: true});30 expectAssignable<Subprocess>(subprocess);31-32-expectType<boolean>(ipcSubprocess.send({}));33-execa('unicorns', {stdio: ['pipe', 'pipe', 'pipe', 'ipc']}).send({});34-execa('unicorns', {stdio: ['pipe', 'pipe', 'ipc', 'pipe']}).send({});35-ipcSubprocess.send('message');36-ipcSubprocess.send({}, undefined, {keepOpen: true});37-expectError(ipcSubprocess.send({}, true));38-expectType<undefined>(execa('unicorns', {}).send);39-expectType<undefined>(execa('unicorns', {ipc: false}).send);40-expectType<undefined>(execa('unicorns', {stdio: ['pipe', 'pipe', 'pipe', 'pipe']}).send);modified:types/arguments/options.d.ts+1 added-1 removed
196 unmodified lines197 */198 readonly buffer?: FdGenericOption<boolean>;199 200 /**201- Enables exchanging messages with the subprocess using `subprocess.send(message)` and `subprocess.on('message', (message) => {})`.201+ Enables exchanging messages with the subprocess using `subprocess.sendMessage(message)`, `subprocess.getOneMessage()` and `subprocess.getEachMessage()`.202 203 @default `true` if the `node` option is enabled, `false` otherwise204 */205 readonly ipc?: Unless<IsSync, boolean>;167 unmodified linesmodified:types/subprocess/subprocess.d.ts+4 added-13 removed
9 unmodified lines10 WritableOptions,11 DuplexOptions,12 SubprocessAsyncIterable,13 } from '../convert.js';14+import type {IpcMethods} from '../ipc.js';15 import type {SubprocessStdioStream} from './stdout.js';16 import type {SubprocessStdioArray} from './stdio.js';17 import type {SubprocessAll} from './all.js';18 11 unmodified lines30 */31 pid?: number;32 33 /**33- Send a `message` to the subprocess. The type of `message` depends on the `serialization` option.34- The subprocess receives it as a [`message` event](https://nodejs.org/api/process.html#event-message).35-36- This returns `true` on success.37-38- This requires the `ipc` option to be `true`.39-40- [More info.](https://nodejs.org/api/child_process.html#subprocesssendmessage-sendhandle-options-callback)41- */42- send: HasIpc<OptionsType> extends true ? ChildProcess['send'] : undefined;43-44- /**34 The subprocess [`stdin`](https://en.wikipedia.org/wiki/Standard_streams#Standard_input_(stdin)) as a stream.35 36 This is `null` if the `stdin` option is set to `'inherit'`, `'ignore'`, `Readable` or `integer`.37 */64 unmodified lines102 /**103 Converts the subprocess to a duplex stream.104 */105 duplex(duplexOptions?: DuplexOptions): Duplex;106+}107+& IpcMethods<OptionsType['ipc'], OptionsType['serialization']>117-} & PipableSubprocess;108+& PipableSubprocess;109 110 /**111 [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess) with additional methods and properties.112 */12 unmodified linesadded:types/ipc.d.ts+85 added
1+import type {Options} from './arguments/options.js';2+3+// Message when the `serialization` option is `'advanced'`4+type AdvancedMessage =5+ | string6+ | number7+ | boolean8+ | null9+ | object;10+11+// Message when the `serialization` option is `'json'`12+type JsonMessage =13+ | string14+ | number15+ | boolean16+ | null17+ | readonly JsonMessage[]18+ | {readonly [key: string | number]: JsonMessage};19+20+/**21+Type of messages exchanged between a process and its subprocess using `sendMessage()`, `getOneMessage()` and `getEachMessage()`.22+23+This requires the `ipc` option to be `true`. The type of `message` depends on the `serialization` option.24+*/25+export type Message<26+ Serialization extends Options['serialization'] = Options['serialization'],27+> = Serialization extends 'json' ? JsonMessage : AdvancedMessage;28+29+// IPC methods in subprocess30+/**31+Send a `message` to the parent process.32+33+This requires the `ipc` option to be `true`. The type of `message` depends on the `serialization` option.34+*/35+export function sendMessage(message: Message): Promise<void>;36+37+/**38+Receive a single `message` from the parent process.39+40+This requires the `ipc` option to be `true`. The type of `message` depends on the `serialization` option.41+*/42+export function getOneMessage(): Promise<Message>;43+44+/**45+Iterate over each `message` from the parent process.46+47+This requires the `ipc` option to be `true`. The type of `message` depends on the `serialization` option.48+*/49+export function getEachMessage(): AsyncIterableIterator<Message>;50+51+// IPC methods in the current process52+export type IpcMethods<53+ IpcOption extends Options['ipc'],54+ Serialization extends Options['serialization'],55+> = IpcOption extends true56+ ? {57+ /**58+ Send a `message` to the subprocess.59+60+ This requires the `ipc` option to be `true`. The type of `message` depends on the `serialization` option.61+ */62+ sendMessage(message: Message<Serialization>): Promise<void>;63+64+ /**65+ Receive a single `message` from the subprocess.66+67+ This requires the `ipc` option to be `true`. The type of `message` depends on the `serialization` option.68+ */69+ getOneMessage(): Promise<Message<Serialization>>;70+71+ /**72+ Iterate over each `message` from the subprocess.73+74+ This requires the `ipc` option to be `true`. The type of `message` depends on the `serialization` option.75+ */76+ getEachMessage(): AsyncIterableIterator<Message<Serialization>>;77+ }78+ // Those methods only work if the `ipc` option is `true`.79+ // At runtime, they are actually defined, in order to provide with a nice error message.80+ // At type check time, they are typed as `never` to prevent calling them.81+ : {82+ sendMessage: never;83+ getOneMessage: never;84+ getEachMessage: never;85+ };modified:index.d.ts+10 added-1 removed
3 unmodified lines4 StdoutStderrOption,5 StdoutStderrSyncOption,6 } from './types/stdio/type.js';7 export type {Options, SyncOptions} from './types/arguments/options.js';8+export type {TemplateExpression} from './types/methods/template.js';9+10 export type {Result, SyncResult} from './types/return/result.js';11 export type {ResultPromise, Subprocess} from './types/subprocess/subprocess.js';12 export {ExecaError, ExecaSyncError} from './types/return/final-error.js';11-export type {TemplateExpression} from './types/methods/template.js';13+14 export {execa} from './types/methods/main-async.js';15 export {execaSync} from './types/methods/main-sync.js';16 export {execaCommand, execaCommandSync, parseCommandString} from './types/methods/command.js';17 export {$} from './types/methods/script.js';18 export {execaNode} from './types/methods/node.js';19+20+export {21+ sendMessage,22+ getOneMessage,23+ getEachMessage,24+ type Message,25+} from './types/ipc.js';modified:index.js+4 added
1 import {createExeca} from './lib/methods/create.js';2 import {mapCommandAsync, mapCommandSync} from './lib/methods/command.js';3 import {mapNode} from './lib/methods/node.js';4 import {mapScriptAsync, setScriptSync, deepScriptOptions} from './lib/methods/script.js';5+import {getIpcExport} from './lib/ipc/methods.js';6 7 export {parseCommandString} from './lib/methods/command.js';8 export {ExecaError, ExecaSyncError} from './lib/return/final-error.js';9 2 unmodified lines12 export const execaCommand = createExeca(mapCommandAsync);13 export const execaCommandSync = createExeca(mapCommandSync);14 export const execaNode = createExeca(mapNode);15 export const $ = createExeca(mapScriptAsync, {}, deepScriptOptions, setScriptSync);16+17+const {sendMessage, getOneMessage, getEachMessage} = getIpcExport();18+export {sendMessage, getOneMessage, getEachMessage};modified:package.json-1 removed
68 unmodified lines69 "ava": "^6.0.1",70 "c8": "^9.1.0",71 "get-node": "^15.0.0",72 "is-running": "^2.1.0",73- "p-event": "^6.0.0",73 "path-exists": "^5.0.0",74 "path-key": "^4.0.0",75 "tempfile": "^5.0.0",76 "tsd": "^0.31.0",27 unmodified linesmodified:readme.md+20 added
65 unmodified lines66 - Retrieve the output [programmatically and print it](#programmatic--terminal-output) on the console at the same time.67 - [Transform or filter](#transformfilter-output) the input and output with [simple functions](docs/transform.md).68 - Redirect the [input](docs/input.md) and [output](docs/output.md) from/to [files](#files), [strings](#simple-input), [`Uint8Array`s](docs/binary.md#binary-input), [iterables](docs/streams.md#iterables-as-input) or [objects](docs/transform.md#object-mode).69 - Pass [Node.js streams](docs/streams.md#nodejs-streams) or [web streams](#web-streams) to subprocesses, or [convert](#convert-to-duplex-stream) subprocesses to [a stream](docs/streams.md#converting-a-subprocess-to-a-stream).70+- [Exchange messages](#exchange-messages) with the subprocess.71 - Ensure subprocesses exit even when they [intercept termination signals](docs/termination.md#forceful-termination), or when the current process [ends abruptly](docs/termination.md#current-process-exit).72 73 ## Install74 177 unmodified lines252 createWriteStream('./output.txt'),253 );254 ```255 256+#### Exchange messages257+258+```js259+// parent.js260+import {execaNode} from 'execa';261+262+const subprocess = execaNode`child.js`;263+console.log(await subprocess.getOneMessage()); // 'Hello from child'264+await subprocess.sendMessage('Hello from parent');265+```266+267+```js268+// child.js269+import {sendMessage, getOneMessage} from 'execa';270+271+await sendMessage('Hello from child');272+console.log(await getOneMessage()); // 'Hello from parent'273+```274+275 ### Debugging276 277 #### Detailed error278 62 unmodified lines