Debounce `message` events (#1087)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent d6f5d9a · Browse files · 63 files·+854 added−772 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
63 files+854 added−772 removed
- tests:+693 added−412 removed
- other:+161 added−360 removed
Provenance
- Commit
e8bab97- Tree
46e753f- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
d6f5d9a
63 files changed+854 added−772 removed
modified:docs/api.md+1 added-25 removed
134 unmodified lines135 This requires the [`ipc`](#optionsipc) option to be `true`. The [type](ipc.md#message-type) of `message` depends on the [`serialization`](#optionsserialization) option.136 137 [More info.](ipc.md#listening-to-messages)138 139-### exchangeMessage(message, getOneMessageOptions?)140-141-`message`: [`Message`](ipc.md#message-type)\142-_getOneMessageOptions_: [`GetOneMessageOptions`](#getonemessageoptions)\143-_Returns_: [`Promise<Message>`](ipc.md#message-type)144-145-Send a `message` to the parent process, then receive a response from it.146-147-This requires the [`ipc`](#optionsipc) option to be `true`. The [type](ipc.md#message-type) of `message` depends on the [`serialization`](#optionsserialization) option.148-149-[More info.](ipc.md#exchanging-messages)150-139 ## Return value140 141 _TypeScript:_ [`ResultPromise`](typescript.md)\142 _Type:_ `Promise<object> | Subprocess`149 unmodified lines292 This requires the [`ipc`](#optionsipc) option to be `true`. The [type](ipc.md#message-type) of `message` depends on the [`serialization`](#optionsserialization) option.293 294 [More info.](ipc.md#listening-to-messages)295 308-### subprocess.exchangeMessage(message, getOneMessageOptions?)309-310-`message`: [`Message`](ipc.md#message-type)\311-_getOneMessageOptions_: [`GetOneMessageOptions`](#getonemessageoptions)\312-_Returns_: [`Promise<Message>`](ipc.md#message-type)313-314-Send a `message` to the subprocess, then receive a response from it.315-316-This requires the [`ipc`](#optionsipc) option to be `true`. The [type](ipc.md#message-type) of `message` depends on the [`serialization`](#optionsserialization) option.317-318-[More info.](ipc.md#exchanging-messages)319-296 ### subprocess.stdin297 298 _Type:_ [`Writable | null`](https://nodejs.org/api/stream.html#class-streamwritable)299 613 unmodified lines913 914 _Type:_ `boolean`\915 _Default:_ `true` if either the [`node`](#optionsnode) option or the [`ipcInput`](#optionsipcinput) is set, `false` otherwise916 941-Enables exchanging messages with the subprocess using [`subprocess.sendMessage(message)`](#subprocesssendmessagemessage), [`subprocess.getOneMessage()`](#subprocessgetonemessagegetonemessageoptions), [`subprocess.exchangeMessage(message)`](#subprocessexchangemessagemessage-getonemessageoptions) and [`subprocess.getEachMessage()`](#subprocessgeteachmessage).917+Enables exchanging messages with the subprocess using [`subprocess.sendMessage(message)`](#subprocesssendmessagemessage), [`subprocess.getOneMessage()`](#subprocessgetonemessagegetonemessageoptions) and [`subprocess.getEachMessage()`](#subprocessgeteachmessage).918 919 The subprocess must be a Node.js file.920 921 [More info.](ipc.md)199 unmodified linesmodified:docs/execution.md+1 added-1 removed
124 unmodified linesExpand all1251261271281291291301311321334 unmodified lines124 unmodified linesExpand all- The [`stdin`](api.md#optionsstdin), [`stdout`](api.md#optionsstdout), [`stderr`](api.md#optionsstderr) and [`stdio`](api.md#optionsstdio) options cannot be [`'overlapped'`](api.md#optionsstdout), an [async iterable](lines.md#progressive-splitting), an async [transform](transform.md), a [`Duplex`](transform.md#duplextransform-streams), nor a [web stream](streams.md#web-streams). Node.js streams can be passed but only if either they [have a file descriptor](streams.md#file-descriptors), or the [`input`](api.md#optionsinput) option is used.- Signal termination: [`subprocess.kill()`](api.md#subprocesskillerror), [`subprocess.pid`](api.md#subprocesspid), [`cleanup`](api.md#optionscleanup) option, [`cancelSignal`](api.md#optionscancelsignal) option, [`forceKillAfterDelay`](api.md#optionsforcekillafterdelay) option.- Piping multiple subprocesses: [`subprocess.pipe()`](api.md#subprocesspipefile-arguments-options).- [`subprocess.iterable()`](lines.md#progressive-splitting).- [IPC](ipc.md): [`sendMessage()`](api.md#sendmessagemessage), [`getOneMessage()`](api.md#getonemessagegetonemessageoptions), [`exchangeMessage()`](api.md#exchangemessagemessage-getonemessageoptions), [`getEachMessage()`](api.md#geteachmessage), [`result.ipcOutput`](output.md#any-output-type), [`ipc`](api.md#optionsipc) option, [`serialization`](api.md#optionsserialization) option, [`ipcInput`](input.md#any-input-type) option.- [IPC](ipc.md): [`sendMessage()`](api.md#sendmessagemessage), [`getOneMessage()`](api.md#getonemessagegetonemessageoptions), [`getEachMessage()`](api.md#geteachmessage), [`result.ipcOutput`](output.md#any-output-type), [`ipc`](api.md#optionsipc) option, [`serialization`](api.md#optionsserialization) option, [`ipcInput`](input.md#any-input-type) option.- [`result.all`](api.md#resultall) is not interleaved.- [`detached`](api.md#optionsdetached) option.- The [`maxBuffer`](api.md#optionsmaxbuffer) option is always measured in bytes, not in characters, [lines](api.md#optionslines) nor [objects](transform.md#object-mode). Also, it ignores transforms and the [`encoding`](api.md#optionsencoding) option.
4 unmodified linesmodified:docs/ipc.md+15 added-85 removed
10 unmodified lines11 When 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](node.md).12 13 The `ipc` option defaults to `true` when using [`execaNode()`](node.md#run-nodejs-files) or the [`node`](node.md#run-nodejs-files) option.14 15-The current process sends messages with [`subprocess.sendMessage(message)`](api.md#subprocesssendmessagemessage) and receives them with [`subprocess.getOneMessage()`](api.md#subprocessgetonemessagegetonemessageoptions). [`subprocess.exchangeMessage(message)`](api.md#subprocessexchangemessagemessage-getonemessageoptions) combines both: first it sends a message, then it returns the response.15+The current process sends messages with [`subprocess.sendMessage(message)`](api.md#subprocesssendmessagemessage) and receives them with [`subprocess.getOneMessage()`](api.md#subprocessgetonemessagegetonemessageoptions).16 17-The subprocess uses [`sendMessage(message)`](api.md#sendmessagemessage), [`getOneMessage()`](api.md#getonemessagegetonemessageoptions) and [`exchangeMessage(message)`](api.md#exchangemessagemessage-getonemessageoptions) instead. Those are the same methods, but imported directly from the `'execa'` module.17+The subprocess uses [`sendMessage(message)`](api.md#sendmessagemessage) and [`getOneMessage()`](api.md#getonemessagegetonemessageoptions). Those are the same methods, but imported directly from the `'execa'` module.18 19 ```js20 // parent.js21 import {execaNode} from 'execa';22 23 const subprocess = execaNode`child.js`;24-const message = await subprocess.exchangeMessage('Hello from parent');24+await subprocess.sendMessage('Hello from parent');25+const message = await subprocess.getOneMessage();26 console.log(message); // 'Hello from child'27 ```28 29 ```js6 unmodified lines36 ```37 38 ## Listening to messages39 39-The methods described above read a single message. On the other hand, [`subprocess.getEachMessage()`](api.md#subprocessgeteachmessage) and [`getEachMessage()`](api.md#geteachmessage) return an [async iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols). This should be [preferred](#prefer-geteachmessage-over-multiple-getonemessage) when listening to multiple messages.40+The methods described above read a single message. On the other hand, [`subprocess.getEachMessage()`](api.md#subprocessgeteachmessage) and [`getEachMessage()`](api.md#geteachmessage) return an [async iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols). This should be preferred when listening to multiple messages.41 42 [`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).43 44 ```js103 unmodified lines148 ```149 150 ## Messages order151 151-The messages are always received in the same order they were sent.152+The messages are always received in the same order they were sent. Even when sent all at once.153 153-## Debugging154-155-When the [`verbose`](api.md#optionsverbose) option is `'full'`, the IPC messages sent by the subprocess to the current process are [printed on the console](debugging.md#full-mode).156-157-Also, when the subprocess [failed](errors.md#subprocess-failure), [`error.ipcOutput`](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).158-159-## Best practices160-161-### Call `getOneMessage()`/`getEachMessage()` early162-163-If a process sends a message but the other process is not listening/receiving it, that message is silently ignored.164-165-This means if [`getOneMessage()`](api.md#getonemessagegetonemessageoptions) or [`getEachMessage()`](api.md#geteachmessage) is called too late (i.e. after the other process called [`sendMessage(message)`](api.md#sendmessagemessage)), it will miss the message. Also, it will keep waiting for the missed message, which might either make it hang forever, or throw when the other process exits.166-167-Therefore, listening to messages should always be done early, before the other process sends any message.168-169-### First `getOneMessage()` call170-171-On the other hand, the _very first_ call to [`getOneMessage()`](api.md#getonemessagegetonemessageoptions), [`getEachMessage()`](api.md#geteachmessage) or [`exchangeMessage(message)`](api.md#exchangemessagemessage-getonemessageoptions) never misses any message. That's because, when a subprocess is just starting, any message sent to it is buffered.172-173-This allows the current process to call [`subprocess.sendMessage(message)`](api.md#subprocesssendmessagemessage) right after spawning the subprocess, even if it is still initializing.174-154 ```js176-// parent.js177-import {execaNode} from 'execa';155+import {sendMessage} from 'execa';156 179-const subprocess = execaNode`child.js`;180-await subprocess.sendMessage('Hello');181-await subprocess.sendMessage('world');157+await Promise.all([158+ sendMessage('first'),159+ sendMessage('second'),160+ sendMessage('third'),161+]);162 ```163 184-```js185-// child.js186-import {getOneMessage} from 'execa';164+## Debugging165 188-// This always retrieves the first message.189-// Even if `sendMessage()` was called while the subprocess was still initializing.190-const helloMessage = await getOneMessage();166+When the [`verbose`](api.md#optionsverbose) option is `'full'`, the IPC messages sent by the subprocess to the current process are [printed on the console](debugging.md#full-mode).167 192-// But this might miss the second message, and hang forever.193-// That's because it is not the first call to `getOneMessage()`.194-const worldMessage = await getOneMessage();195-```168+Also, when the subprocess [failed](errors.md#subprocess-failure), [`error.ipcOutput`](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).169 197-### Prefer `getEachMessage()` over multiple `getOneMessage()`198-199-If you call [`getOneMessage()`](api.md#getonemessagegetonemessageoptions) multiple times (like the example above) and the other process sends any message in between those calls, that message [will be missed](#call-getonemessagegeteachmessage-early).200-201-This can be prevented by using [`getEachMessage()`](api.md#geteachmessage) instead.202-203-### Prefer `exchangeMessage(message)` over `sendMessage(message)` + `getOneMessage()`204-205-When _first_ sending a message, _then_ receiving a response, the following code should be avoided.206-207-```js208-import {sendMessage, getOneMessage} from 'execa';209-210-await sendMessage(message);211-212-// The other process might respond between those two calls213-214-const response = await getOneMessage();215-```216-217-Indeed, when [`getOneMessage()`](api.md#getonemessagegetonemessageoptions) is called, the other process might have already sent a response. This only happens when the other process is very fast. However, when it does happen, `getOneMessage()` will miss that response.218-219-Using [`exchangeMessage(message)`](api.md#exchangemessagemessage-getonemessageoptions) prevents this race condition.220-221-```js222-import {exchangeMessage} from 'execa';223-224-const response = await exchangeMessage(message);225-```226-227-However please note that, when doing the reverse (_first_ receiving a message, _then_ sending a response), the following code is correct.228-229-```js230-import {sendMessage, getOneMessage} from 'execa';231-232-const message = await getOneMessage();233-234-// The other process is just waiting for a response between those two calls.235-// So there is no race condition here.236-237-await sendMessage('response');238-```239-170 <hr>171 172 [**Next**: 🐛 Debugging](debugging.md)\173 [**Previous**: ⏳️ Streams](streams.md)\1 unmodified linedeleted:lib/ipc/exchange.js-43 removed
12345678910111213141516171819202122232425262728293031323334353637383940414243import {validateIpcMethod} from './validation.js';import {sendOneMessage} from './send.js';import {onceMessage} from './get-one.js';
// Like `[sub]process.send()` followed by `[sub]process.getOneMessage()`.// Avoids the following race condition: listening to `message` after the other process already responded.export const exchangeMessage = ({anyProcess, anyProcessSend, isSubprocess, ipc}, message, {filter} = {}) => { const methodName = 'exchangeMessage'; validateIpcMethod({ methodName, isSubprocess, ipc, isConnected: anyProcess.connected, });
return exchangeOneMessage({ anyProcess, anyProcessSend, isSubprocess, methodName, message, filter, });};
const exchangeOneMessage = async ({anyProcess, anyProcessSend, isSubprocess, methodName, message, filter}) => { const [response] = await Promise.all([ onceMessage({ anyProcess, isSubprocess, methodName, filter, }), sendOneMessage({ anyProcess, anyProcessSend, isSubprocess, methodName, message, }), ]); return response;};modified:lib/ipc/forward.js+17 added-42 removed
1 import {EventEmitter} from 'node:events';2+import {onMessage, onDisconnect} from './incoming.js';3+import {undoAddedReferences} from './reference.js';4 3-// By default, Node.js keeps the subprocess alive while it has a `message` or `disconnect` listener.4-// This is implemented by calling `.channel.ref()` and `.channel.unref()` automatically.5-// However, this prevents forwarding those events to our proxy, since that requires setting up additional listeners.6-// Therefore, we need to do manual referencing counting.7-// See https://github.com/nodejs/node/blob/2aaeaa863c35befa2ebaa98fb7737ec84df4d8e9/lib/internal/child_process.js#L5478-export const addReference = anyProcess => {9- const referencesCount = IPC_REFERENCES.get(anyProcess) ?? 0;10- if (referencesCount === 0) {11- anyProcess.channel?.ref();12- }13-14- IPC_REFERENCES.set(anyProcess, referencesCount + 1);15-};16-17-export const removeReference = anyProcess => {18- const referencesCount = IPC_REFERENCES.get(anyProcess);19- if (referencesCount === 1) {20- anyProcess.channel?.unref();21- }22-23- IPC_REFERENCES.set(anyProcess, referencesCount - 1);24-};25-26-const IPC_REFERENCES = new WeakMap();27-5 // Forward the `message` and `disconnect` events from the process and subprocess to a proxy emitter.6 // This prevents the `error` event from stopping IPC.7+// This also allows debouncing the `message` event.30-export const getIpcEmitter = anyProcess => {8+export const getIpcEmitter = (anyProcess, isSubprocess) => {9 if (IPC_EMITTERS.has(anyProcess)) {10 return IPC_EMITTERS.get(anyProcess);11 }12 13 // Use an `EventEmitter`, like the `process` that is being proxied14 // eslint-disable-next-line unicorn/prefer-event-target15 const ipcEmitter = new EventEmitter();16+ ipcEmitter.connected = true;17 IPC_EMITTERS.set(anyProcess, ipcEmitter);39- forwardEvents(ipcEmitter, anyProcess);18+ forwardEvents(ipcEmitter, anyProcess, isSubprocess);19 return ipcEmitter;20 };21 22 const IPC_EMITTERS = new WeakMap();23 24 // The `message` and `disconnect` events are buffered in the subprocess until the first listener is setup.25 // However, unbuffering happens after one tick, so this give enough time for the caller to setup the listener on the proxy emitter first.26 // See https://github.com/nodejs/node/blob/2aaeaa863c35befa2ebaa98fb7737ec84df4d8e9/lib/internal/child_process.js#L72148-const forwardEvents = (ipcEmitter, anyProcess) => {49- forwardEvent(ipcEmitter, anyProcess, 'message');50- forwardEvent(ipcEmitter, anyProcess, 'disconnect');27+const forwardEvents = (ipcEmitter, anyProcess, isSubprocess) => {28+ const boundOnMessage = onMessage.bind(undefined, anyProcess, ipcEmitter);29+ anyProcess.on('message', boundOnMessage);30+ anyProcess.once('disconnect', onDisconnect.bind(undefined, {anyProcess, ipcEmitter, boundOnMessage}));31+ undoAddedReferences(anyProcess, isSubprocess);32 };33 53-const forwardEvent = (ipcEmitter, anyProcess, eventName) => {54- const eventListener = forwardListener.bind(undefined, ipcEmitter, eventName);55- anyProcess.on(eventName, eventListener);56- anyProcess.once('disconnect', cleanupListener.bind(undefined, anyProcess, eventName, eventListener));34+// Check whether there might still be some `message` events to receive35+export const isConnected = anyProcess => {36+ const ipcEmitter = IPC_EMITTERS.get(anyProcess);37+ return ipcEmitter === undefined38+ ? anyProcess.channel !== null39+ : ipcEmitter.connected;40 };58-59-const forwardListener = (ipcEmitter, eventName, payload) => {60- ipcEmitter.emit(eventName, payload);61-};62-63-const cleanupListener = (anyProcess, eventName, eventListener) => {64- anyProcess.removeListener(eventName, eventListener);65-};modified:lib/ipc/get-each.js+4 added-3 removed
1 import {once, on} from 'node:events';2 import {validateIpcMethod, disconnect} from './validation.js';3-import {addReference, removeReference, getIpcEmitter} from './forward.js';3+import {getIpcEmitter, isConnected} from './forward.js';4+import {addReference, removeReference} from './reference.js';5 6 // Like `[sub]process.on('message')` but promise-based7 export const getEachMessage = ({anyProcess, isSubprocess, ipc}) => loopOnMessages({8 anyProcess,7 unmodified lines16 validateIpcMethod({17 methodName: 'getEachMessage',18 isSubprocess,19 ipc,19- isConnected: anyProcess.channel !== null,20+ isConnected: isConnected(anyProcess),21 });22 23 addReference(anyProcess);23- const ipcEmitter = getIpcEmitter(anyProcess);24+ const ipcEmitter = getIpcEmitter(anyProcess, isSubprocess);25 const controller = new AbortController();26 stopOnDisconnect(anyProcess, ipcEmitter, controller);27 return iterateOnMessages({28 anyProcess,32 unmodified linesmodified:lib/ipc/get-one.js+10 added-21 removed
1 import {once, on} from 'node:events';2 import {validateIpcMethod, throwOnEarlyDisconnect} from './validation.js';3-import {addReference, removeReference, getIpcEmitter} from './forward.js';3+import {getIpcEmitter, isConnected} from './forward.js';4+import {addReference, removeReference} from './reference.js';5 6 // Like `[sub]process.once('message')` but promise-based7 export const getOneMessage = ({anyProcess, isSubprocess, ipc}, {filter} = {}) => {7- const methodName = 'getOneMessage';8 validateIpcMethod({9- methodName,9+ methodName: 'getOneMessage',10 isSubprocess,11 ipc,12- isConnected: anyProcess.channel !== null,12+ isConnected: isConnected(anyProcess),13 });14 15- return onceMessage({16- anyProcess,17- isSubprocess,18- methodName,19- filter,20- });15+ return getOneMessageAsync(anyProcess, isSubprocess, filter);16 };17 23-// Same but used internally24-export const onceMessage = async ({anyProcess, isSubprocess, methodName, filter}) => {18+const getOneMessageAsync = async (anyProcess, isSubprocess, filter) => {19 addReference(anyProcess);26- const ipcEmitter = getIpcEmitter(anyProcess);20+ const ipcEmitter = getIpcEmitter(anyProcess, isSubprocess);21 const controller = new AbortController();22 try {23 return await Promise.race([24 getMessage(ipcEmitter, filter, controller),31- throwOnDisconnect({32- ipcEmitter,33- isSubprocess,34- methodName,35- controller,36- }),25+ throwOnDisconnect(ipcEmitter, isSubprocess, controller),26 ]);27 } finally {28 controller.abort();29 removeReference(anyProcess);12 unmodified lines42 }43 }44 };45 57-const throwOnDisconnect = async ({ipcEmitter, isSubprocess, methodName, controller: {signal}}) => {46+const throwOnDisconnect = async (ipcEmitter, isSubprocess, {signal}) => {47 await once(ipcEmitter, 'disconnect', {signal});59- throwOnEarlyDisconnect(methodName, isSubprocess);48+ throwOnEarlyDisconnect(isSubprocess);49 };added:lib/ipc/incoming.js+41 added
1234567891011121314151617181920212223242526272829303132333435363738394041import {once} from 'node:events';import {scheduler} from 'node:timers/promises';import {waitForOutgoingMessages} from './outgoing.js';
// Debounce the `message` event so it is emitted at most once per macrotask.// This allows users to call `await getOneMessage()`/`getEachMessage()` multiple times in a row.export const onMessage = async (anyProcess, ipcEmitter, message) => { if (!INCOMING_MESSAGES.has(anyProcess)) { INCOMING_MESSAGES.set(anyProcess, []); }
const incomingMessages = INCOMING_MESSAGES.get(anyProcess); incomingMessages.push(message);
if (incomingMessages.length > 1) { return; }
while (incomingMessages.length > 0) { // eslint-disable-next-line no-await-in-loop await waitForOutgoingMessages(anyProcess); // eslint-disable-next-line no-await-in-loop await scheduler.yield(); ipcEmitter.emit('message', incomingMessages.shift()); }};
const INCOMING_MESSAGES = new WeakMap();
// If the `message` event is currently debounced, the `disconnect` event must wait for itexport const onDisconnect = async ({anyProcess, ipcEmitter, boundOnMessage}) => { const incomingMessages = INCOMING_MESSAGES.get(anyProcess); while (incomingMessages?.length > 0) { // eslint-disable-next-line no-await-in-loop await once(ipcEmitter, 'message'); }
anyProcess.removeListener('message', boundOnMessage); ipcEmitter.connected = false; ipcEmitter.emit('disconnect');};modified:lib/ipc/methods.js-7 removed
1 unmodified line2 import {promisify} from 'node:util';3 import {sendMessage} from './send.js';4 import {getOneMessage} from './get-one.js';5 import {getEachMessage} from './get-each.js';6-import {exchangeMessage} from './exchange.js';6 7 // Add promise-based IPC methods in current process8 export const addIpcMethods = (subprocess, {ipc}) => {9 Object.assign(subprocess, getIpcMethods(subprocess, false, ipc));15 unmodified lines25 ipc,26 }),27 getOneMessage: getOneMessage.bind(undefined, {anyProcess, isSubprocess, ipc}),28 getEachMessage: getEachMessage.bind(undefined, {anyProcess, isSubprocess, ipc}),30- exchangeMessage: exchangeMessage.bind(undefined, {31- anyProcess,32- anyProcessSend,33- isSubprocess,34- ipc,35- }),29 };30 };added:lib/ipc/outgoing.js+30 added
1+import {createDeferred} from '../utils/deferred.js';2+3+// When `sendMessage()` is ongoing, any `message` being received waits before being emitted.4+// This allows calling one or multiple `await sendMessage()` followed by `await getOneMessage()`/`await getEachMessage()`.5+// Without running into a race condition when the other process sends a response too fast, before the current process set up a listener.6+export const startSendMessage = anyProcess => {7+ if (!OUTGOING_MESSAGES.has(anyProcess)) {8+ OUTGOING_MESSAGES.set(anyProcess, new Set());9+ }10+11+ const outgoingMessages = OUTGOING_MESSAGES.get(anyProcess);12+ const onMessageSent = createDeferred();13+ outgoingMessages.add(onMessageSent);14+ return {outgoingMessages, onMessageSent};15+};16+17+export const endSendMessage = ({outgoingMessages, onMessageSent}) => {18+ outgoingMessages.delete(onMessageSent);19+ onMessageSent.resolve();20+};21+22+// Await while `sendMessage()` is ongoing23+export const waitForOutgoingMessages = async anyProcess => {24+ while (OUTGOING_MESSAGES.get(anyProcess)?.size > 0) {25+ // eslint-disable-next-line no-await-in-loop26+ await Promise.all(OUTGOING_MESSAGES.get(anyProcess));27+ }28+};29+30+const OUTGOING_MESSAGES = new WeakMap();added:lib/ipc/reference.js+21 added
1+// By default, Node.js keeps the subprocess alive while it has a `message` or `disconnect` listener.2+// We replicate the same logic for the events that we proxy.3+// This ensures the subprocess is kept alive while `sendMessage()`, `getOneMessage()` and `getEachMessage()` are ongoing.4+// See https://github.com/nodejs/node/blob/2aaeaa863c35befa2ebaa98fb7737ec84df4d8e9/lib/internal/child_process.js#L5475+export const addReference = anyProcess => {6+ anyProcess.channel?.refCounted();7+};8+9+export const removeReference = anyProcess => {10+ anyProcess.channel?.unrefCounted();11+};12+13+// To proxy events, we setup some global listeners on the `message` and `disconnect` events.14+// Those should not keep the subprocess alive, so we remove the automatic counting that Node.js is doing.15+// See https://github.com/nodejs/node/blob/1b965270a9c273d4cf70e8808e9d28b9ada7844f/lib/child_process.js#L18016+export const undoAddedReferences = (anyProcess, isSubprocess) => {17+ if (isSubprocess) {18+ removeReference(anyProcess);19+ removeReference(anyProcess);20+ }21+};modified:lib/ipc/send.js+9 added-14 removed
1 unmodified line2 validateIpcMethod,3 handleSerializationError,4 disconnect,5 } from './validation.js';6+import {startSendMessage, endSendMessage} from './outgoing.js';6-import {addReference, removeReference} from './forward.js';7+import {addReference, removeReference} from './reference.js';8 9 // Like `[sub]process.send()` but promise-based.9-// We do not `await subprocess` during `.sendMessage()`, `.getOneMessage()` nor `.exchangeMessage()` since those methods are transient.10+// We do not `await subprocess` during `.sendMessage()` nor `.getOneMessage()` since those methods are transient.11 // Users would still need to `await subprocess` after the method is done.12 // Also, this would prevent `unhandledRejection` event from being emitted, making it silent.13 export const sendMessage = ({anyProcess, anyProcessSend, isSubprocess, ipc}, message) => {13- const methodName = 'sendMessage';14 validateIpcMethod({15- methodName,15+ methodName: 'sendMessage',16 isSubprocess,17 ipc,18 isConnected: anyProcess.connected,19 });20 21- return sendOneMessage({21+ return sendMessageAsync({22 anyProcess,23 anyProcessSend,24 isSubprocess,25- methodName,25 message,26 });27 };28 30-// Same but used internally31-export const sendOneMessage = async ({anyProcess, anyProcessSend, isSubprocess, methodName, message}) => {29+const sendMessageAsync = async ({anyProcess, anyProcessSend, isSubprocess, message}) => {30 addReference(anyProcess);31+ const outgoingMessagesState = startSendMessage(anyProcess);32 try {33 await anyProcessSend(message);34 } catch (error) {35 disconnect(anyProcess);37- handleSerializationError({38- error,39- isSubprocess,40- methodName,41- message,42- });36+ handleSerializationError(error, isSubprocess, message);37 throw error;38 } finally {39+ endSendMessage(outgoingMessagesState);40 removeReference(anyProcess);41 }42 };modified:lib/ipc/validation.js+4 added-4 removed
18 unmodified lines19 }20 };21 22 // When `getOneMessage()` could not complete due to an early disconnection23-export const throwOnEarlyDisconnect = (methodName, isSubprocess) => {24- throw new Error(`${getNamespaceName(isSubprocess)}${methodName}() could not complete: the ${getOtherProcessName(isSubprocess)} exited or disconnected.`);23+export const throwOnEarlyDisconnect = isSubprocess => {24+ throw new Error(`${getNamespaceName(isSubprocess)}getOneMessage() could not complete: the ${getOtherProcessName(isSubprocess)} exited or disconnected.`);25 };26 27 const getNamespaceName = isSubprocess => isSubprocess ? '' : 'subprocess.';28 29 const getOtherProcessName = isSubprocess => isSubprocess ? 'parent process' : 'subprocess';30 31 // Better error message when sending messages which cannot be serialized.32 // Works with both `serialization: 'advanced'` and `serialization: 'json'`.33-export const handleSerializationError = ({error, isSubprocess, methodName, message}) => {33+export const handleSerializationError = (error, isSubprocess, message) => {34 if (isSerializationError(error)) {35- error.message = `${getNamespaceName(isSubprocess)}${methodName}()'s argument type is invalid: the message cannot be serialized: ${String(message)}.\n${error.message}`;35+ error.message = `${getNamespaceName(isSubprocess)}sendMessage()'s argument type is invalid: the message cannot be serialized: ${String(message)}.\n${error.message}`;36 }37 };38 39 const isSerializationError = ({code, message}) => SERIALIZATION_ERROR_CODES.has(code)28 unmodified linesmodified:test/convert/readable.js+4 added-2 removed
117 unmodified lines118 const stream = subprocess[methodName]();119 120 subprocess.stdout.destroy();121 122+ await subprocess.sendMessage(foobarString);123 const [error, message] = await Promise.all([124 t.throwsAsync(finishedStream(stream)),124- subprocess.exchangeMessage(foobarString),125+ subprocess.getOneMessage(),126 ]);127 t.like(error, prematureClose);128 t.is(message, foobarString);129 assertWritableAborted(t, subprocess.stdin);11 unmodified lines141 142 const cause = new Error(foobarString);143 subprocess.stdout.destroy(cause);144 145+ await subprocess.sendMessage(foobarString);146 const [error, message] = await Promise.all([147 t.throwsAsync(finishedStream(stream)),146- subprocess.exchangeMessage(foobarString),148+ subprocess.getOneMessage(),149 ]);150 t.is(message, foobarString);151 t.is(error.cause, cause);152 assertProcessNormalExit(t, error);307 unmodified linesdeleted:test/fixtures/ipc-echo-filter-exchange.js-5 removed
1-#!/usr/bin/env node2-import {sendMessage, exchangeMessage} from '../../index.js';3-import {foobarArray} from '../helpers/input.js';4-5-await sendMessage(await exchangeMessage('.', ({filter: message => message === foobarArray[1]})));modified:test/fixtures/ipc-echo-filter.js+2 added-1 removed
1 #!/usr/bin/env node2 import {sendMessage, getOneMessage} from '../../index.js';3 import {foobarArray} from '../helpers/input.js';4 5-await sendMessage(await getOneMessage(({filter: message => message === foobarArray[1]})));5+const message = await getOneMessage({filter: message => message === foobarArray[1]});6+await sendMessage(message);deleted:test/fixtures/ipc-echo-item-exchange.js-5 removed
1-#!/usr/bin/env node2-import {exchangeMessage, getOneMessage} from '../../index.js';3-4-const [message] = await getOneMessage();5-await exchangeMessage(message);deleted:test/fixtures/ipc-echo-twice-filter-get.js-10 removed
1-#!/usr/bin/env node2-import {sendMessage, getOneMessage} from '../../index.js';3-import {alwaysPass} from '../helpers/ipc.js';4-5-const message = await getOneMessage({filter: alwaysPass});6-const [secondMessage] = await Promise.all([7- getOneMessage({filter: alwaysPass}),8- sendMessage(message),9-]);10-await sendMessage(secondMessage);deleted:test/fixtures/ipc-echo-twice-filter.js-7 removed
1-#!/usr/bin/env node2-import {sendMessage, getOneMessage, exchangeMessage} from '../../index.js';3-import {alwaysPass} from '../helpers/ipc.js';4-5-const message = await getOneMessage({filter: alwaysPass});6-const secondMessage = await exchangeMessage(message, {filter: alwaysPass});7-await sendMessage(secondMessage);deleted:test/fixtures/ipc-echo-twice-get.js-9 removed
1-#!/usr/bin/env node2-import {sendMessage, getOneMessage} from '../../index.js';3-4-const message = await getOneMessage();5-const [secondMessage] = await Promise.all([6- getOneMessage(),7- sendMessage(message),8-]);9-await sendMessage(await secondMessage);modified:test/fixtures/ipc-echo-twice.js+3 added-2 removed
1 #!/usr/bin/env node2-import {sendMessage, getOneMessage, exchangeMessage} from '../../index.js';2+import {sendMessage, getOneMessage} from '../../index.js';3 4 const message = await getOneMessage();5-const secondMessage = await exchangeMessage(message);5+await sendMessage(message);6+const secondMessage = await getOneMessage();7 await sendMessage(secondMessage);deleted:test/fixtures/ipc-exchange-error.js-4 removed
1-#!/usr/bin/env node2-import {exchangeMessage} from '../../index.js';3-4-await exchangeMessage(0n);added:test/fixtures/ipc-get-send-get.js+12 added
1+#!/usr/bin/env node2+import {argv} from 'node:process';3+import {sendMessage, getOneMessage} from '../../index.js';4+import {alwaysPass} from '../helpers/ipc.js';5+6+const filter = argv[2] === 'true' ? alwaysPass : undefined;7+8+const message = await getOneMessage({filter});9+await Promise.all([10+ getOneMessage({filter}),11+ sendMessage(message),12+]);added:test/fixtures/ipc-iterate-back-serial.js+24 added
1+#!/usr/bin/env node2+import process from 'node:process';3+import {sendMessage, getOneMessage} from '../../index.js';4+import {PARALLEL_COUNT} from '../helpers/parallel.js';5+import {alwaysPass, getFirst} from '../helpers/ipc.js';6+7+const filter = process.argv[2] === 'true' ? alwaysPass : undefined;8+9+await sendMessage(await getOneMessage({filter}));10+11+const promise = sendMessage(1);12+process.emit('message', '.');13+await promise;14+15+const messages = Array.from({length: PARALLEL_COUNT}, (_, index) => index + 2);16+for (const message of messages) {17+ // eslint-disable-next-line no-await-in-loop18+ await sendMessage(message);19+}20+21+const secondPromise = process.argv[3] === 'true'22+ ? getFirst()23+ : getOneMessage({filter});24+await sendMessage(await secondPromise);added:test/fixtures/ipc-iterate-back.js+20 added
1+#!/usr/bin/env node2+import process from 'node:process';3+import {sendMessage, getOneMessage} from '../../index.js';4+import {PARALLEL_COUNT} from '../helpers/parallel.js';5+import {alwaysPass, getFirst} from '../helpers/ipc.js';6+7+const filter = process.argv[2] === 'true' ? alwaysPass : undefined;8+9+await sendMessage(await getOneMessage({filter}));10+11+const messages = Array.from({length: PARALLEL_COUNT}, (_, index) => index + 1);12+await Promise.all([13+ ...messages.map(message => sendMessage(message)),14+ process.emit('message', '.'),15+]);16+17+const promise = process.argv[3] === 'true'18+ ? getFirst()19+ : getOneMessage({filter});20+await sendMessage(await promise);modified:test/fixtures/ipc-iterate-break.js+2 added-1 removed
1 #!/usr/bin/env node2 import {sendMessage, getEachMessage} from '../../index.js';3 import {foobarString} from '../helpers/input.js';4 5+const iterable = getEachMessage();6 await sendMessage(foobarString);7 8 // eslint-disable-next-line no-unreachable-loop8-for await (const _ of getEachMessage()) {9+for await (const _ of iterable) {10 break;11 }modified:test/fixtures/ipc-iterate-print.js+3 added-1 removed
1 unmodified line2 import process from 'node:process';3 import {sendMessage, getEachMessage} from '../../index.js';4 import {foobarString} from '../helpers/input.js';5 6+const iterable = getEachMessage();7+8 await sendMessage(foobarString);9 8-for await (const message of getEachMessage()) {10+for await (const message of iterable) {11 if (message === foobarString) {12 break;13 }14 2 unmodified linesmodified:test/fixtures/ipc-iterate-throw.js+2 added-1 removed
1 #!/usr/bin/env node2 import {sendMessage, getEachMessage} from '../../index.js';3 import {foobarString} from '../helpers/input.js';4 5+const iterable = getEachMessage();6 await sendMessage(foobarString);7 8 // eslint-disable-next-line no-unreachable-loop8-for await (const message of getEachMessage()) {9+for await (const message of iterable) {10 throw new Error(message);11 }added:test/fixtures/ipc-once-disconnect-get.js+11 added
1+#!/usr/bin/env node2+import process from 'node:process';3+import {getOneMessage} from '../../index.js';4+5+await getOneMessage();6+7+process.once('disconnect', () => {8+ console.log('.');9+});10+11+process.send('.');added:test/fixtures/ipc-once-disconnect-send.js+11 added
1+#!/usr/bin/env node2+import process from 'node:process';3+import {sendMessage} from '../../index.js';4+5+await sendMessage('.');6+7+process.once('disconnect', () => {8+ console.log('.');9+});10+11+process.send('.');added:test/fixtures/ipc-once-disconnect.js+8 added
1+#!/usr/bin/env node2+import process from 'node:process';3+4+process.send('.');5+6+process.once('disconnect', () => {7+ console.log('.');8+});added:test/fixtures/ipc-once-message-get.js+11 added
1+#!/usr/bin/env node2+import process from 'node:process';3+import {getOneMessage} from '../../index.js';4+5+await getOneMessage();6+7+process.once('message', message => {8+ console.log(message);9+});10+11+process.send('.');added:test/fixtures/ipc-once-message-send.js+9 added
1+#!/usr/bin/env node2+import process from 'node:process';3+import {sendMessage} from '../../index.js';4+5+await sendMessage('.');6+7+process.once('message', message => {8+ console.log(message);9+});added:test/fixtures/ipc-once-message.js+8 added
1+#!/usr/bin/env node2+import process from 'node:process';3+4+process.send('.');5+6+process.once('message', message => {7+ console.log(message);8+});added:test/fixtures/ipc-print-many-each.js+13 added
1+#!/usr/bin/env node2+import {argv} from 'node:process';3+import {getEachMessage} from '../../index.js';4+5+const count = Number(argv[2]);6+7+for (let index = 0; index < count; index += 1) {8+ // eslint-disable-next-line no-await-in-loop, no-unreachable-loop9+ for await (const message of getEachMessage()) {10+ console.log(message);11+ break;12+ }13+}added:test/fixtures/ipc-print-many.js+12 added
1+#!/usr/bin/env node2+import {argv} from 'node:process';3+import {getOneMessage} from '../../index.js';4+import {alwaysPass} from '../helpers/ipc.js';5+6+const count = Number(argv[2]);7+const filter = argv[3] === 'true' ? alwaysPass : undefined;8+9+for (let index = 0; index < count; index += 1) {10+ // eslint-disable-next-line no-await-in-loop11+ console.log(await getOneMessage({filter}));12+}deleted:test/fixtures/ipc-process-error-exchange.js-11 removed
1-#!/usr/bin/env node2-import process from 'node:process';3-import {exchangeMessage, sendMessage} from '../../index.js';4-import {foobarString} from '../helpers/input.js';5-import {alwaysPass} from '../helpers/ipc.js';6-7-process.on('error', () => {});8-const filter = process.argv[2] === 'true' ? alwaysPass : undefined;9-const promise = exchangeMessage('.', {filter});10-process.emit('error', new Error(foobarString));11-await sendMessage(await promise);added:test/fixtures/ipc-process-send-get.js+10 added
1+#!/usr/bin/env node2+import process from 'node:process';3+import {foobarString} from '../helpers/input.js';4+import {getOneMessage} from '../../index.js';5+6+await getOneMessage();7+8+process.send(foobarString, () => {9+ console.log('.');10+});added:test/fixtures/ipc-process-send-send.js+10 added
1+#!/usr/bin/env node2+import process from 'node:process';3+import {foobarString} from '../helpers/input.js';4+import {sendMessage} from '../../index.js';5+6+await sendMessage('.');7+8+process.send(foobarString, () => {9+ console.log('.');10+});added:test/fixtures/ipc-process-send.js+7 added
1+#!/usr/bin/env node2+import process from 'node:process';3+import {foobarString} from '../helpers/input.js';4+5+process.send(foobarString, () => {6+ console.log('.');7+});deleted:test/fixtures/ipc-send-get.js-5 removed
1-#!/usr/bin/env node2-import {exchangeMessage} from '../../index.js';3-import {foobarString} from '../helpers/input.js';4-5-await exchangeMessage(foobarString);added:test/fixtures/ipc-send-many.js+6 added
1+#!/usr/bin/env node2+import {argv} from 'node:process';3+import {sendMessage} from '../../index.js';4+5+const count = Number(argv[2]);6+await Promise.all(Array.from({length: count}, (_, index) => sendMessage(index)));added:test/fixtures/ipc-send-repeat.js+9 added
1+#!/usr/bin/env node2+import {argv} from 'node:process';3+import {sendMessage} from '../../index.js';4+5+const count = Number(argv[2]);6+for (let index = 0; index < count; index += 1) {7+ // eslint-disable-next-line no-await-in-loop8+ await sendMessage(index);9+}added:test/fixtures/ipc-send-wait-print.js+8 added
1+#!/usr/bin/env node2+import {setTimeout} from 'node:timers/promises';3+import {sendMessage} from '../../index.js';4+import {foobarString} from '../helpers/input.js';5+6+await sendMessage(foobarString);7+await setTimeout(100);8+console.log('.');modified:test/helpers/ipc.js+15 added-15 removed
1-import isPlainObj from 'is-plain-obj';1+import {getEachMessage} from '../../index.js';2 3-export const subprocessGetOne = (subprocess, options) => subprocess.getOneMessage(options);4-5-export const subprocessSendGetOne = async (subprocess, message) => {6- const [response] = await Promise.all([7- subprocess.getOneMessage(),8- subprocess.sendMessage(message),9- ]);10- return response;11-};12-13-export const subprocessExchange = (subprocess, messageOrOptions) => isPlainObj(messageOrOptions)14- ? subprocess.exchangeMessage('.', messageOrOptions)15- : subprocess.exchangeMessage(messageOrOptions);16-3 // @todo: replace with Array.fromAsync(subprocess.getEachMessage()) after dropping support for Node <22.0.04 export const iterateAllMessages = async subprocess => {5 const messages = [];6 for await (const message of subprocess.getEachMessage()) {2 unmodified lines9 10 return messages;11 };12 13+export const subprocessGetFirst = async subprocess => {14+ const [firstMessage] = await iterateAllMessages(subprocess);15+ return firstMessage;16+};17+18+export const getFirst = async () => {19+ // eslint-disable-next-line no-unreachable-loop20+ for await (const message of getEachMessage()) {21+ return message;22+ }23+};24+25+export const subprocessGetOne = (subprocess, options) => subprocess.getOneMessage(options);26+27 export const alwaysPass = () => true;modified:test/ipc/buffer-messages.js-15 removed
64 unmodified lines65 t.deepEqual(ipcOutput, [`${index}`]);66 }),67 );68 });69-70-test('"error" event does not interrupt result.ipcOutput', async t => {71- const subprocess = execa('ipc-echo-twice.js', {ipcInput: foobarString});72-73- const cause = new Error(foobarString);74- subprocess.emit('error', cause);75- t.is(await subprocess.getOneMessage(), foobarString);76- t.is(await subprocess.exchangeMessage(foobarString), foobarString);77-78- const error = await t.throwsAsync(subprocess);79- t.is(error.exitCode, undefined);80- t.false(error.isTerminated);81- t.is(error.cause, cause);82- t.deepEqual(error.ipcOutput, [foobarString, foobarString]);83-});added:test/ipc/forward.js+96 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+import {iterateAllMessages, alwaysPass} from '../helpers/ipc.js';6+7+setFixtureDirectory();8+9+const testParentErrorOne = async (t, filter, buffer) => {10+ const subprocess = execa('ipc-send.js', {ipc: true, buffer});11+12+ const promise = subprocess.getOneMessage({filter});13+ const cause = new Error(foobarString);14+ subprocess.emit('error', cause);15+ t.is(await promise, foobarString);16+17+ const error = await t.throwsAsync(subprocess);18+ t.is(error.exitCode, undefined);19+ t.false(error.isTerminated);20+ t.is(error.cause, cause);21+ if (buffer) {22+ t.deepEqual(error.ipcOutput, [foobarString]);23+ }24+};25+26+test('"error" event does not interrupt subprocess.getOneMessage(), buffer false', testParentErrorOne, undefined, false);27+test('"error" event does not interrupt subprocess.getOneMessage(), buffer true', testParentErrorOne, undefined, true);28+test('"error" event does not interrupt subprocess.getOneMessage(), buffer false, filter', testParentErrorOne, alwaysPass, false);29+test('"error" event does not interrupt subprocess.getOneMessage(), buffer true, filter', testParentErrorOne, alwaysPass, true);30+31+const testSubprocessErrorOne = async (t, filter, buffer) => {32+ const subprocess = execa('ipc-process-error.js', [`${filter}`], {ipc: true, buffer});33+ await subprocess.sendMessage(foobarString);34+ t.is(await subprocess.getOneMessage(), foobarString);35+36+ const {ipcOutput} = await subprocess;37+ if (buffer) {38+ t.deepEqual(ipcOutput, [foobarString]);39+ }40+};41+42+test('"error" event does not interrupt exports.getOneMessage(), buffer false', testSubprocessErrorOne, false, false);43+test('"error" event does not interrupt exports.getOneMessage(), buffer true', testSubprocessErrorOne, false, true);44+test('"error" event does not interrupt exports.getOneMessage(), buffer false, filter', testSubprocessErrorOne, true, false);45+test('"error" event does not interrupt exports.getOneMessage(), buffer true, filter', testSubprocessErrorOne, true, true);46+47+const testParentErrorEach = async (t, buffer) => {48+ const subprocess = execa('ipc-send-twice.js', {ipc: true, buffer});49+50+ const promise = iterateAllMessages(subprocess);51+ const cause = new Error(foobarString);52+ subprocess.emit('error', cause);53+54+ const error = await t.throwsAsync(subprocess);55+ t.is(error, await t.throwsAsync(promise));56+ t.is(error.exitCode, undefined);57+ t.false(error.isTerminated);58+ t.is(error.cause, cause);59+ if (buffer) {60+ t.deepEqual(error.ipcOutput, foobarArray);61+ }62+};63+64+test('"error" event does not interrupt subprocess.getEachMessage(), buffer false', testParentErrorEach, false);65+test('"error" event does not interrupt subprocess.getEachMessage(), buffer true', testParentErrorEach, true);66+67+const testSubprocessErrorEach = async (t, filter, buffer) => {68+ const subprocess = execa('ipc-iterate-error.js', [`${filter}`], {ipc: true, buffer});69+ await subprocess.sendMessage('.');70+ t.is(await subprocess.getOneMessage(), '.');71+ await subprocess.sendMessage(foobarString);72+73+ const {ipcOutput} = await subprocess;74+ if (buffer) {75+ t.deepEqual(ipcOutput, ['.']);76+ }77+};78+79+test('"error" event does not interrupt exports.getEachMessage(), buffer false', testSubprocessErrorEach, 'ipc-iterate-error.js', false);80+test('"error" event does not interrupt exports.getEachMessage(), buffer true', testSubprocessErrorEach, 'ipc-iterate-error.js', true);81+82+test('"error" event does not interrupt result.ipcOutput', async t => {83+ const subprocess = execa('ipc-echo-twice.js', {ipcInput: foobarString});84+85+ const cause = new Error(foobarString);86+ subprocess.emit('error', cause);87+ t.is(await subprocess.getOneMessage(), foobarString);88+ await subprocess.sendMessage(foobarString);89+ t.is(await subprocess.getOneMessage(), foobarString);90+91+ const error = await t.throwsAsync(subprocess);92+ t.is(error.exitCode, undefined);93+ t.false(error.isTerminated);94+ t.is(error.cause, cause);95+ t.deepEqual(error.ipcOutput, [foobarString, foobarString]);96+});modified:test/ipc/get-each.js+31 added-70 removed
1 import test from 'ava';2 import {execa} from '../../index.js';3 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';4 import {foobarString, foobarArray} from '../helpers/input.js';5-import {iterateAllMessages} from '../helpers/ipc.js';5 import {PARALLEL_COUNT} from '../helpers/parallel.js';6+import {iterateAllMessages} from '../helpers/ipc.js';7 8 setFixtureDirectory();9 10 test('Can iterate over IPC messages', async t => {17 unmodified lines28 const {ipcOutput} = await subprocess;29 t.deepEqual(ipcOutput, ['.', '.']);30 });31 32-test('Can iterate multiple times over IPC messages in subprocess', async t => {33- const subprocess = execa('ipc-iterate-twice.js', {ipc: true});34-35- t.is(await subprocess.getOneMessage(), foobarString);36- t.is(await subprocess.exchangeMessage('.'), '0.');37- t.is(await subprocess.exchangeMessage(foobarString), foobarString);38- t.is(await subprocess.exchangeMessage('.'), '1.');39- await subprocess.sendMessage(foobarString);40-41- const {ipcOutput} = await subprocess;42- t.deepEqual(ipcOutput, [foobarString, '0.', foobarString, '1.']);43-});44-32 test('subprocess.getEachMessage() can be called twice at the same time', async t => {33 const subprocess = execa('ipc-send-twice.js', {ipc: true});34 t.deepEqual(35 await Promise.all([iterateAllMessages(subprocess), iterateAllMessages(subprocess)]),3 unmodified lines39 const {ipcOutput} = await subprocess;40 t.deepEqual(ipcOutput, foobarArray);41 });42 56-const loopAndBreak = async (t, subprocess) => {43+const iterateAndBreak = async (t, subprocess) => {44 // eslint-disable-next-line no-unreachable-loop45 for await (const message of subprocess.getEachMessage()) {46 t.is(message, foobarString);47 break;1 unmodified line49 };50 51 test('Breaking in subprocess.getEachMessage() disconnects', async t => {52 const subprocess = execa('ipc-iterate-send.js', {ipc: true});66- await loopAndBreak(t, subprocess);53+ await iterateAndBreak(t, subprocess);54 const {ipcOutput} = await subprocess;55 t.deepEqual(ipcOutput, [foobarString]);56 });57 58 test('Breaking from subprocess.getEachMessage() awaits the subprocess', async t => {72- const subprocess = execa('ipc-send-get.js', {ipc: true});59+ const subprocess = execa('ipc-send-wait-print.js', {ipc: true});60+ await iterateAndBreak(t, subprocess);61 74- const {exitCode, isTerminated, message, ipcOutput} = await t.throwsAsync(loopAndBreak(t, subprocess));75- t.is(exitCode, 1);76- t.false(isTerminated);77- t.true(message.includes('Error: exchangeMessage() could not complete'));62+ const {ipcOutput, stdout} = await subprocess;63 t.deepEqual(ipcOutput, [foobarString]);64+ t.is(stdout, '.');65 });66 67 test('Breaking from exports.getEachMessage() disconnects', async t => {68 const subprocess = execa('ipc-iterate-break.js', {ipc: true});69 70 t.is(await subprocess.getOneMessage(), foobarString);71+ await subprocess.sendMessage(foobarString);85- const ipcError = await t.throwsAsync(subprocess.exchangeMessage(foobarString));86- t.true(ipcError.message.includes('subprocess.exchangeMessage() could not complete'));72+ const ipcError = await t.throwsAsync(subprocess.getOneMessage());73+ t.true(ipcError.message.includes('subprocess.getOneMessage() could not complete'));74 75 const {ipcOutput} = await subprocess;76 t.deepEqual(ipcOutput, [foobarString]);77 });78 92-const iterateAndError = async (t, subprocess, cause) => {79+const iterateAndThrow = async (t, subprocess, cause) => {80 // eslint-disable-next-line no-unreachable-loop81 for await (const message of subprocess.getEachMessage()) {82 t.is(message, foobarString);83 throw cause;3 unmodified lines87 test('Throwing from subprocess.getEachMessage() disconnects', async t => {88 const subprocess = execa('ipc-iterate-send.js', {ipc: true});89 90 const cause = new Error(foobarString);104- t.is(await t.throwsAsync(iterateAndError(t, subprocess, cause)), cause);91+ t.is(await t.throwsAsync(iterateAndThrow(t, subprocess, cause)), cause);92 93 const {ipcOutput} = await subprocess;94 t.deepEqual(ipcOutput, [foobarString]);95 });96 97 test('Throwing from subprocess.getEachMessage() awaits the subprocess', async t => {111- const subprocess = execa('ipc-send-get.js', {ipc: true});112-98+ const subprocess = execa('ipc-send-wait-print.js', {ipc: true});99 const cause = new Error(foobarString);114- t.is(await t.throwsAsync(iterateAndError(t, subprocess, cause)), cause);100+ t.is(await t.throwsAsync(iterateAndThrow(t, subprocess, cause)), cause);101 116- const {exitCode, isTerminated, message, ipcOutput} = await t.throwsAsync(subprocess);117- t.is(exitCode, 1);118- t.false(isTerminated);119- t.true(message.includes('Error: exchangeMessage() could not complete'));102+ const {ipcOutput, stdout} = await subprocess;103 t.deepEqual(ipcOutput, [foobarString]);104+ t.is(stdout, '.');105 });106 107 test('Throwing from exports.getEachMessage() disconnects', async t => {108 const subprocess = execa('ipc-iterate-throw.js', {ipc: true});109 110 t.is(await subprocess.getOneMessage(), foobarString);111+ await subprocess.sendMessage(foobarString);127- const ipcError = await t.throwsAsync(subprocess.exchangeMessage(foobarString));128- t.true(ipcError.message.includes('subprocess.exchangeMessage() could not complete'));112+ const ipcError = await t.throwsAsync(subprocess.getOneMessage());113+ t.true(ipcError.message.includes('subprocess.getOneMessage() could not complete'));114 115 const {exitCode, isTerminated, message, ipcOutput} = await t.throwsAsync(subprocess);116 t.is(exitCode, 1);117 t.false(isTerminated);9 unmodified lines127 const {ipcOutput} = await subprocess;128 t.deepEqual(ipcOutput, Array.from({length: PARALLEL_COUNT}, (_, index) => index));129 });130 131+test('subprocess.getOneMessage() can be called multiple times in a row, buffer true', async t => {132+ const subprocess = execa('ipc-print-many-each.js', [`${PARALLEL_COUNT}`], {ipc: true});133+ const indexes = Array.from({length: PARALLEL_COUNT}, (_, index) => `${index}`);134+ await Promise.all(indexes.map(index => subprocess.sendMessage(index)));135+136+ const {stdout} = await subprocess;137+ const expectedOutput = indexes.join('\n');138+ t.is(stdout, expectedOutput);139+});140+141 test('Disconnecting in the current process stops exports.getEachMessage()', async t => {142 const subprocess = execa('ipc-iterate-print.js', {ipc: true});143 t.is(await subprocess.getOneMessage(), foobarString);144 await subprocess.sendMessage('.');22 unmodified lines167 const {ipcOutput} = await subprocess;168 t.deepEqual(ipcOutput, [foobarString]);169 });170 176-const testParentError = async (t, buffer) => {177- const subprocess = execa('ipc-send-twice.js', {ipc: true, buffer});178-179- const promise = iterateAllMessages(subprocess);180- const cause = new Error(foobarString);181- subprocess.emit('error', cause);182-183- const error = await t.throwsAsync(subprocess);184- t.is(error, await t.throwsAsync(promise));185- t.is(error.exitCode, undefined);186- t.false(error.isTerminated);187- t.is(error.cause, cause);188- if (buffer) {189- t.deepEqual(error.ipcOutput, foobarArray);190- }191-};192-193-test('"error" event does not interrupt subprocess.getEachMessage(), buffer false', testParentError, false);194-test('"error" event does not interrupt subprocess.getEachMessage(), buffer true', testParentError, true);195-196-const testSubprocessError = async (t, filter, buffer) => {197- const subprocess = execa('ipc-iterate-error.js', [`${filter}`], {ipc: true, buffer});198- t.is(await subprocess.exchangeMessage('.'), '.');199- await subprocess.sendMessage(foobarString);200-201- const {ipcOutput} = await subprocess;202- if (buffer) {203- t.deepEqual(ipcOutput, ['.']);204- }205-};206-207-test('"error" event does not interrupt exports.getEachMessage(), buffer false', testSubprocessError, 'ipc-iterate-error.js', false);208-test('"error" event does not interrupt exports.getEachMessage(), buffer true', testSubprocessError, 'ipc-iterate-error.js', true);209-171 const testCleanupListeners = async (t, buffer) => {172 const subprocess = execa('ipc-send.js', {ipc: true, buffer});173 174 t.is(subprocess.listenerCount('message'), buffer ? 1 : 0);214- t.is(subprocess.listenerCount('disconnect'), buffer ? 3 : 0);175+ t.is(subprocess.listenerCount('disconnect'), buffer ? 1 : 0);176 177 const promise = iterateAllMessages(subprocess);178 t.is(subprocess.listenerCount('message'), 1);218- t.is(subprocess.listenerCount('disconnect'), 3);179+ t.is(subprocess.listenerCount('disconnect'), 1);180 t.deepEqual(await promise, [foobarString]);181 182 t.is(subprocess.listenerCount('message'), 0);183 t.is(subprocess.listenerCount('disconnect'), 0);4 unmodified linesmodified:test/ipc/get-one.js+44 added-151 removed
2 unmodified lines3 import test from 'ava';4 import {execa} from '../../index.js';5 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6 import {foobarString, foobarArray} from '../helpers/input.js';7-import {8- subprocessGetOne,9- subprocessSendGetOne,10- subprocessExchange,11- alwaysPass,12-} from '../helpers/ipc.js';7+import {alwaysPass} from '../helpers/ipc.js';8 import {PARALLEL_COUNT} from '../helpers/parallel.js';9 10 setFixtureDirectory();11 17-const testKeepAlive = async (t, buffer, exchangeMethod) => {18- const subprocess = execa('ipc-echo-twice.js', {ipc: true, buffer});19- t.is(await exchangeMethod(subprocess, foobarString), foobarString);20- t.is(await exchangeMethod(subprocess, foobarString), foobarString);21- await subprocess;22-};23-24-test('subprocess.getOneMessage() keeps the subprocess alive, buffer false', testKeepAlive, false, subprocessSendGetOne);25-test('subprocess.getOneMessage() keeps the subprocess alive, buffer true', testKeepAlive, true, subprocessSendGetOne);26-test('subprocess.getOneMessage() keeps the subprocess alive, buffer false, exchangeMessage()', testKeepAlive, false, subprocessExchange);27-test('subprocess.getOneMessage() keeps the subprocess alive, buffer true, exchangeMessage()', testKeepAlive, true, subprocessExchange);28-29-const testBufferInitial = async (t, buffer, exchangeMethod) => {12+const testBufferInitial = async (t, buffer) => {13 const subprocess = execa('ipc-echo-wait.js', {ipc: true, buffer});31- t.is(await exchangeMethod(subprocess, foobarString), foobarString);14+ await subprocess.sendMessage(foobarString);15+ t.is(await subprocess.getOneMessage(), foobarString);16 await subprocess;17 };18 35-test('Buffers initial message to subprocess, buffer false', testBufferInitial, false, subprocessSendGetOne);36-test('Buffers initial message to subprocess, buffer true', testBufferInitial, true, subprocessSendGetOne);37-test('Buffers initial message to subprocess, buffer false, exchangeMessage()', testBufferInitial, false, subprocessExchange);38-test('Buffers initial message to subprocess, buffer true, exchangeMessage()', testBufferInitial, true, subprocessExchange);19+test('Buffers initial message to subprocess, buffer false', testBufferInitial, false);20+test('Buffers initial message to subprocess, buffer true', testBufferInitial, true);21 22 test('Buffers initial message to current process, buffer false', async t => {23 const subprocess = execa('ipc-send-print.js', {ipc: true, buffer: false});24 const [chunk] = await once(subprocess.stdout, 'data');13 unmodified lines38 const {ipcOutput} = await subprocess;39 t.deepEqual(ipcOutput, [foobarString]);40 });41 60-const testFilterParent = async (t, exchangeMethod) => {42+test('subprocess.getOneMessage() can filter messages', async t => {43 const subprocess = execa('ipc-send-twice.js', {ipc: true});62- const message = await exchangeMethod(subprocess, {filter: message => message === foobarArray[1]});44+ const message = await subprocess.getOneMessage({filter: message => message === foobarArray[1]});45 t.is(message, foobarArray[1]);46 47 const {ipcOutput} = await subprocess;48 t.deepEqual(ipcOutput, foobarArray);67-};49+});50 69-test('subprocess.getOneMessage() can filter messages', testFilterParent, subprocessGetOne);70-test('subprocess.exchangeMessage() can filter messages', testFilterParent, subprocessExchange);71-72-const testFilterSubprocess = async (t, fixtureName, expectedOutput) => {73- const subprocess = execa(fixtureName, {ipc: true});51+test('exports.getOneMessage() can filter messages', async t => {52+ const subprocess = execa('ipc-echo-filter.js', {ipc: true});53 await subprocess.sendMessage(foobarArray[0]);54 await subprocess.sendMessage(foobarArray[1]);55 56 const {ipcOutput} = await subprocess;78- t.deepEqual(ipcOutput, expectedOutput);79-};57+ t.deepEqual(ipcOutput, [foobarArray[1]]);58+});59 81-test('exports.getOneMessage() can filter messages', testFilterSubprocess, 'ipc-echo-filter.js', [foobarArray[1]]);82-test('exports.exchangeMessage() can filter messages', testFilterSubprocess, 'ipc-echo-filter-exchange.js', ['.', foobarArray[1]]);83-84-const testHeavyLoad = async (t, exchangeMethod) => {60+test.serial('Can retrieve initial IPC messages under heavy load', async t => {61 await Promise.all(62 Array.from({length: PARALLEL_COUNT}, async (_, index) => {63 const subprocess = execa('ipc-send-argv.js', [`${index}`], {ipc: true, buffer: false});88- t.is(await exchangeMethod(subprocess, {}), `${index}`);64+ t.is(await subprocess.getOneMessage(), `${index}`);65 await subprocess;66 }),67 );92-};68+});69 94-test.serial('Can retrieve initial IPC messages under heavy load', testHeavyLoad, subprocessGetOne);95-test.serial('Can retrieve initial IPC messages under heavy load, exchangeMessage()', testHeavyLoad, subprocessExchange);96-97-const testTwice = async (t, exchangeMethod, buffer, filter) => {70+const testTwice = async (t, buffer, filter) => {71 const subprocess = execa('ipc-send.js', {ipc: true, buffer});72 t.deepEqual(100- await Promise.all([exchangeMethod(subprocess, {filter}), exchangeMethod(subprocess, {filter})]),73+ await Promise.all([subprocess.getOneMessage({filter}), subprocess.getOneMessage({filter})]),74 [foobarString, foobarString],75 );76 await subprocess;77 };78 106-test('subprocess.getOneMessage() can be called twice at the same time, buffer false', testTwice, subprocessGetOne, false, undefined);107-test('subprocess.getOneMessage() can be called twice at the same time, buffer true', testTwice, subprocessGetOne, true, undefined);108-test('subprocess.getOneMessage() can be called twice at the same time, buffer false, filter', testTwice, subprocessGetOne, false, alwaysPass);109-test('subprocess.getOneMessage() can be called twice at the same time, buffer true, filter', testTwice, subprocessGetOne, true, alwaysPass);110-test('subprocess.exchangeMessage() can be called twice at the same time, buffer false', testTwice, subprocessExchange, false, undefined);111-test('subprocess.exchangeMessage() can be called twice at the same time, buffer true', testTwice, subprocessExchange, true, undefined);112-test('subprocess.exchangeMessage() can be called twice at the same time, buffer false, filter', testTwice, subprocessExchange, false, alwaysPass);113-test('subprocess.exchangeMessage() can be called twice at the same time, buffer true, filter', testTwice, subprocessExchange, true, alwaysPass);79+test('subprocess.getOneMessage() can be called twice at the same time, buffer false', testTwice, false, undefined);80+test('subprocess.getOneMessage() can be called twice at the same time, buffer true', testTwice, true, undefined);81+test('subprocess.getOneMessage() can be called twice at the same time, buffer false, filter', testTwice, false, alwaysPass);82+test('subprocess.getOneMessage() can be called twice at the same time, buffer true, filter', testTwice, true, alwaysPass);83 115-const testCleanupListeners = async (t, exchangeMethod, buffer, filter) => {84+const testCleanupListeners = async (t, buffer, filter) => {85 const subprocess = execa('ipc-send.js', {ipc: true, buffer});86 87 t.is(subprocess.listenerCount('message'), buffer ? 1 : 0);119- t.is(subprocess.listenerCount('disconnect'), buffer ? 3 : 0);88+ t.is(subprocess.listenerCount('disconnect'), buffer ? 1 : 0);89 121- const promise = exchangeMethod(subprocess, {filter});90+ const promise = subprocess.getOneMessage({filter});91 t.is(subprocess.listenerCount('message'), 1);123- t.is(subprocess.listenerCount('disconnect'), 3);124- t.is(await promise, foobarString);92+ t.is(subprocess.listenerCount('disconnect'), 1);93 126- t.is(subprocess.listenerCount('message'), 1);127- t.is(subprocess.listenerCount('disconnect'), 3);128-94+ t.is(await promise, foobarString);95 await subprocess;96 97 t.is(subprocess.listenerCount('message'), 0);98 t.is(subprocess.listenerCount('disconnect'), 0);99 };100 135-test('Cleans up subprocess.getOneMessage() listeners, buffer false', testCleanupListeners, subprocessGetOne, false, undefined);136-test('Cleans up subprocess.getOneMessage() listeners, buffer true', testCleanupListeners, subprocessGetOne, true, undefined);137-test('Cleans up subprocess.getOneMessage() listeners, buffer false, filter', testCleanupListeners, subprocessGetOne, false, alwaysPass);138-test('Cleans up subprocess.getOneMessage() listeners, buffer true, filter', testCleanupListeners, subprocessGetOne, true, alwaysPass);139-test('Cleans up subprocess.exchangeMessage() listeners, buffer false', testCleanupListeners, subprocessExchange, false, undefined);140-test('Cleans up subprocess.exchangeMessage() listeners, buffer true', testCleanupListeners, subprocessExchange, true, undefined);141-test('Cleans up subprocess.exchangeMessage() listeners, buffer false, filter', testCleanupListeners, subprocessExchange, false, alwaysPass);142-test('Cleans up subprocess.exchangeMessage() listeners, buffer true, filter', testCleanupListeners, subprocessExchange, true, alwaysPass);101+test('Cleans up subprocess.getOneMessage() listeners, buffer false', testCleanupListeners, false, undefined);102+test('Cleans up subprocess.getOneMessage() listeners, buffer true', testCleanupListeners, true, undefined);103+test('Cleans up subprocess.getOneMessage() listeners, buffer false, filter', testCleanupListeners, false, alwaysPass);104+test('Cleans up subprocess.getOneMessage() listeners, buffer true, filter', testCleanupListeners, true, alwaysPass);105 144-const testParentDisconnect = async (t, buffer, filter, exchange) => {145- const fixtureStart = filter ? 'ipc-echo-twice-filter' : 'ipc-echo-twice';146- const fixtureName = exchange ? `${fixtureStart}.js` : `${fixtureStart}-get.js`;147- const subprocess = execa(fixtureName, {ipc: true, buffer});106+const testParentDisconnect = async (t, buffer, filter) => {107+ const subprocess = execa('ipc-get-send-get.js', [`${filter}`], {ipc: true, buffer});108 await subprocess.sendMessage(foobarString);109 t.is(await subprocess.getOneMessage(), foobarString);110 111 subprocess.disconnect();1 unmodified line113 const {exitCode, isTerminated, message} = await t.throwsAsync(subprocess);114 t.is(exitCode, 1);115 t.false(isTerminated);116 if (buffer) {157- const methodName = exchange ? 'exchangeMessage()' : 'getOneMessage()';158- t.true(message.includes(`Error: ${methodName} could not complete`));117+ t.true(message.includes('Error: getOneMessage() could not complete'));118 }119 };120 162-test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer false', testParentDisconnect, false, false, false);163-test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer true', testParentDisconnect, true, false, false);164-test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer false, filter', testParentDisconnect, false, true, false);121+test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer false', testParentDisconnect, false, false);122+test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer true', testParentDisconnect, true, false);123+test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer false, filter', testParentDisconnect, false, true);124 test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer true, filter', testParentDisconnect, true, false);166-test('subprocess.disconnect() interrupts exports.exchangeMessage(), buffer false', testParentDisconnect, false, false, true);167-test('subprocess.disconnect() interrupts exports.exchangeMessage(), buffer true', testParentDisconnect, true, false, true);168-test('subprocess.disconnect() interrupts exports.exchangeMessage(), buffer false, filter', testParentDisconnect, false, true, true);169-test('subprocess.disconnect() interrupts exports.exchangeMessage(), buffer true, filter', testParentDisconnect, true, true, true);125 171-// eslint-disable-next-line max-params172-const testSubprocessDisconnect = async (t, exchangeMethod, methodName, buffer, filter) => {126+const testSubprocessDisconnect = async (t, buffer, filter) => {127 const subprocess = execa('empty.js', {ipc: true, buffer});174- const {message} = await t.throwsAsync(exchangeMethod(subprocess, {filter}));175- t.true(message.includes(`subprocess.${methodName}() could not complete`));128+ const {message} = await t.throwsAsync(subprocess.getOneMessage({filter}));129+ t.true(message.includes('subprocess.getOneMessage() could not complete'));130 await subprocess;131 };132 179-test('Subprocess exit interrupts subprocess.getOneMessage(), buffer false', testSubprocessDisconnect, subprocessGetOne, 'getOneMessage', false, undefined);180-test('Subprocess exit interrupts subprocess.getOneMessage(), buffer true', testSubprocessDisconnect, subprocessGetOne, 'getOneMessage', true, undefined);181-test('Subprocess exit interrupts subprocess.getOneMessage(), buffer false, filter', testSubprocessDisconnect, subprocessGetOne, 'getOneMessage', false, alwaysPass);182-test('Subprocess exit interrupts subprocess.getOneMessage(), buffer true, filter', testSubprocessDisconnect, subprocessGetOne, 'getOneMessage', true, alwaysPass);183-test('Subprocess exit interrupts subprocess.exchangeMessage(), buffer false', testSubprocessDisconnect, subprocessExchange, 'exchangeMessage', false, undefined);184-test('Subprocess exit interrupts subprocess.exchangeMessage(), buffer true', testSubprocessDisconnect, subprocessExchange, 'exchangeMessage', true, undefined);185-test('Subprocess exit interrupts subprocess.exchangeMessage(), buffer false, filter', testSubprocessDisconnect, subprocessExchange, 'exchangeMessage', false, alwaysPass);186-test('Subprocess exit interrupts subprocess.exchangeMessage(), buffer true, filter', testSubprocessDisconnect, subprocessExchange, 'exchangeMessage', true, alwaysPass);187-188-const testParentError = async (t, exchangeMethod, filter, buffer) => {189- const subprocess = execa('ipc-send.js', {ipc: true, buffer});190-191- const promise = exchangeMethod(subprocess, {filter});192- const cause = new Error(foobarString);193- subprocess.emit('error', cause);194- t.is(await promise, foobarString);195-196- const error = await t.throwsAsync(subprocess);197- t.is(error.exitCode, undefined);198- t.false(error.isTerminated);199- t.is(error.cause, cause);200- if (buffer) {201- t.deepEqual(error.ipcOutput, [foobarString]);202- }203-};204-205-test('"error" event does not interrupt subprocess.getOneMessage(), buffer false', testParentError, subprocessGetOne, undefined, false);206-test('"error" event does not interrupt subprocess.getOneMessage(), buffer true', testParentError, subprocessGetOne, undefined, true);207-test('"error" event does not interrupt subprocess.getOneMessage(), buffer false, filter', testParentError, subprocessGetOne, alwaysPass, false);208-test('"error" event does not interrupt subprocess.getOneMessage(), buffer true, filter', testParentError, subprocessGetOne, alwaysPass, true);209-test('"error" event does not interrupt subprocess.exchangeMessage(), buffer false', testParentError, subprocessExchange, undefined, false);210-test('"error" event does not interrupt subprocess.exchangeMessage(), buffer true', testParentError, subprocessExchange, undefined, true);211-test('"error" event does not interrupt subprocess.exchangeMessage(), buffer false, filter', testParentError, subprocessExchange, alwaysPass, false);212-test('"error" event does not interrupt subprocess.exchangeMessage(), buffer true, filter', testParentError, subprocessExchange, alwaysPass, true);213-214-const testSubprocessError = async (t, filter, buffer) => {215- const subprocess = execa('ipc-process-error.js', [`${filter}`], {ipc: true, buffer});216- t.is(await subprocess.exchangeMessage(foobarString), foobarString);217-218- const {ipcOutput} = await subprocess;219- if (buffer) {220- t.deepEqual(ipcOutput, [foobarString]);221- }222-};223-224-test('"error" event does not interrupt exports.getOneMessage(), buffer false', testSubprocessError, false, false);225-test('"error" event does not interrupt exports.getOneMessage(), buffer true', testSubprocessError, false, true);226-test('"error" event does not interrupt exports.getOneMessage(), buffer false, filter', testSubprocessError, true, false);227-test('"error" event does not interrupt exports.getOneMessage(), buffer true, filter', testSubprocessError, true, true);228-229-const testSubprocessExchangeError = async (t, filter, buffer) => {230- const subprocess = execa('ipc-process-error-exchange.js', [`${filter}`], {ipc: true, buffer});231- t.is(await subprocess.getOneMessage(), '.');232- t.is(await subprocess.exchangeMessage(foobarString), foobarString);233-234- const {ipcOutput} = await subprocess;235- if (buffer) {236- t.deepEqual(ipcOutput, ['.', foobarString]);237- }238-};239-240-test('"error" event does not interrupt exports.exchangeMessage(), buffer false', testSubprocessExchangeError, false, false);241-test('"error" event does not interrupt exports.exchangeMessage(), buffer true', testSubprocessExchangeError, false, true);242-test('"error" event does not interrupt exports.exchangeMessage(), buffer false, filter', testSubprocessExchangeError, true, false);243-test('"error" event does not interrupt exports.exchangeMessage(), buffer true, filter', testSubprocessExchangeError, true, true);133+test('Subprocess exit interrupts subprocess.getOneMessage(), buffer false', testSubprocessDisconnect, false, undefined);134+test('Subprocess exit interrupts subprocess.getOneMessage(), buffer true', testSubprocessDisconnect, true, undefined);135+test('Subprocess exit interrupts subprocess.getOneMessage(), buffer false, filter', testSubprocessDisconnect, false, alwaysPass);136+test('Subprocess exit interrupts subprocess.getOneMessage(), buffer true, filter', testSubprocessDisconnect, true, alwaysPass);added:test/ipc/incoming.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+import {alwaysPass} from '../helpers/ipc.js';6+import {PARALLEL_COUNT} from '../helpers/parallel.js';7+8+setFixtureDirectory();9+10+const testSeriesParent = async (t, buffer, filter) => {11+ const subprocess = execa('ipc-send-many.js', [`${PARALLEL_COUNT}`], {ipc: true, buffer});12+13+ for (let index = 0; index < PARALLEL_COUNT; index += 1) {14+ // eslint-disable-next-line no-await-in-loop15+ t.is(await subprocess.getOneMessage({filter}), index);16+ }17+18+ const {ipcOutput} = await subprocess;19+ if (buffer) {20+ t.deepEqual(ipcOutput, Array.from({length: PARALLEL_COUNT}, (_, index) => index));21+ }22+};23+24+test('subprocess.getOneMessage() can be called multiple times in a row, buffer false', testSeriesParent, false, undefined);25+test('subprocess.getOneMessage() can be called multiple times in a row, buffer true', testSeriesParent, true, undefined);26+test('subprocess.getOneMessage() can be called multiple times in a row, buffer false, filter', testSeriesParent, false, alwaysPass);27+test('subprocess.getOneMessage() can be called multiple times in a row, buffer true, filter', testSeriesParent, true, alwaysPass);28+29+const testSeriesSubprocess = async (t, filter) => {30+ const subprocess = execa('ipc-print-many.js', [`${PARALLEL_COUNT}`, `${filter}`], {ipc: true});31+ const indexes = Array.from({length: PARALLEL_COUNT}, (_, index) => `${index}`);32+ await Promise.all(indexes.map(index => subprocess.sendMessage(index)));33+34+ const {stdout} = await subprocess;35+ const expectedOutput = indexes.join('\n');36+ t.is(stdout, expectedOutput);37+};38+39+test('exports.getOneMessage() can be called multiple times in a row', testSeriesSubprocess, false);40+test('exports.getOneMessage() can be called multiple times in a row, filter', testSeriesSubprocess, true);41+42+test('Can iterate multiple times over IPC messages in subprocess', async t => {43+ const subprocess = execa('ipc-iterate-twice.js', {ipc: true});44+45+ t.is(await subprocess.getOneMessage(), foobarString);46+ await subprocess.sendMessage('.');47+ t.is(await subprocess.getOneMessage(), '0.');48+ await subprocess.sendMessage(foobarString);49+ t.is(await subprocess.getOneMessage(), foobarString);50+ await subprocess.sendMessage('.');51+ t.is(await subprocess.getOneMessage(), '1.');52+ await subprocess.sendMessage(foobarString);53+54+ const {ipcOutput} = await subprocess;55+ t.deepEqual(ipcOutput, [foobarString, '0.', foobarString, '1.']);56+});added:test/ipc/outgoing.js+88 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 {alwaysPass, subprocessGetOne, subprocessGetFirst} from '../helpers/ipc.js';6+import {PARALLEL_COUNT} from '../helpers/parallel.js';7+8+setFixtureDirectory();9+10+const testSendHoldParent = async (t, getMessage, buffer, filter) => {11+ const subprocess = execa('ipc-iterate.js', {ipc: true, buffer});12+13+ await subprocess.sendMessage(0);14+ t.is(await subprocess.getOneMessage({filter}), 0);15+16+ const messages = Array.from({length: PARALLEL_COUNT}, (_, index) => index + 1);17+ await Promise.all([18+ ...messages.map(message => subprocess.sendMessage(message)),19+ subprocess.sendMessage(foobarString),20+ subprocess.emit('message', '.'),21+ ]);22+ t.is(await getMessage(subprocess, {filter}), '.');23+24+ const {ipcOutput} = await subprocess;25+ if (buffer) {26+ const expectedOutput = [0, '.', ...messages];27+ t.deepEqual(ipcOutput, expectedOutput);28+ }29+};30+31+test('Multiple parallel subprocess.sendMessage() + subprocess.getOneMessage(), buffer false', testSendHoldParent, subprocessGetOne, false, undefined);32+test('Multiple parallel subprocess.sendMessage() + subprocess.getOneMessage(), buffer true', testSendHoldParent, subprocessGetOne, true, undefined);33+test('Multiple parallel subprocess.sendMessage() + subprocess.getOneMessage(), buffer false, filter', testSendHoldParent, subprocessGetOne, false, alwaysPass);34+test('Multiple parallel subprocess.sendMessage() + subprocess.getOneMessage(), buffer true, filter', testSendHoldParent, subprocessGetOne, true, alwaysPass);35+test('Multiple parallel subprocess.sendMessage() + subprocess.getEachMessage(), buffer false', testSendHoldParent, subprocessGetFirst, false, undefined);36+test('Multiple parallel subprocess.sendMessage() + subprocess.getEachMessage(), buffer true', testSendHoldParent, subprocessGetFirst, true, undefined);37+38+const testSendHoldSubprocess = async (t, filter, isGetEach) => {39+ const {ipcOutput} = await execa('ipc-iterate-back.js', [`${filter}`, `${isGetEach}`], {ipc: true, ipcInput: 0});40+ const expectedOutput = [...Array.from({length: PARALLEL_COUNT + 1}, (_, index) => index), '.'];41+ t.deepEqual(ipcOutput, expectedOutput);42+};43+44+test('Multiple parallel exports.sendMessage() + exports.getOneMessage()', testSendHoldSubprocess, false, false);45+test('Multiple parallel exports.sendMessage() + exports.getOneMessage(), filter', testSendHoldSubprocess, true, false);46+test('Multiple parallel exports.sendMessage() + exports.getEachMessage()', testSendHoldSubprocess, false, true);47+48+const testSendHoldParentSerial = async (t, getMessage, buffer, filter) => {49+ const subprocess = execa('ipc-iterate.js', {ipc: true, buffer});50+51+ await subprocess.sendMessage(0);52+ t.is(await subprocess.getOneMessage({filter}), 0);53+54+ const promise = subprocess.sendMessage(1);55+ subprocess.emit('message', '.');56+ await promise;57+58+ const messages = Array.from({length: PARALLEL_COUNT}, (_, index) => index + 2);59+ for (const message of messages) {60+ // eslint-disable-next-line no-await-in-loop61+ await subprocess.sendMessage(message);62+ }63+64+ await subprocess.sendMessage(foobarString);65+66+ const {ipcOutput} = await subprocess;67+ if (buffer) {68+ const expectedOutput = [0, '.', 1, ...messages];69+ t.deepEqual(ipcOutput, expectedOutput);70+ }71+};72+73+test('Multiple serial subprocess.sendMessage() + subprocess.getOneMessage(), buffer false', testSendHoldParentSerial, subprocessGetOne, false, undefined);74+test('Multiple serial subprocess.sendMessage() + subprocess.getOneMessage(), buffer true', testSendHoldParentSerial, subprocessGetOne, true, undefined);75+test('Multiple serial subprocess.sendMessage() + subprocess.getOneMessage(), buffer false, filter', testSendHoldParentSerial, subprocessGetOne, false, alwaysPass);76+test('Multiple serial subprocess.sendMessage() + subprocess.getOneMessage(), buffer true, filter', testSendHoldParentSerial, subprocessGetOne, true, alwaysPass);77+test('Multiple serial subprocess.sendMessage() + subprocess.getEachMessage(), buffer false', testSendHoldParentSerial, subprocessGetFirst, false, undefined);78+test('Multiple serial subprocess.sendMessage() + subprocess.getEachMessage(), buffer true', testSendHoldParentSerial, subprocessGetFirst, true, undefined);79+80+const testSendHoldSubprocessSerial = async (t, filter, isGetEach) => {81+ const {ipcOutput} = await execa('ipc-iterate-back-serial.js', [`${filter}`, `${isGetEach}`], {ipc: true, ipcInput: 0, stdout: 'inherit'});82+ const expectedOutput = [...Array.from({length: PARALLEL_COUNT + 2}, (_, index) => index), '.'];83+ t.deepEqual(ipcOutput, expectedOutput);84+};85+86+test('Multiple serial exports.sendMessage() + exports.getOneMessage()', testSendHoldSubprocessSerial, false, false);87+test('Multiple serial exports.sendMessage() + exports.getOneMessage(), filter', testSendHoldSubprocessSerial, true, false);88+test('Multiple serial exports.sendMessage() + exports.getEachMessage()', testSendHoldSubprocessSerial, false, true);added:test/ipc/reference.js+102 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 {PARALLEL_COUNT} from '../helpers/parallel.js';6+7+setFixtureDirectory();8+9+const testKeepAliveSubprocess = async (t, fixtureName) => {10+ const {timedOut} = await t.throwsAsync(execa(fixtureName, {ipc: true, timeout: 1e3}));11+ t.true(timedOut);12+};13+14+test('exports.getOneMessage() keeps the subprocess alive', testKeepAliveSubprocess, 'ipc-echo.js');15+test('exports.getEachMessage() keeps the subprocess alive', testKeepAliveSubprocess, 'ipc-iterate.js');16+17+test('exports.sendMessage() keeps the subprocess alive', async t => {18+ const {ipcOutput} = await execa('ipc-send-repeat.js', [`${PARALLEL_COUNT}`], {ipc: true});19+ const expectedOutput = Array.from({length: PARALLEL_COUNT}, (_, index) => index);20+ t.deepEqual(ipcOutput, expectedOutput);21+});22+23+test('process.send() keeps the subprocess alive', async t => {24+ const {ipcOutput, stdout} = await execa('ipc-process-send.js', {ipc: true});25+ t.deepEqual(ipcOutput, [foobarString]);26+ t.is(stdout, '.');27+});28+29+test('process.send() keeps the subprocess alive, after getOneMessage()', async t => {30+ const {ipcOutput, stdout} = await execa('ipc-process-send-get.js', {ipc: true, ipcInput: 0});31+ t.deepEqual(ipcOutput, [foobarString]);32+ t.is(stdout, '.');33+});34+35+test('process.send() keeps the subprocess alive, after sendMessage()', async t => {36+ const {ipcOutput, stdout} = await execa('ipc-process-send-send.js', {ipc: true});37+ t.deepEqual(ipcOutput, ['.', foobarString]);38+ t.is(stdout, '.');39+});40+41+test('process.once("message") keeps the subprocess alive', async t => {42+ const subprocess = execa('ipc-once-message.js', {ipc: true});43+ t.is(await subprocess.getOneMessage(), '.');44+ await subprocess.sendMessage(foobarString);45+46+ const {ipcOutput, stdout} = await subprocess;47+ t.deepEqual(ipcOutput, ['.']);48+ t.is(stdout, foobarString);49+});50+51+test('process.once("message") keeps the subprocess alive, after sendMessage()', async t => {52+ const subprocess = execa('ipc-once-message-send.js', {ipc: true});53+ t.is(await subprocess.getOneMessage(), '.');54+ await subprocess.sendMessage(foobarString);55+56+ const {ipcOutput, stdout} = await subprocess;57+ t.deepEqual(ipcOutput, ['.']);58+ t.is(stdout, foobarString);59+});60+61+test('process.once("message") keeps the subprocess alive, after getOneMessage()', async t => {62+ const subprocess = execa('ipc-once-message-get.js', {ipc: true});63+ await subprocess.sendMessage('.');64+ t.is(await subprocess.getOneMessage(), '.');65+ await subprocess.sendMessage(foobarString);66+67+ const {ipcOutput, stdout} = await subprocess;68+ t.deepEqual(ipcOutput, ['.']);69+ t.is(stdout, foobarString);70+});71+72+test('process.once("disconnect") keeps the subprocess alive', async t => {73+ const subprocess = execa('ipc-once-disconnect.js', {ipc: true});74+ t.is(await subprocess.getOneMessage(), '.');75+ subprocess.disconnect();76+77+ const {ipcOutput, stdout} = await subprocess;78+ t.deepEqual(ipcOutput, ['.']);79+ t.is(stdout, '.');80+});81+82+test('process.once("disconnect") keeps the subprocess alive, after sendMessage()', async t => {83+ const subprocess = execa('ipc-once-disconnect-send.js', {ipc: true});84+ t.is(await subprocess.getOneMessage(), '.');85+ t.is(await subprocess.getOneMessage(), '.');86+ subprocess.disconnect();87+88+ const {ipcOutput, stdout} = await subprocess;89+ t.deepEqual(ipcOutput, ['.', '.']);90+ t.is(stdout, '.');91+});92+93+test('process.once("disconnect") does not keep the subprocess alive, after getOneMessage()', async t => {94+ const subprocess = execa('ipc-once-disconnect-get.js', {ipc: true});95+ await subprocess.sendMessage('.');96+ t.is(await subprocess.getOneMessage(), '.');97+ subprocess.disconnect();98+99+ const {ipcOutput, stdout} = await subprocess;100+ t.deepEqual(ipcOutput, ['.']);101+ t.is(stdout, '.');102+});modified:test/ipc/send.js+35 added-54 removed
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 {subprocessSendGetOne, subprocessExchange} from '../helpers/ipc.js';5 import {PARALLEL_COUNT} from '../helpers/parallel.js';6 7 setFixtureDirectory();8 10-const testExchange = async (t, exchangeMethod) => {9+test('Can exchange IPC messages', async t => {10 const subprocess = execa('ipc-echo.js', {ipc: true});12- t.is(await exchangeMethod(subprocess, foobarString), foobarString);11+ await subprocess.sendMessage(foobarString);12+ t.is(await subprocess.getOneMessage(), foobarString);13 await subprocess;14-};14+});15 16-test('Can exchange IPC messages', testExchange, subprocessSendGetOne);17-test('Can exchange IPC messages, exchangeMessage()', testExchange, subprocessExchange);18-19-const testHeavyLoad = async (t, exchangeMethod) => {16+test.serial('Can exchange IPC messages under heavy load', async t => {17 await Promise.all(18 Array.from({length: PARALLEL_COUNT}, async (_, index) => {19 const subprocess = execa('ipc-echo.js', {ipc: true});23- t.is(await exchangeMethod(subprocess, index), index);20+ await subprocess.sendMessage(index);21+ t.is(await subprocess.getOneMessage(), index);22 await subprocess;23 }),24 );27-};25+});26 29-test.serial('Can exchange IPC messages under heavy load', testHeavyLoad, subprocessSendGetOne);30-test.serial('Can exchange IPC messages under heavy load, exchangeMessage()', testHeavyLoad, subprocessExchange);31-32-const testDefaultSerialization = async (t, exchangeMethod) => {27+test('The "serialization" option defaults to "advanced"', async t => {28 const subprocess = execa('ipc-echo.js', {ipc: true});34- const message = await exchangeMethod(subprocess, [0n]);29+ await subprocess.sendMessage([0n]);30+ const message = await subprocess.getOneMessage();31 t.is(message[0], 0n);32 await subprocess;37-};33+});34 39-test('The "serialization" option defaults to "advanced"', testDefaultSerialization, subprocessSendGetOne);40-test('The "serialization" option defaults to "advanced", exchangeMessage()', testDefaultSerialization, subprocessExchange);41-42-const testJsonSerialization = async (t, exchangeMethod) => {35+test('Can use "serialization: json" option', async t => {36 const subprocess = execa('ipc-echo.js', {ipc: true, serialization: 'json'});37 const date = new Date();45- t.is(await exchangeMethod(subprocess, date), date.toJSON());38+ await subprocess.sendMessage(date);39+ t.is(await subprocess.getOneMessage(), date.toJSON());40 await subprocess;47-};41+});42 49-test('Can use "serialization: json" option', testJsonSerialization, subprocessSendGetOne);50-test('Can use "serialization: json" option, exchangeMessage()', testJsonSerialization, subprocessExchange);51-52-const testJsonError = async (t, exchangeMethod) => {43+test('Validates JSON payload with serialization: "json"', async t => {44 const subprocess = execa('ipc-echo.js', {ipc: true, serialization: 'json'});54- await t.throwsAsync(exchangeMethod(subprocess, [0n]), {message: /serialize a BigInt/});45+ await t.throwsAsync(subprocess.sendMessage([0n]), {message: /serialize a BigInt/});46 await t.throwsAsync(subprocess);56-};47+});48 58-test('Validates JSON payload with serialization: "json"', testJsonError, subprocessSendGetOne);59-test('Validates JSON payload with serialization: "json", exchangeMessage()', testJsonError, subprocessExchange);60-49 const BIG_PAYLOAD_SIZE = '.'.repeat(1e6);50 63-const testBackpressure = async (t, exchangeMethod) => {51+test('Handles backpressure', async t => {52 const subprocess = execa('ipc-iterate.js', {ipc: true});65- await exchangeMethod(subprocess, BIG_PAYLOAD_SIZE);53+ await subprocess.sendMessage(BIG_PAYLOAD_SIZE);54 t.true(subprocess.send(foobarString));55+ t.is(await subprocess.getOneMessage(), BIG_PAYLOAD_SIZE);56 const {ipcOutput} = await subprocess;57 t.deepEqual(ipcOutput, [BIG_PAYLOAD_SIZE]);69-};58+});59 71-test('Handles backpressure', testBackpressure, subprocessSendGetOne);72-test('Handles backpressure, exchangeMessage()', testBackpressure, subprocessExchange);60+test('Disconnects IPC on exports.sendMessage() error', async t => {61+ const subprocess = execa('ipc-get-send-get.js', ['false'], {ipc: true});62+ await subprocess.sendMessage(foobarString);63+ t.is(await subprocess.getOneMessage(), foobarString);64 74-const testParentDisconnect = async (t, methodName) => {75- const subprocess = execa('ipc-echo-twice.js', {ipc: true});76- t.is(await subprocess.exchangeMessage(foobarString), foobarString);65+ const {message} = await t.throwsAsync(subprocess.sendMessage(0n));66+ t.true(message.includes('subprocess.sendMessage()\'s argument type is invalid'));67 78- const {message} = await t.throwsAsync(subprocess[methodName](0n));79- t.true(message.includes(`subprocess.${methodName}()'s argument type is invalid`));80-68 const {exitCode, isTerminated, stderr} = await t.throwsAsync(subprocess);69 t.is(exitCode, 1);70 t.false(isTerminated);84- t.true(stderr.includes('Error: exchangeMessage() could not complete'));85-};71+ t.true(stderr.includes('Error: getOneMessage() could not complete'));72+});73 87-test('Disconnects IPC on exports.sendMessage() error', testParentDisconnect, 'sendMessage');88-test('Disconnects IPC on exports.exchangeMessage() error', testParentDisconnect, 'exchangeMessage');89-90-const testSubprocessDisconnect = async (t, methodName, fixtureName) => {91- const subprocess = execa(fixtureName, {ipc: true});74+test('Disconnects IPC on subprocess.sendMessage() error', async t => {75+ const subprocess = execa('ipc-send-error.js', {ipc: true});76 const ipcError = await t.throwsAsync(subprocess.getOneMessage());77 t.true(ipcError.message.includes('subprocess.getOneMessage() could not complete'));78 79 const {exitCode, isTerminated, stderr} = await t.throwsAsync(subprocess);80 t.is(exitCode, 1);81 t.false(isTerminated);98- t.true(stderr.includes(`${methodName}()'s argument type is invalid`));99-};100-101-test('Disconnects IPC on subprocess.sendMessage() error', testSubprocessDisconnect, 'sendMessage', 'ipc-send-error.js');102-test('Disconnects IPC on subprocess.exchangeMessage() error', testSubprocessDisconnect, 'exchangeMessage', 'ipc-exchange-error.js');82+ t.true(stderr.includes('sendMessage()\'s argument type is invalid'));83+});modified:test/ipc/validation.js+19 added-42 removed
19 unmodified lines20 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.exchangeMessage() without ipc option', testRequiredIpcSubprocess, 'exchangeMessage', {});25-test('Cannot use subprocess.exchangeMessage() with ipc: false', testRequiredIpcSubprocess, 'exchangeMessage', {ipc: false});26-test('Cannot use subprocess.exchangeMessage() with stdio: [..., "ipc"]', testRequiredIpcSubprocess, 'exchangeMessage', 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 5 unmodified lines33 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});40-test('Cannot use exports.exchangeMessage() without ipc option', testRequiredIpcExports, 'exchangeMessage', {});41-test('Cannot use exports.exchangeMessage() with ipc: false', testRequiredIpcExports, 'exchangeMessage', {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) => {4 unmodified lines45 };46 47 test('subprocess.sendMessage() after disconnection', testPostDisconnection, 'sendMessage');48 test('subprocess.getOneMessage() after disconnection', testPostDisconnection, 'getOneMessage');54-test('subprocess.exchangeMessage() after disconnection', testPostDisconnection, 'exchangeMessage');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});3 unmodified lines56 };57 58 test('exports.sendMessage() after disconnection', testPostDisconnectionSubprocess, 'sendMessage');59 test('exports.getOneMessage() after disconnection', testPostDisconnectionSubprocess, 'getOneMessage');66-test('exports.exchangeMessage() after disconnection', testPostDisconnectionSubprocess, 'exchangeMessage');60 test('exports.getEachMessage() after disconnection', testPostDisconnectionSubprocess, 'getEachMessage');61 69-const testInvalidPayload = async (t, methodName, serialization, message) => {62+const testInvalidPayload = async (t, serialization, message) => {63 const subprocess = execa('empty.js', {ipc: true, serialization});71- await t.throwsAsync(subprocess[methodName](message), {message: /type is invalid/});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 79-test('subprocess.sendMessage() cannot send undefined', testInvalidPayload, 'sendMessage', 'advanced', undefined);80-test('subprocess.sendMessage() cannot send bigints', testInvalidPayload, 'sendMessage', 'advanced', 0n);81-test('subprocess.sendMessage() cannot send symbols', testInvalidPayload, 'sendMessage', 'advanced', Symbol('test'));82-test('subprocess.sendMessage() cannot send functions', testInvalidPayload, 'sendMessage', 'advanced', () => {});83-test('subprocess.sendMessage() cannot send promises', testInvalidPayload, 'sendMessage', 'advanced', Promise.resolve());84-test('subprocess.sendMessage() cannot send proxies', testInvalidPayload, 'sendMessage', 'advanced', new Proxy({}, {}));85-test('subprocess.sendMessage() cannot send Intl', testInvalidPayload, 'sendMessage', 'advanced', new Intl.Collator());86-test('subprocess.sendMessage() cannot send undefined, JSON', testInvalidPayload, 'sendMessage', 'json', undefined);87-test('subprocess.sendMessage() cannot send bigints, JSON', testInvalidPayload, 'sendMessage', 'json', 0n);88-test('subprocess.sendMessage() cannot send symbols, JSON', testInvalidPayload, 'sendMessage', 'json', Symbol('test'));89-test('subprocess.sendMessage() cannot send functions, JSON', testInvalidPayload, 'sendMessage', 'json', () => {});90-test('subprocess.sendMessage() cannot send cycles, JSON', testInvalidPayload, 'sendMessage', 'json', cycleObject);91-test('subprocess.sendMessage() cannot send cycles in toJSON(), JSON', testInvalidPayload, 'sendMessage', 'json', toJsonCycle);92-test('subprocess.exchangeMessage() cannot send undefined', testInvalidPayload, 'exchangeMessage', 'advanced', undefined);93-test('subprocess.exchangeMessage() cannot send bigints', testInvalidPayload, 'exchangeMessage', 'advanced', 0n);94-test('subprocess.exchangeMessage() cannot send symbols', testInvalidPayload, 'exchangeMessage', 'advanced', Symbol('test'));95-test('subprocess.exchangeMessage() cannot send functions', testInvalidPayload, 'exchangeMessage', 'advanced', () => {});96-test('subprocess.exchangeMessage() cannot send promises', testInvalidPayload, 'exchangeMessage', 'advanced', Promise.resolve());97-test('subprocess.exchangeMessage() cannot send proxies', testInvalidPayload, 'exchangeMessage', 'advanced', new Proxy({}, {}));98-test('subprocess.exchangeMessage() cannot send Intl', testInvalidPayload, 'exchangeMessage', 'advanced', new Intl.Collator());99-test('subprocess.exchangeMessage() cannot send undefined, JSON', testInvalidPayload, 'exchangeMessage', 'json', undefined);100-test('subprocess.exchangeMessage() cannot send bigints, JSON', testInvalidPayload, 'exchangeMessage', 'json', 0n);101-test('subprocess.exchangeMessage() cannot send symbols, JSON', testInvalidPayload, 'exchangeMessage', 'json', Symbol('test'));102-test('subprocess.exchangeMessage() cannot send functions, JSON', testInvalidPayload, 'exchangeMessage', 'json', () => {});103-test('subprocess.exchangeMessage() cannot send cycles, JSON', testInvalidPayload, 'exchangeMessage', 'json', cycleObject);104-test('subprocess.exchangeMessage() cannot send cycles in toJSON(), JSON', testInvalidPayload, 'exchangeMessage', 'json', toJsonCycle);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 106-const testSubprocessInvalidPayload = async (t, methodName, fixtureName) => {107- const subprocess = execa(fixtureName, {ipc: true});86+test('exports.sendMessage() validates payload', async t => {87+ const subprocess = execa('ipc-echo-item.js', {ipc: true});88 await subprocess.sendMessage([undefined]);89 const {message} = await t.throwsAsync(subprocess);110- t.true(message.includes(`${methodName}()'s argument type is invalid`));111-};112-113-test('exports.sendMessage() validates payload', testSubprocessInvalidPayload, 'sendMessage', 'ipc-echo-item.js');114-test('exports.exchangeMessage() validates payload', testSubprocessInvalidPayload, 'exchangeMessage', 'ipc-echo-item-exchange.js');90+ t.true(message.includes('sendMessage()\'s argument type is invalid'));91+});modified:test/methods/node.js+2 added-1 removed
223 unmodified lines224 225 const testIpc = async (t, execaMethod, options) => {226 const subprocess = execaMethod('ipc-echo.js', [], options);227 228- t.is(await subprocess.exchangeMessage(foobarString), foobarString);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);55 unmodified linesdeleted:test-d/ipc/exchange.test-d.ts-65 removed
1-import {expectType, expectError} from 'tsd';2-import {3- exchangeMessage,4- execa,5- type Message,6- type Options,7-} from '../../index.js';8-9-const subprocess = execa('test', {ipc: true});10-expectType<Promise<Message<'advanced'>>>(subprocess.exchangeMessage(''));11-const jsonSubprocess = execa('test', {ipc: true, serialization: 'json'});12-expectType<Promise<Message<'json'>>>(jsonSubprocess.exchangeMessage(''));13-expectType<Promise<Message>>(exchangeMessage(''));14-15-expectError(await subprocess.exchangeMessage());16-expectError(await exchangeMessage());17-expectError(await subprocess.exchangeMessage(undefined));18-expectError(await exchangeMessage(undefined));19-expectError(await subprocess.exchangeMessage(0n));20-expectError(await exchangeMessage(0n));21-expectError(await subprocess.exchangeMessage(Symbol('test')));22-expectError(await exchangeMessage(Symbol('test')));23-expectError(await subprocess.exchangeMessage('', ''));24-expectError(await exchangeMessage('', ''));25-expectError(await subprocess.exchangeMessage('', {}, ''));26-expectError(await exchangeMessage('', {}, ''));27-28-await execa('test', {ipcInput: ''}).exchangeMessage('');29-await execa('test', {ipcInput: '' as Message}).exchangeMessage('');30-await execa('test', {} as Options).exchangeMessage?.('');31-await execa('test', {ipc: true as boolean}).exchangeMessage?.('');32-await execa('test', {ipcInput: '' as '' | undefined}).exchangeMessage?.('');33-34-expectType<undefined>(execa('test').exchangeMessage);35-expectType<undefined>(execa('test', {}).exchangeMessage);36-expectType<undefined>(execa('test', {ipc: false}).exchangeMessage);37-expectType<undefined>(execa('test', {ipcInput: undefined}).exchangeMessage);38-expectType<undefined>(execa('test', {ipc: false, ipcInput: ''}).exchangeMessage);39-40-await subprocess.exchangeMessage('', {filter: undefined} as const);41-await subprocess.exchangeMessage('', {filter: (message: Message<'advanced'>) => true} as const);42-await jsonSubprocess.exchangeMessage('', {filter: (message: Message<'json'>) => true} as const);43-await jsonSubprocess.exchangeMessage('', {filter: (message: Message<'advanced'>) => true} as const);44-await subprocess.exchangeMessage('', {filter: (message: Message<'advanced'> | bigint) => true} as const);45-await subprocess.exchangeMessage('', {filter: () => true} as const);46-expectError(await subprocess.exchangeMessage('', {filter: (message: Message<'advanced'>) => ''} as const));47-// eslint-disable-next-line @typescript-eslint/no-empty-function48-expectError(await subprocess.exchangeMessage('', {filter(message: Message<'advanced'>) {}} as const));49-expectError(await subprocess.exchangeMessage('', {filter: (message: Message<'json'>) => true} as const));50-expectError(await subprocess.exchangeMessage('', {filter: (message: '') => true} as const));51-expectError(await subprocess.exchangeMessage('', {filter: true} as const));52-expectError(await subprocess.exchangeMessage('', {unknownOption: true} as const));53-54-await exchangeMessage('', {filter: undefined} as const);55-await exchangeMessage('', {filter: (message: Message) => true} as const);56-await exchangeMessage('', {filter: (message: Message<'advanced'>) => true} as const);57-await exchangeMessage('', {filter: (message: Message | bigint) => true} as const);58-await exchangeMessage('', {filter: () => true} as const);59-expectError(await exchangeMessage('', {filter: (message: Message) => ''} as const));60-// eslint-disable-next-line @typescript-eslint/no-empty-function61-expectError(await exchangeMessage('', {filter(message: Message) {}} as const));62-expectError(await exchangeMessage('', {filter: (message: Message<'json'>) => true} as const));63-expectError(await exchangeMessage('', {filter: (message: '') => true} as const));64-expectError(await exchangeMessage('', {filter: true} as const));65-expectError(await exchangeMessage('', {unknownOption: true} as const));modified:test-d/ipc/message.test-d.ts+1 added-27 removed
1 import {File} from 'node:buffer';2 import {expectAssignable, expectNotAssignable} from 'tsd';3-import {sendMessage, exchangeMessage, type Message} from '../../index.js';3+import {sendMessage, type Message} from '../../index.js';4 5 await sendMessage('');6-await exchangeMessage('');6 expectAssignable<Message>('');7 expectAssignable<Message<'advanced'>>('');8 expectAssignable<Message<'json'>>('');9 10 await sendMessage(0);12-await exchangeMessage(0);11 expectAssignable<Message>(0);12 expectAssignable<Message<'advanced'>>(0);13 expectAssignable<Message<'json'>>(0);14 15 await sendMessage(true);18-await exchangeMessage(true);16 expectAssignable<Message>(true);17 expectAssignable<Message<'advanced'>>(true);18 expectAssignable<Message<'json'>>(true);19 20 await sendMessage([] as const);24-await exchangeMessage([] 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);30-await exchangeMessage([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);36-await exchangeMessage([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);42-await exchangeMessage([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);48-await exchangeMessage({} 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);54-await exchangeMessage({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);60-await exchangeMessage({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);66-await exchangeMessage({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);72-await exchangeMessage(null);61 expectAssignable<Message>(null);62 expectAssignable<Message<'advanced'>>(null);63 expectAssignable<Message<'json'>>(null);64 65 await sendMessage(Number.NaN);78-await exchangeMessage(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);84-await exchangeMessage(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());90-await exchangeMessage(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());96-await exchangeMessage(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());102-await exchangeMessage(new Date());86 expectAssignable<Message>(new Date());87 expectAssignable<Message<'advanced'>>(new Date());88 expectNotAssignable<Message<'json'>>(new Date());89 90 await sendMessage(/regexp/);108-await exchangeMessage(/regexp/);91 expectAssignable<Message>(/regexp/);92 expectAssignable<Message<'advanced'>>(/regexp/);93 expectNotAssignable<Message<'json'>>(/regexp/);94 95 await sendMessage(new Blob());114-await exchangeMessage(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([], ''));120-await exchangeMessage(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)));126-await exchangeMessage(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));132-await exchangeMessage(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));138-await exchangeMessage(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());144-await exchangeMessage(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());150-await exchangeMessage(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'));156-await exchangeMessage(new Error('test'));131 expectAssignable<Message>(new Error('test'));132 expectAssignable<Message<'advanced'>>(new Error('test'));133 expectNotAssignable<Message<'json'>>(new Error('test'));modified:types/arguments/options.d.ts+1 added-1 removed
197 unmodified lines198 */199 readonly buffer?: FdGenericOption<boolean>;200 201 /**202- Enables exchanging messages with the subprocess using `subprocess.sendMessage(message)`, `subprocess.getOneMessage()`, `subprocess.exchangeMessage(message)` and `subprocess.getEachMessage()`.202+ Enables exchanging messages with the subprocess using `subprocess.sendMessage(message)`, `subprocess.getOneMessage()` and `subprocess.getEachMessage()`.203 204 The subprocess must be a Node.js file.205 206 @default `true` if either the `node` option or the `ipcInput` option is set, `false` otherwise176 unmodified linesmodified:types/methods/main-async.d.ts+2 added-1 removed
185 unmodified lines186 // parent.js187 import {execaNode} from 'execa';188 189 const subprocess = execaNode`child.js`;190-const message = await subprocess.exchangeMessage('Hello from parent');190+await subprocess.sendMessage('Hello from parent');191+const message = await subprocess.getOneMessage();192 console.log(message); // 'Hello from child'193 ```194 195 ```115 unmodified linesmodified:types/ipc.d.ts+2 added-17 removed
16 unmodified lines17 | readonly JsonMessage[]18 | {readonly [key: string | number]: JsonMessage};19 20 /**21-Type of messages exchanged between a process and its subprocess using `sendMessage()`, `getOneMessage()`, `exchangeMessage()` and `getEachMessage()`.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 /**30-Options to `getOneMessage()`, `exchangeMessage()`, `subprocess.getOneMessage()` and `subprocess.exchangeMessage()`30+Options to `getOneMessage()` and `subprocess.getOneMessage()`31 */32 type GetOneMessageOptions<33 Serialization extends Options['serialization'],34 > = {18 unmodified lines53 */54 export function getOneMessage(getOneMessageOptions?: GetOneMessageOptions<Options['serialization']>): Promise<Message>;55 56 /**57-Send a `message` to the parent process, then receive a response from it.58-59-This requires the `ipc` option to be `true`. The type of `message` depends on the `serialization` option.60-*/61-export function exchangeMessage(message: Message, getOneMessageOptions?: GetOneMessageOptions<Options['serialization']>): Promise<Message>;62-63-/**57 Iterate over each `message` from the parent process.58 59 This requires the `ipc` option to be `true`. The type of `message` depends on the `serialization` option.60 */19 unmodified lines80 */81 getOneMessage(getOneMessageOptions?: GetOneMessageOptions<Serialization>): Promise<Message<Serialization>>;82 83 /**91- Send a `message` to the subprocess, then receive a response from it.92-93- This requires the `ipc` option to be `true`. The type of `message` depends on the `serialization` option.94- */95- exchangeMessage(message: Message<Serialization>, getOneMessageOptions?: GetOneMessageOptions<Serialization>): Promise<Message<Serialization>>;96-97- /**84 Iterate over each `message` from the subprocess.85 86 This requires the `ipc` option to be `true`. The type of `message` depends on the `serialization` option.87 */4 unmodified lines92 // At type check time, they are typed as `undefined` to prevent calling them.93 : {94 sendMessage: undefined;95 getOneMessage: undefined;110- exchangeMessage: undefined;96 getEachMessage: undefined;97 };98 99 // Whether IPC is enabled, based on the `ipc` and `ipcInput` options15 unmodified linesmodified:index.d.ts-1 removed
18 unmodified lines19 20 export {21 sendMessage,22 getOneMessage,23- exchangeMessage,23 getEachMessage,24 type Message,25 } from './types/ipc.js';modified:index.js-2 removed
15 unmodified lines16 17 const {18 sendMessage,19 getOneMessage,20- exchangeMessage,20 getEachMessage,21 } = getIpcExport();22 export {23 sendMessage,24 getOneMessage,26- exchangeMessage,25 getEachMessage,26 };modified:readme.md+2 added-1 removed
268 unmodified lines269 // parent.js270 import {execaNode} from 'execa';271 272 const subprocess = execaNode`child.js`;273-const message = await subprocess.exchangeMessage('Hello from parent');273+await subprocess.sendMessage('Hello from parent');274+const message = await subprocess.getOneMessage();275 console.log(message); // 'Hello from child'276 ```277 278 ```js114 unmodified lines