Skip to content
Myr

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

63 files+854 added−772 removed

modified:docs/api.md+1 added-25 removed
134 unmodified lines
135This requires the [`ipc`](#optionsipc) option to be `true`. The [type](ipc.md#message-type) of `message` depends on the [`serialization`](#optionsserialization) option.136137[More info.](ipc.md#listening-to-messages)138139### exchangeMessage(message, getOneMessageOptions?)140141`message`: [`Message`](ipc.md#message-type)\142_getOneMessageOptions_: [`GetOneMessageOptions`](#getonemessageoptions)\143_Returns_: [`Promise<Message>`](ipc.md#message-type)144145Send a `message` to the parent process, then receive a response from it.146147This requires the [`ipc`](#optionsipc) option to be `true`. The [type](ipc.md#message-type) of `message` depends on the [`serialization`](#optionsserialization) option.148149[More info.](ipc.md#exchanging-messages)150139## Return value140141_TypeScript:_ [`ResultPromise`](typescript.md)\142_Type:_ `Promise<object> | Subprocess`
149 unmodified lines
292This requires the [`ipc`](#optionsipc) option to be `true`. The [type](ipc.md#message-type) of `message` depends on the [`serialization`](#optionsserialization) option.293294[More info.](ipc.md#listening-to-messages)295308### subprocess.exchangeMessage(message, getOneMessageOptions?)309310`message`: [`Message`](ipc.md#message-type)\311_getOneMessageOptions_: [`GetOneMessageOptions`](#getonemessageoptions)\312_Returns_: [`Promise<Message>`](ipc.md#message-type)313314Send a `message` to the subprocess, then receive a response from it.315316This requires the [`ipc`](#optionsipc) option to be `true`. The [type](ipc.md#message-type) of `message` depends on the [`serialization`](#optionsserialization) option.317318[More info.](ipc.md#exchanging-messages)319296### subprocess.stdin297298_Type:_ [`Writable | null`](https://nodejs.org/api/stream.html#class-streamwritable)299
613 unmodified lines
913914_Type:_ `boolean`\915_Default:_ `true` if either the [`node`](#optionsnode) option or the [`ipcInput`](#optionsipcinput) is set, `false` otherwise916941Enables exchanging messages with the subprocess using [`subprocess.sendMessage(message)`](#subprocesssendmessagemessage), [`subprocess.getOneMessage()`](#subprocessgetonemessagegetonemessageoptions), [`subprocess.exchangeMessage(message)`](#subprocessexchangemessagemessage-getonemessageoptions) and [`subprocess.getEachMessage()`](#subprocessgeteachmessage).917Enables exchanging messages with the subprocess using [`subprocess.sendMessage(message)`](#subprocesssendmessagemessage), [`subprocess.getOneMessage()`](#subprocessgetonemessagegetonemessageoptions) and [`subprocess.getEachMessage()`](#subprocessgeteachmessage).918919The subprocess must be a Node.js file.920921[More info.](ipc.md)
199 unmodified lines
modified:docs/execution.md+1 added-1 removed
modified:docs/ipc.md+15 added-85 removed
10 unmodified lines
11When 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).1213The `ipc` option defaults to `true` when using [`execaNode()`](node.md#run-nodejs-files) or the [`node`](node.md#run-nodejs-files) option.1415The 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.15The current process sends messages with [`subprocess.sendMessage(message)`](api.md#subprocesssendmessagemessage) and receives them with [`subprocess.getOneMessage()`](api.md#subprocessgetonemessagegetonemessageoptions).1617The 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.17The subprocess uses [`sendMessage(message)`](api.md#sendmessagemessage) and [`getOneMessage()`](api.md#getonemessagegetonemessageoptions). Those are the same methods, but imported directly from the `'execa'` module.1819```js20// parent.js21import {execaNode} from 'execa';2223const subprocess = execaNode`child.js`;24const message = await subprocess.exchangeMessage('Hello from parent');24await subprocess.sendMessage('Hello from parent');25const message = await subprocess.getOneMessage();26console.log(message); // 'Hello from child'27```2829```js
6 unmodified lines
36```3738## Listening to messages3939The 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.40The 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.4142[`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).4344```js
103 unmodified lines
148```149150## Messages order151151The messages are always received in the same order they were sent.152The messages are always received in the same order they were sent. Even when sent all at once.153153## Debugging154155When 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).156157Also, 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).158159## Best practices160161### Call `getOneMessage()`/`getEachMessage()` early162163If a process sends a message but the other process is not listening/receiving it, that message is silently ignored.164165This 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.166167Therefore, listening to messages should always be done early, before the other process sends any message.168169### First `getOneMessage()` call170171On 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.172173This allows the current process to call [`subprocess.sendMessage(message)`](api.md#subprocesssendmessagemessage) right after spawning the subprocess, even if it is still initializing.174154```js176// parent.js177import {execaNode} from 'execa';155import {sendMessage} from 'execa';156179const subprocess = execaNode`child.js`;180await subprocess.sendMessage('Hello');181await subprocess.sendMessage('world');157await Promise.all([158 sendMessage('first'),159 sendMessage('second'),160 sendMessage('third'),161]);162```163184```js185// child.js186import {getOneMessage} from 'execa';164## Debugging165188// This always retrieves the first message.189// Even if `sendMessage()` was called while the subprocess was still initializing.190const helloMessage = await getOneMessage();166When 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).167192// But this might miss the second message, and hang forever.193// That's because it is not the first call to `getOneMessage()`.194const worldMessage = await getOneMessage();195```168Also, 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).169197### Prefer `getEachMessage()` over multiple `getOneMessage()`198199If 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).200201This can be prevented by using [`getEachMessage()`](api.md#geteachmessage) instead.202203### Prefer `exchangeMessage(message)` over `sendMessage(message)` + `getOneMessage()`204205When _first_ sending a message, _then_ receiving a response, the following code should be avoided.206207```js208import {sendMessage, getOneMessage} from 'execa';209210await sendMessage(message);211212// The other process might respond between those two calls213214const response = await getOneMessage();215```216217Indeed, 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.218219Using [`exchangeMessage(message)`](api.md#exchangemessagemessage-getonemessageoptions) prevents this race condition.220221```js222import {exchangeMessage} from 'execa';223224const response = await exchangeMessage(message);225```226227However please note that, when doing the reverse (_first_ receiving a message, _then_ sending a response), the following code is correct.228229```js230import {sendMessage, getOneMessage} from 'execa';231232const message = await getOneMessage();233234// The other process is just waiting for a response between those two calls.235// So there is no race condition here.236237await sendMessage('response');238```239170<hr>171172[**Next**: 🐛 Debugging](debugging.md)\173[**Previous**: ⏳️ Streams](streams.md)\
1 unmodified line
deleted:lib/ipc/exchange.js-43 removed
modified:lib/ipc/forward.js+17 added-42 removed
1import {EventEmitter} from 'node:events';2import {onMessage, onDisconnect} from './incoming.js';3import {undoAddedReferences} from './reference.js';43// 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#L5478export const addReference = anyProcess => {9 const referencesCount = IPC_REFERENCES.get(anyProcess) ?? 0;10 if (referencesCount === 0) {11 anyProcess.channel?.ref();12 }1314 IPC_REFERENCES.set(anyProcess, referencesCount + 1);15};1617export const removeReference = anyProcess => {18 const referencesCount = IPC_REFERENCES.get(anyProcess);19 if (referencesCount === 1) {20 anyProcess.channel?.unref();21 }2223 IPC_REFERENCES.set(anyProcess, referencesCount - 1);24};2526const IPC_REFERENCES = new WeakMap();275// 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.30export const getIpcEmitter = anyProcess => {8export const getIpcEmitter = (anyProcess, isSubprocess) => {9 if (IPC_EMITTERS.has(anyProcess)) {10 return IPC_EMITTERS.get(anyProcess);11 }1213 // 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};2122const IPC_EMITTERS = new WeakMap();2324// 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#L72148const forwardEvents = (ipcEmitter, anyProcess) => {49 forwardEvent(ipcEmitter, anyProcess, 'message');50 forwardEvent(ipcEmitter, anyProcess, 'disconnect');27const 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};3353const 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 receive35export const isConnected = anyProcess => {36 const ipcEmitter = IPC_EMITTERS.get(anyProcess);37 return ipcEmitter === undefined38 ? anyProcess.channel !== null39 : ipcEmitter.connected;40};5859const forwardListener = (ipcEmitter, eventName, payload) => {60 ipcEmitter.emit(eventName, payload);61};6263const cleanupListener = (anyProcess, eventName, eventListener) => {64 anyProcess.removeListener(eventName, eventListener);65};
modified:lib/ipc/get-each.js+4 added-3 removed
1import {once, on} from 'node:events';2import {validateIpcMethod, disconnect} from './validation.js';3import {addReference, removeReference, getIpcEmitter} from './forward.js';3import {getIpcEmitter, isConnected} from './forward.js';4import {addReference, removeReference} from './reference.js';56// Like `[sub]process.on('message')` but promise-based7export const getEachMessage = ({anyProcess, isSubprocess, ipc}) => loopOnMessages({8 anyProcess,
7 unmodified lines
16 validateIpcMethod({17 methodName: 'getEachMessage',18 isSubprocess,19 ipc,19 isConnected: anyProcess.channel !== null,20 isConnected: isConnected(anyProcess),21 });2223 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 lines
modified:lib/ipc/get-one.js+10 added-21 removed
1import {once, on} from 'node:events';2import {validateIpcMethod, throwOnEarlyDisconnect} from './validation.js';3import {addReference, removeReference, getIpcEmitter} from './forward.js';3import {getIpcEmitter, isConnected} from './forward.js';4import {addReference, removeReference} from './reference.js';56// Like `[sub]process.once('message')` but promise-based7export 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 });1415 return onceMessage({16 anyProcess,17 isSubprocess,18 methodName,19 filter,20 });15 return getOneMessageAsync(anyProcess, isSubprocess, filter);16};1723// Same but used internally24export const onceMessage = async ({anyProcess, isSubprocess, methodName, filter}) => {18const 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 lines
42 }43 }44};4557const throwOnDisconnect = async ({ipcEmitter, isSubprocess, methodName, controller: {signal}}) => {46const 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
modified:lib/ipc/methods.js-7 removed
1 unmodified line
2import {promisify} from 'node:util';3import {sendMessage} from './send.js';4import {getOneMessage} from './get-one.js';5import {getEachMessage} from './get-each.js';6import {exchangeMessage} from './exchange.js';67// Add promise-based IPC methods in current process8export const addIpcMethods = (subprocess, {ipc}) => {9 Object.assign(subprocess, getIpcMethods(subprocess, false, ipc));
15 unmodified lines
25 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
1import {createDeferred} from '../utils/deferred.js';23// 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.6export const startSendMessage = anyProcess => {7 if (!OUTGOING_MESSAGES.has(anyProcess)) {8 OUTGOING_MESSAGES.set(anyProcess, new Set());9 }1011 const outgoingMessages = OUTGOING_MESSAGES.get(anyProcess);12 const onMessageSent = createDeferred();13 outgoingMessages.add(onMessageSent);14 return {outgoingMessages, onMessageSent};15};1617export const endSendMessage = ({outgoingMessages, onMessageSent}) => {18 outgoingMessages.delete(onMessageSent);19 onMessageSent.resolve();20};2122// Await while `sendMessage()` is ongoing23export 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};2930const 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#L5475export const addReference = anyProcess => {6 anyProcess.channel?.refCounted();7};89export const removeReference = anyProcess => {10 anyProcess.channel?.unrefCounted();11};1213// 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#L18016export 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 line
2 validateIpcMethod,3 handleSerializationError,4 disconnect,5} from './validation.js';6import {startSendMessage, endSendMessage} from './outgoing.js';6import {addReference, removeReference} from './forward.js';7import {addReference, removeReference} from './reference.js';89// 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.13export 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 });2021 return sendOneMessage({21 return sendMessageAsync({22 anyProcess,23 anyProcessSend,24 isSubprocess,25 methodName,25 message,26 });27};2830// Same but used internally31export const sendOneMessage = async ({anyProcess, anyProcessSend, isSubprocess, methodName, message}) => {29const 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 lines
19 }20};2122// When `getOneMessage()` could not complete due to an early disconnection23export const throwOnEarlyDisconnect = (methodName, isSubprocess) => {24 throw new Error(`${getNamespaceName(isSubprocess)}${methodName}() could not complete: the ${getOtherProcessName(isSubprocess)} exited or disconnected.`);23export const throwOnEarlyDisconnect = isSubprocess => {24 throw new Error(`${getNamespaceName(isSubprocess)}getOneMessage() could not complete: the ${getOtherProcessName(isSubprocess)} exited or disconnected.`);25};2627const getNamespaceName = isSubprocess => isSubprocess ? '' : 'subprocess.';2829const getOtherProcessName = isSubprocess => isSubprocess ? 'parent process' : 'subprocess';3031// Better error message when sending messages which cannot be serialized.32// Works with both `serialization: 'advanced'` and `serialization: 'json'`.33export const handleSerializationError = ({error, isSubprocess, methodName, message}) => {33export 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};3839const isSerializationError = ({code, message}) => SERIALIZATION_ERROR_CODES.has(code)
28 unmodified lines
modified:test/convert/readable.js+4 added-2 removed
117 unmodified lines
118 const stream = subprocess[methodName]();119120 subprocess.stdout.destroy();121122 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 lines
141142 const cause = new Error(foobarString);143 subprocess.stdout.destroy(cause);144145 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 lines
deleted:test/fixtures/ipc-echo-filter-exchange.js-5 removed
1#!/usr/bin/env node2import {sendMessage, exchangeMessage} from '../../index.js';3import {foobarArray} from '../helpers/input.js';45await sendMessage(await exchangeMessage('.', ({filter: message => message === foobarArray[1]})));
modified:test/fixtures/ipc-echo-filter.js+2 added-1 removed
1#!/usr/bin/env node2import {sendMessage, getOneMessage} from '../../index.js';3import {foobarArray} from '../helpers/input.js';45await sendMessage(await getOneMessage(({filter: message => message === foobarArray[1]})));5const message = await getOneMessage({filter: message => message === foobarArray[1]});6await sendMessage(message);
deleted:test/fixtures/ipc-echo-item-exchange.js-5 removed
1#!/usr/bin/env node2import {exchangeMessage, getOneMessage} from '../../index.js';34const [message] = await getOneMessage();5await exchangeMessage(message);
deleted:test/fixtures/ipc-echo-twice-filter-get.js-10 removed
1#!/usr/bin/env node2import {sendMessage, getOneMessage} from '../../index.js';3import {alwaysPass} from '../helpers/ipc.js';45const message = await getOneMessage({filter: alwaysPass});6const [secondMessage] = await Promise.all([7 getOneMessage({filter: alwaysPass}),8 sendMessage(message),9]);10await sendMessage(secondMessage);
deleted:test/fixtures/ipc-echo-twice-filter.js-7 removed
1#!/usr/bin/env node2import {sendMessage, getOneMessage, exchangeMessage} from '../../index.js';3import {alwaysPass} from '../helpers/ipc.js';45const message = await getOneMessage({filter: alwaysPass});6const secondMessage = await exchangeMessage(message, {filter: alwaysPass});7await sendMessage(secondMessage);
deleted:test/fixtures/ipc-echo-twice-get.js-9 removed
1#!/usr/bin/env node2import {sendMessage, getOneMessage} from '../../index.js';34const message = await getOneMessage();5const [secondMessage] = await Promise.all([6 getOneMessage(),7 sendMessage(message),8]);9await sendMessage(await secondMessage);
modified:test/fixtures/ipc-echo-twice.js+3 added-2 removed
1#!/usr/bin/env node2import {sendMessage, getOneMessage, exchangeMessage} from '../../index.js';2import {sendMessage, getOneMessage} from '../../index.js';34const message = await getOneMessage();5const secondMessage = await exchangeMessage(message);5await sendMessage(message);6const secondMessage = await getOneMessage();7await sendMessage(secondMessage);
deleted:test/fixtures/ipc-exchange-error.js-4 removed
1#!/usr/bin/env node2import {exchangeMessage} from '../../index.js';34await exchangeMessage(0n);
added:test/fixtures/ipc-get-send-get.js+12 added
1#!/usr/bin/env node2import {argv} from 'node:process';3import {sendMessage, getOneMessage} from '../../index.js';4import {alwaysPass} from '../helpers/ipc.js';56const filter = argv[2] === 'true' ? alwaysPass : undefined;78const message = await getOneMessage({filter});9await Promise.all([10 getOneMessage({filter}),11 sendMessage(message),12]);
added:test/fixtures/ipc-iterate-back-serial.js+24 added
1#!/usr/bin/env node2import process from 'node:process';3import {sendMessage, getOneMessage} from '../../index.js';4import {PARALLEL_COUNT} from '../helpers/parallel.js';5import {alwaysPass, getFirst} from '../helpers/ipc.js';67const filter = process.argv[2] === 'true' ? alwaysPass : undefined;89await sendMessage(await getOneMessage({filter}));1011const promise = sendMessage(1);12process.emit('message', '.');13await promise;1415const messages = Array.from({length: PARALLEL_COUNT}, (_, index) => index + 2);16for (const message of messages) {17 // eslint-disable-next-line no-await-in-loop18 await sendMessage(message);19}2021const secondPromise = process.argv[3] === 'true'22 ? getFirst()23 : getOneMessage({filter});24await sendMessage(await secondPromise);
added:test/fixtures/ipc-iterate-back.js+20 added
1#!/usr/bin/env node2import process from 'node:process';3import {sendMessage, getOneMessage} from '../../index.js';4import {PARALLEL_COUNT} from '../helpers/parallel.js';5import {alwaysPass, getFirst} from '../helpers/ipc.js';67const filter = process.argv[2] === 'true' ? alwaysPass : undefined;89await sendMessage(await getOneMessage({filter}));1011const messages = Array.from({length: PARALLEL_COUNT}, (_, index) => index + 1);12await Promise.all([13 ...messages.map(message => sendMessage(message)),14 process.emit('message', '.'),15]);1617const promise = process.argv[3] === 'true'18 ? getFirst()19 : getOneMessage({filter});20await sendMessage(await promise);
modified:test/fixtures/ipc-iterate-break.js+2 added-1 removed
1#!/usr/bin/env node2import {sendMessage, getEachMessage} from '../../index.js';3import {foobarString} from '../helpers/input.js';45const iterable = getEachMessage();6await sendMessage(foobarString);78// eslint-disable-next-line no-unreachable-loop8for await (const _ of getEachMessage()) {9for await (const _ of iterable) {10 break;11}
modified:test/fixtures/ipc-iterate-print.js+3 added-1 removed
1 unmodified line
2import process from 'node:process';3import {sendMessage, getEachMessage} from '../../index.js';4import {foobarString} from '../helpers/input.js';56const iterable = getEachMessage();78await sendMessage(foobarString);98for await (const message of getEachMessage()) {10for await (const message of iterable) {11 if (message === foobarString) {12 break;13 }14
2 unmodified lines
modified:test/fixtures/ipc-iterate-throw.js+2 added-1 removed
1#!/usr/bin/env node2import {sendMessage, getEachMessage} from '../../index.js';3import {foobarString} from '../helpers/input.js';45const iterable = getEachMessage();6await sendMessage(foobarString);78// eslint-disable-next-line no-unreachable-loop8for await (const message of getEachMessage()) {9for 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 node2import process from 'node:process';3import {getOneMessage} from '../../index.js';45await getOneMessage();67process.once('disconnect', () => {8 console.log('.');9});1011process.send('.');
added:test/fixtures/ipc-once-disconnect-send.js+11 added
1#!/usr/bin/env node2import process from 'node:process';3import {sendMessage} from '../../index.js';45await sendMessage('.');67process.once('disconnect', () => {8 console.log('.');9});1011process.send('.');
added:test/fixtures/ipc-once-disconnect.js+8 added
1#!/usr/bin/env node2import process from 'node:process';34process.send('.');56process.once('disconnect', () => {7 console.log('.');8});
added:test/fixtures/ipc-once-message-get.js+11 added
1#!/usr/bin/env node2import process from 'node:process';3import {getOneMessage} from '../../index.js';45await getOneMessage();67process.once('message', message => {8 console.log(message);9});1011process.send('.');
added:test/fixtures/ipc-once-message-send.js+9 added
1#!/usr/bin/env node2import process from 'node:process';3import {sendMessage} from '../../index.js';45await sendMessage('.');67process.once('message', message => {8 console.log(message);9});
added:test/fixtures/ipc-once-message.js+8 added
1#!/usr/bin/env node2import process from 'node:process';34process.send('.');56process.once('message', message => {7 console.log(message);8});
added:test/fixtures/ipc-print-many-each.js+13 added
1#!/usr/bin/env node2import {argv} from 'node:process';3import {getEachMessage} from '../../index.js';45const count = Number(argv[2]);67for (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 node2import {argv} from 'node:process';3import {getOneMessage} from '../../index.js';4import {alwaysPass} from '../helpers/ipc.js';56const count = Number(argv[2]);7const filter = argv[3] === 'true' ? alwaysPass : undefined;89for (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 node2import process from 'node:process';3import {exchangeMessage, sendMessage} from '../../index.js';4import {foobarString} from '../helpers/input.js';5import {alwaysPass} from '../helpers/ipc.js';67process.on('error', () => {});8const filter = process.argv[2] === 'true' ? alwaysPass : undefined;9const promise = exchangeMessage('.', {filter});10process.emit('error', new Error(foobarString));11await sendMessage(await promise);
added:test/fixtures/ipc-process-send-get.js+10 added
1#!/usr/bin/env node2import process from 'node:process';3import {foobarString} from '../helpers/input.js';4import {getOneMessage} from '../../index.js';56await getOneMessage();78process.send(foobarString, () => {9 console.log('.');10});
added:test/fixtures/ipc-process-send-send.js+10 added
1#!/usr/bin/env node2import process from 'node:process';3import {foobarString} from '../helpers/input.js';4import {sendMessage} from '../../index.js';56await sendMessage('.');78process.send(foobarString, () => {9 console.log('.');10});
added:test/fixtures/ipc-process-send.js+7 added
1#!/usr/bin/env node2import process from 'node:process';3import {foobarString} from '../helpers/input.js';45process.send(foobarString, () => {6 console.log('.');7});
deleted:test/fixtures/ipc-send-get.js-5 removed
1#!/usr/bin/env node2import {exchangeMessage} from '../../index.js';3import {foobarString} from '../helpers/input.js';45await exchangeMessage(foobarString);
added:test/fixtures/ipc-send-many.js+6 added
1#!/usr/bin/env node2import {argv} from 'node:process';3import {sendMessage} from '../../index.js';45const count = Number(argv[2]);6await Promise.all(Array.from({length: count}, (_, index) => sendMessage(index)));
added:test/fixtures/ipc-send-repeat.js+9 added
1#!/usr/bin/env node2import {argv} from 'node:process';3import {sendMessage} from '../../index.js';45const count = Number(argv[2]);6for (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 node2import {setTimeout} from 'node:timers/promises';3import {sendMessage} from '../../index.js';4import {foobarString} from '../helpers/input.js';56await sendMessage(foobarString);7await setTimeout(100);8console.log('.');
modified:test/helpers/ipc.js+15 added-15 removed
1import isPlainObj from 'is-plain-obj';1import {getEachMessage} from '../../index.js';23export const subprocessGetOne = (subprocess, options) => subprocess.getOneMessage(options);45export const subprocessSendGetOne = async (subprocess, message) => {6 const [response] = await Promise.all([7 subprocess.getOneMessage(),8 subprocess.sendMessage(message),9 ]);10 return response;11};1213export const subprocessExchange = (subprocess, messageOrOptions) => isPlainObj(messageOrOptions)14 ? subprocess.exchangeMessage('.', messageOrOptions)15 : subprocess.exchangeMessage(messageOrOptions);163// @todo: replace with Array.fromAsync(subprocess.getEachMessage()) after dropping support for Node <22.0.04export const iterateAllMessages = async subprocess => {5 const messages = [];6 for await (const message of subprocess.getEachMessage()) {
2 unmodified lines
910 return messages;11};1213export const subprocessGetFirst = async subprocess => {14 const [firstMessage] = await iterateAllMessages(subprocess);15 return firstMessage;16};1718export const getFirst = async () => {19 // eslint-disable-next-line no-unreachable-loop20 for await (const message of getEachMessage()) {21 return message;22 }23};2425export const subprocessGetOne = (subprocess, options) => subprocess.getOneMessage(options);2627export const alwaysPass = () => true;
modified:test/ipc/buffer-messages.js-15 removed
64 unmodified lines
65 t.deepEqual(ipcOutput, [`${index}`]);66 }),67 );68});6970test('"error" event does not interrupt result.ipcOutput', async t => {71 const subprocess = execa('ipc-echo-twice.js', {ipcInput: foobarString});7273 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);7778 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
1import test from 'ava';2import {execa} from '../../index.js';3import {setFixtureDirectory} from '../helpers/fixtures-directory.js';4import {foobarString, foobarArray} from '../helpers/input.js';5import {iterateAllMessages, alwaysPass} from '../helpers/ipc.js';67setFixtureDirectory();89const testParentErrorOne = async (t, filter, buffer) => {10 const subprocess = execa('ipc-send.js', {ipc: true, buffer});1112 const promise = subprocess.getOneMessage({filter});13 const cause = new Error(foobarString);14 subprocess.emit('error', cause);15 t.is(await promise, foobarString);1617 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};2526test('"error" event does not interrupt subprocess.getOneMessage(), buffer false', testParentErrorOne, undefined, false);27test('"error" event does not interrupt subprocess.getOneMessage(), buffer true', testParentErrorOne, undefined, true);28test('"error" event does not interrupt subprocess.getOneMessage(), buffer false, filter', testParentErrorOne, alwaysPass, false);29test('"error" event does not interrupt subprocess.getOneMessage(), buffer true, filter', testParentErrorOne, alwaysPass, true);3031const 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);3536 const {ipcOutput} = await subprocess;37 if (buffer) {38 t.deepEqual(ipcOutput, [foobarString]);39 }40};4142test('"error" event does not interrupt exports.getOneMessage(), buffer false', testSubprocessErrorOne, false, false);43test('"error" event does not interrupt exports.getOneMessage(), buffer true', testSubprocessErrorOne, false, true);44test('"error" event does not interrupt exports.getOneMessage(), buffer false, filter', testSubprocessErrorOne, true, false);45test('"error" event does not interrupt exports.getOneMessage(), buffer true, filter', testSubprocessErrorOne, true, true);4647const testParentErrorEach = async (t, buffer) => {48 const subprocess = execa('ipc-send-twice.js', {ipc: true, buffer});4950 const promise = iterateAllMessages(subprocess);51 const cause = new Error(foobarString);52 subprocess.emit('error', cause);5354 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};6364test('"error" event does not interrupt subprocess.getEachMessage(), buffer false', testParentErrorEach, false);65test('"error" event does not interrupt subprocess.getEachMessage(), buffer true', testParentErrorEach, true);6667const 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);7273 const {ipcOutput} = await subprocess;74 if (buffer) {75 t.deepEqual(ipcOutput, ['.']);76 }77};7879test('"error" event does not interrupt exports.getEachMessage(), buffer false', testSubprocessErrorEach, 'ipc-iterate-error.js', false);80test('"error" event does not interrupt exports.getEachMessage(), buffer true', testSubprocessErrorEach, 'ipc-iterate-error.js', true);8182test('"error" event does not interrupt result.ipcOutput', async t => {83 const subprocess = execa('ipc-echo-twice.js', {ipcInput: foobarString});8485 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);9091 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
1import test from 'ava';2import {execa} from '../../index.js';3import {setFixtureDirectory} from '../helpers/fixtures-directory.js';4import {foobarString, foobarArray} from '../helpers/input.js';5import {iterateAllMessages} from '../helpers/ipc.js';5import {PARALLEL_COUNT} from '../helpers/parallel.js';6import {iterateAllMessages} from '../helpers/ipc.js';78setFixtureDirectory();910test('Can iterate over IPC messages', async t => {
17 unmodified lines
28 const {ipcOutput} = await subprocess;29 t.deepEqual(ipcOutput, ['.', '.']);30});3132test('Can iterate multiple times over IPC messages in subprocess', async t => {33 const subprocess = execa('ipc-iterate-twice.js', {ipc: true});3435 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);4041 const {ipcOutput} = await subprocess;42 t.deepEqual(ipcOutput, [foobarString, '0.', foobarString, '1.']);43});4432test('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 lines
39 const {ipcOutput} = await subprocess;40 t.deepEqual(ipcOutput, foobarArray);41});4256const loopAndBreak = async (t, subprocess) => {43const 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 line
49};5051test('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});5758test('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);6174 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});6667test('Breaking from exports.getEachMessage() disconnects', async t => {68 const subprocess = execa('ipc-iterate-break.js', {ipc: true});6970 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'));7475 const {ipcOutput} = await subprocess;76 t.deepEqual(ipcOutput, [foobarString]);77});7892const iterateAndError = async (t, subprocess, cause) => {79const 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 lines
87test('Throwing from subprocess.getEachMessage() disconnects', async t => {88 const subprocess = execa('ipc-iterate-send.js', {ipc: true});8990 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);9293 const {ipcOutput} = await subprocess;94 t.deepEqual(ipcOutput, [foobarString]);95});9697test('Throwing from subprocess.getEachMessage() awaits the subprocess', async t => {111 const subprocess = execa('ipc-send-get.js', {ipc: true});11298 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);101116 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});106107test('Throwing from exports.getEachMessage() disconnects', async t => {108 const subprocess = execa('ipc-iterate-throw.js', {ipc: true});109110 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'));114115 const {exitCode, isTerminated, message, ipcOutput} = await t.throwsAsync(subprocess);116 t.is(exitCode, 1);117 t.false(isTerminated);
9 unmodified lines
127 const {ipcOutput} = await subprocess;128 t.deepEqual(ipcOutput, Array.from({length: PARALLEL_COUNT}, (_, index) => index));129});130131test('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)));135136 const {stdout} = await subprocess;137 const expectedOutput = indexes.join('\n');138 t.is(stdout, expectedOutput);139});140141test('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 lines
167 const {ipcOutput} = await subprocess;168 t.deepEqual(ipcOutput, [foobarString]);169});170176const testParentError = async (t, buffer) => {177 const subprocess = execa('ipc-send-twice.js', {ipc: true, buffer});178179 const promise = iterateAllMessages(subprocess);180 const cause = new Error(foobarString);181 subprocess.emit('error', cause);182183 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};192193test('"error" event does not interrupt subprocess.getEachMessage(), buffer false', testParentError, false);194test('"error" event does not interrupt subprocess.getEachMessage(), buffer true', testParentError, true);195196const 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);200201 const {ipcOutput} = await subprocess;202 if (buffer) {203 t.deepEqual(ipcOutput, ['.']);204 }205};206207test('"error" event does not interrupt exports.getEachMessage(), buffer false', testSubprocessError, 'ipc-iterate-error.js', false);208test('"error" event does not interrupt exports.getEachMessage(), buffer true', testSubprocessError, 'ipc-iterate-error.js', true);209171const testCleanupListeners = async (t, buffer) => {172 const subprocess = execa('ipc-send.js', {ipc: true, buffer});173174 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);176177 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]);181182 t.is(subprocess.listenerCount('message'), 0);183 t.is(subprocess.listenerCount('disconnect'), 0);
4 unmodified lines
modified:test/ipc/get-one.js+44 added-151 removed
2 unmodified lines
3import test from 'ava';4import {execa} from '../../index.js';5import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6import {foobarString, foobarArray} from '../helpers/input.js';7import {8 subprocessGetOne,9 subprocessSendGetOne,10 subprocessExchange,11 alwaysPass,12} from '../helpers/ipc.js';7import {alwaysPass} from '../helpers/ipc.js';8import {PARALLEL_COUNT} from '../helpers/parallel.js';910setFixtureDirectory();1117const 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};2324test('subprocess.getOneMessage() keeps the subprocess alive, buffer false', testKeepAlive, false, subprocessSendGetOne);25test('subprocess.getOneMessage() keeps the subprocess alive, buffer true', testKeepAlive, true, subprocessSendGetOne);26test('subprocess.getOneMessage() keeps the subprocess alive, buffer false, exchangeMessage()', testKeepAlive, false, subprocessExchange);27test('subprocess.getOneMessage() keeps the subprocess alive, buffer true, exchangeMessage()', testKeepAlive, true, subprocessExchange);2829const testBufferInitial = async (t, buffer, exchangeMethod) => {12const 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};1835test('Buffers initial message to subprocess, buffer false', testBufferInitial, false, subprocessSendGetOne);36test('Buffers initial message to subprocess, buffer true', testBufferInitial, true, subprocessSendGetOne);37test('Buffers initial message to subprocess, buffer false, exchangeMessage()', testBufferInitial, false, subprocessExchange);38test('Buffers initial message to subprocess, buffer true, exchangeMessage()', testBufferInitial, true, subprocessExchange);19test('Buffers initial message to subprocess, buffer false', testBufferInitial, false);20test('Buffers initial message to subprocess, buffer true', testBufferInitial, true);2122test('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 lines
38 const {ipcOutput} = await subprocess;39 t.deepEqual(ipcOutput, [foobarString]);40});4160const testFilterParent = async (t, exchangeMethod) => {42test('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]);4647 const {ipcOutput} = await subprocess;48 t.deepEqual(ipcOutput, foobarArray);67};49});5069test('subprocess.getOneMessage() can filter messages', testFilterParent, subprocessGetOne);70test('subprocess.exchangeMessage() can filter messages', testFilterParent, subprocessExchange);7172const testFilterSubprocess = async (t, fixtureName, expectedOutput) => {73 const subprocess = execa(fixtureName, {ipc: true});51test('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]);5556 const {ipcOutput} = await subprocess;78 t.deepEqual(ipcOutput, expectedOutput);79};57 t.deepEqual(ipcOutput, [foobarArray[1]]);58});5981test('exports.getOneMessage() can filter messages', testFilterSubprocess, 'ipc-echo-filter.js', [foobarArray[1]]);82test('exports.exchangeMessage() can filter messages', testFilterSubprocess, 'ipc-echo-filter-exchange.js', ['.', foobarArray[1]]);8384const testHeavyLoad = async (t, exchangeMethod) => {60test.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});6994test.serial('Can retrieve initial IPC messages under heavy load', testHeavyLoad, subprocessGetOne);95test.serial('Can retrieve initial IPC messages under heavy load, exchangeMessage()', testHeavyLoad, subprocessExchange);9697const testTwice = async (t, exchangeMethod, buffer, filter) => {70const 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};78106test('subprocess.getOneMessage() can be called twice at the same time, buffer false', testTwice, subprocessGetOne, false, undefined);107test('subprocess.getOneMessage() can be called twice at the same time, buffer true', testTwice, subprocessGetOne, true, undefined);108test('subprocess.getOneMessage() can be called twice at the same time, buffer false, filter', testTwice, subprocessGetOne, false, alwaysPass);109test('subprocess.getOneMessage() can be called twice at the same time, buffer true, filter', testTwice, subprocessGetOne, true, alwaysPass);110test('subprocess.exchangeMessage() can be called twice at the same time, buffer false', testTwice, subprocessExchange, false, undefined);111test('subprocess.exchangeMessage() can be called twice at the same time, buffer true', testTwice, subprocessExchange, true, undefined);112test('subprocess.exchangeMessage() can be called twice at the same time, buffer false, filter', testTwice, subprocessExchange, false, alwaysPass);113test('subprocess.exchangeMessage() can be called twice at the same time, buffer true, filter', testTwice, subprocessExchange, true, alwaysPass);79test('subprocess.getOneMessage() can be called twice at the same time, buffer false', testTwice, false, undefined);80test('subprocess.getOneMessage() can be called twice at the same time, buffer true', testTwice, true, undefined);81test('subprocess.getOneMessage() can be called twice at the same time, buffer false, filter', testTwice, false, alwaysPass);82test('subprocess.getOneMessage() can be called twice at the same time, buffer true, filter', testTwice, true, alwaysPass);83115const testCleanupListeners = async (t, exchangeMethod, buffer, filter) => {84const testCleanupListeners = async (t, buffer, filter) => {85 const subprocess = execa('ipc-send.js', {ipc: true, buffer});8687 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);89121 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);93126 t.is(subprocess.listenerCount('message'), 1);127 t.is(subprocess.listenerCount('disconnect'), 3);12894 t.is(await promise, foobarString);95 await subprocess;9697 t.is(subprocess.listenerCount('message'), 0);98 t.is(subprocess.listenerCount('disconnect'), 0);99};100135test('Cleans up subprocess.getOneMessage() listeners, buffer false', testCleanupListeners, subprocessGetOne, false, undefined);136test('Cleans up subprocess.getOneMessage() listeners, buffer true', testCleanupListeners, subprocessGetOne, true, undefined);137test('Cleans up subprocess.getOneMessage() listeners, buffer false, filter', testCleanupListeners, subprocessGetOne, false, alwaysPass);138test('Cleans up subprocess.getOneMessage() listeners, buffer true, filter', testCleanupListeners, subprocessGetOne, true, alwaysPass);139test('Cleans up subprocess.exchangeMessage() listeners, buffer false', testCleanupListeners, subprocessExchange, false, undefined);140test('Cleans up subprocess.exchangeMessage() listeners, buffer true', testCleanupListeners, subprocessExchange, true, undefined);141test('Cleans up subprocess.exchangeMessage() listeners, buffer false, filter', testCleanupListeners, subprocessExchange, false, alwaysPass);142test('Cleans up subprocess.exchangeMessage() listeners, buffer true, filter', testCleanupListeners, subprocessExchange, true, alwaysPass);101test('Cleans up subprocess.getOneMessage() listeners, buffer false', testCleanupListeners, false, undefined);102test('Cleans up subprocess.getOneMessage() listeners, buffer true', testCleanupListeners, true, undefined);103test('Cleans up subprocess.getOneMessage() listeners, buffer false, filter', testCleanupListeners, false, alwaysPass);104test('Cleans up subprocess.getOneMessage() listeners, buffer true, filter', testCleanupListeners, true, alwaysPass);105144const 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});106const 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);110111 subprocess.disconnect();
1 unmodified line
113 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};120162test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer false', testParentDisconnect, false, false, false);163test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer true', testParentDisconnect, true, false, false);164test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer false, filter', testParentDisconnect, false, true, false);121test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer false', testParentDisconnect, false, false);122test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer true', testParentDisconnect, true, false);123test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer false, filter', testParentDisconnect, false, true);124test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer true, filter', testParentDisconnect, true, false);166test('subprocess.disconnect() interrupts exports.exchangeMessage(), buffer false', testParentDisconnect, false, false, true);167test('subprocess.disconnect() interrupts exports.exchangeMessage(), buffer true', testParentDisconnect, true, false, true);168test('subprocess.disconnect() interrupts exports.exchangeMessage(), buffer false, filter', testParentDisconnect, false, true, true);169test('subprocess.disconnect() interrupts exports.exchangeMessage(), buffer true, filter', testParentDisconnect, true, true, true);125171// eslint-disable-next-line max-params172const testSubprocessDisconnect = async (t, exchangeMethod, methodName, buffer, filter) => {126const 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};132179test('Subprocess exit interrupts subprocess.getOneMessage(), buffer false', testSubprocessDisconnect, subprocessGetOne, 'getOneMessage', false, undefined);180test('Subprocess exit interrupts subprocess.getOneMessage(), buffer true', testSubprocessDisconnect, subprocessGetOne, 'getOneMessage', true, undefined);181test('Subprocess exit interrupts subprocess.getOneMessage(), buffer false, filter', testSubprocessDisconnect, subprocessGetOne, 'getOneMessage', false, alwaysPass);182test('Subprocess exit interrupts subprocess.getOneMessage(), buffer true, filter', testSubprocessDisconnect, subprocessGetOne, 'getOneMessage', true, alwaysPass);183test('Subprocess exit interrupts subprocess.exchangeMessage(), buffer false', testSubprocessDisconnect, subprocessExchange, 'exchangeMessage', false, undefined);184test('Subprocess exit interrupts subprocess.exchangeMessage(), buffer true', testSubprocessDisconnect, subprocessExchange, 'exchangeMessage', true, undefined);185test('Subprocess exit interrupts subprocess.exchangeMessage(), buffer false, filter', testSubprocessDisconnect, subprocessExchange, 'exchangeMessage', false, alwaysPass);186test('Subprocess exit interrupts subprocess.exchangeMessage(), buffer true, filter', testSubprocessDisconnect, subprocessExchange, 'exchangeMessage', true, alwaysPass);187188const testParentError = async (t, exchangeMethod, filter, buffer) => {189 const subprocess = execa('ipc-send.js', {ipc: true, buffer});190191 const promise = exchangeMethod(subprocess, {filter});192 const cause = new Error(foobarString);193 subprocess.emit('error', cause);194 t.is(await promise, foobarString);195196 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};204205test('"error" event does not interrupt subprocess.getOneMessage(), buffer false', testParentError, subprocessGetOne, undefined, false);206test('"error" event does not interrupt subprocess.getOneMessage(), buffer true', testParentError, subprocessGetOne, undefined, true);207test('"error" event does not interrupt subprocess.getOneMessage(), buffer false, filter', testParentError, subprocessGetOne, alwaysPass, false);208test('"error" event does not interrupt subprocess.getOneMessage(), buffer true, filter', testParentError, subprocessGetOne, alwaysPass, true);209test('"error" event does not interrupt subprocess.exchangeMessage(), buffer false', testParentError, subprocessExchange, undefined, false);210test('"error" event does not interrupt subprocess.exchangeMessage(), buffer true', testParentError, subprocessExchange, undefined, true);211test('"error" event does not interrupt subprocess.exchangeMessage(), buffer false, filter', testParentError, subprocessExchange, alwaysPass, false);212test('"error" event does not interrupt subprocess.exchangeMessage(), buffer true, filter', testParentError, subprocessExchange, alwaysPass, true);213214const 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);217218 const {ipcOutput} = await subprocess;219 if (buffer) {220 t.deepEqual(ipcOutput, [foobarString]);221 }222};223224test('"error" event does not interrupt exports.getOneMessage(), buffer false', testSubprocessError, false, false);225test('"error" event does not interrupt exports.getOneMessage(), buffer true', testSubprocessError, false, true);226test('"error" event does not interrupt exports.getOneMessage(), buffer false, filter', testSubprocessError, true, false);227test('"error" event does not interrupt exports.getOneMessage(), buffer true, filter', testSubprocessError, true, true);228229const 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);233234 const {ipcOutput} = await subprocess;235 if (buffer) {236 t.deepEqual(ipcOutput, ['.', foobarString]);237 }238};239240test('"error" event does not interrupt exports.exchangeMessage(), buffer false', testSubprocessExchangeError, false, false);241test('"error" event does not interrupt exports.exchangeMessage(), buffer true', testSubprocessExchangeError, false, true);242test('"error" event does not interrupt exports.exchangeMessage(), buffer false, filter', testSubprocessExchangeError, true, false);243test('"error" event does not interrupt exports.exchangeMessage(), buffer true, filter', testSubprocessExchangeError, true, true);133test('Subprocess exit interrupts subprocess.getOneMessage(), buffer false', testSubprocessDisconnect, false, undefined);134test('Subprocess exit interrupts subprocess.getOneMessage(), buffer true', testSubprocessDisconnect, true, undefined);135test('Subprocess exit interrupts subprocess.getOneMessage(), buffer false, filter', testSubprocessDisconnect, false, alwaysPass);136test('Subprocess exit interrupts subprocess.getOneMessage(), buffer true, filter', testSubprocessDisconnect, true, alwaysPass);
added:test/ipc/incoming.js+56 added
1import test from 'ava';2import {execa} from '../../index.js';3import {setFixtureDirectory} from '../helpers/fixtures-directory.js';4import {foobarString} from '../helpers/input.js';5import {alwaysPass} from '../helpers/ipc.js';6import {PARALLEL_COUNT} from '../helpers/parallel.js';78setFixtureDirectory();910const testSeriesParent = async (t, buffer, filter) => {11 const subprocess = execa('ipc-send-many.js', [`${PARALLEL_COUNT}`], {ipc: true, buffer});1213 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 }1718 const {ipcOutput} = await subprocess;19 if (buffer) {20 t.deepEqual(ipcOutput, Array.from({length: PARALLEL_COUNT}, (_, index) => index));21 }22};2324test('subprocess.getOneMessage() can be called multiple times in a row, buffer false', testSeriesParent, false, undefined);25test('subprocess.getOneMessage() can be called multiple times in a row, buffer true', testSeriesParent, true, undefined);26test('subprocess.getOneMessage() can be called multiple times in a row, buffer false, filter', testSeriesParent, false, alwaysPass);27test('subprocess.getOneMessage() can be called multiple times in a row, buffer true, filter', testSeriesParent, true, alwaysPass);2829const 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)));3334 const {stdout} = await subprocess;35 const expectedOutput = indexes.join('\n');36 t.is(stdout, expectedOutput);37};3839test('exports.getOneMessage() can be called multiple times in a row', testSeriesSubprocess, false);40test('exports.getOneMessage() can be called multiple times in a row, filter', testSeriesSubprocess, true);4142test('Can iterate multiple times over IPC messages in subprocess', async t => {43 const subprocess = execa('ipc-iterate-twice.js', {ipc: true});4445 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);5354 const {ipcOutput} = await subprocess;55 t.deepEqual(ipcOutput, [foobarString, '0.', foobarString, '1.']);56});
added:test/ipc/outgoing.js+88 added
1import test from 'ava';2import {execa} from '../../index.js';3import {setFixtureDirectory} from '../helpers/fixtures-directory.js';4import {foobarString} from '../helpers/input.js';5import {alwaysPass, subprocessGetOne, subprocessGetFirst} from '../helpers/ipc.js';6import {PARALLEL_COUNT} from '../helpers/parallel.js';78setFixtureDirectory();910const testSendHoldParent = async (t, getMessage, buffer, filter) => {11 const subprocess = execa('ipc-iterate.js', {ipc: true, buffer});1213 await subprocess.sendMessage(0);14 t.is(await subprocess.getOneMessage({filter}), 0);1516 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}), '.');2324 const {ipcOutput} = await subprocess;25 if (buffer) {26 const expectedOutput = [0, '.', ...messages];27 t.deepEqual(ipcOutput, expectedOutput);28 }29};3031test('Multiple parallel subprocess.sendMessage() + subprocess.getOneMessage(), buffer false', testSendHoldParent, subprocessGetOne, false, undefined);32test('Multiple parallel subprocess.sendMessage() + subprocess.getOneMessage(), buffer true', testSendHoldParent, subprocessGetOne, true, undefined);33test('Multiple parallel subprocess.sendMessage() + subprocess.getOneMessage(), buffer false, filter', testSendHoldParent, subprocessGetOne, false, alwaysPass);34test('Multiple parallel subprocess.sendMessage() + subprocess.getOneMessage(), buffer true, filter', testSendHoldParent, subprocessGetOne, true, alwaysPass);35test('Multiple parallel subprocess.sendMessage() + subprocess.getEachMessage(), buffer false', testSendHoldParent, subprocessGetFirst, false, undefined);36test('Multiple parallel subprocess.sendMessage() + subprocess.getEachMessage(), buffer true', testSendHoldParent, subprocessGetFirst, true, undefined);3738const 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};4344test('Multiple parallel exports.sendMessage() + exports.getOneMessage()', testSendHoldSubprocess, false, false);45test('Multiple parallel exports.sendMessage() + exports.getOneMessage(), filter', testSendHoldSubprocess, true, false);46test('Multiple parallel exports.sendMessage() + exports.getEachMessage()', testSendHoldSubprocess, false, true);4748const testSendHoldParentSerial = async (t, getMessage, buffer, filter) => {49 const subprocess = execa('ipc-iterate.js', {ipc: true, buffer});5051 await subprocess.sendMessage(0);52 t.is(await subprocess.getOneMessage({filter}), 0);5354 const promise = subprocess.sendMessage(1);55 subprocess.emit('message', '.');56 await promise;5758 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 }6364 await subprocess.sendMessage(foobarString);6566 const {ipcOutput} = await subprocess;67 if (buffer) {68 const expectedOutput = [0, '.', 1, ...messages];69 t.deepEqual(ipcOutput, expectedOutput);70 }71};7273test('Multiple serial subprocess.sendMessage() + subprocess.getOneMessage(), buffer false', testSendHoldParentSerial, subprocessGetOne, false, undefined);74test('Multiple serial subprocess.sendMessage() + subprocess.getOneMessage(), buffer true', testSendHoldParentSerial, subprocessGetOne, true, undefined);75test('Multiple serial subprocess.sendMessage() + subprocess.getOneMessage(), buffer false, filter', testSendHoldParentSerial, subprocessGetOne, false, alwaysPass);76test('Multiple serial subprocess.sendMessage() + subprocess.getOneMessage(), buffer true, filter', testSendHoldParentSerial, subprocessGetOne, true, alwaysPass);77test('Multiple serial subprocess.sendMessage() + subprocess.getEachMessage(), buffer false', testSendHoldParentSerial, subprocessGetFirst, false, undefined);78test('Multiple serial subprocess.sendMessage() + subprocess.getEachMessage(), buffer true', testSendHoldParentSerial, subprocessGetFirst, true, undefined);7980const 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};8586test('Multiple serial exports.sendMessage() + exports.getOneMessage()', testSendHoldSubprocessSerial, false, false);87test('Multiple serial exports.sendMessage() + exports.getOneMessage(), filter', testSendHoldSubprocessSerial, true, false);88test('Multiple serial exports.sendMessage() + exports.getEachMessage()', testSendHoldSubprocessSerial, false, true);
added:test/ipc/reference.js+102 added
1import test from 'ava';2import {execa} from '../../index.js';3import {setFixtureDirectory} from '../helpers/fixtures-directory.js';4import {foobarString} from '../helpers/input.js';5import {PARALLEL_COUNT} from '../helpers/parallel.js';67setFixtureDirectory();89const testKeepAliveSubprocess = async (t, fixtureName) => {10 const {timedOut} = await t.throwsAsync(execa(fixtureName, {ipc: true, timeout: 1e3}));11 t.true(timedOut);12};1314test('exports.getOneMessage() keeps the subprocess alive', testKeepAliveSubprocess, 'ipc-echo.js');15test('exports.getEachMessage() keeps the subprocess alive', testKeepAliveSubprocess, 'ipc-iterate.js');1617test('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});2223test('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});2829test('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});3435test('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});4041test('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);4546 const {ipcOutput, stdout} = await subprocess;47 t.deepEqual(ipcOutput, ['.']);48 t.is(stdout, foobarString);49});5051test('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);5556 const {ipcOutput, stdout} = await subprocess;57 t.deepEqual(ipcOutput, ['.']);58 t.is(stdout, foobarString);59});6061test('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);6667 const {ipcOutput, stdout} = await subprocess;68 t.deepEqual(ipcOutput, ['.']);69 t.is(stdout, foobarString);70});7172test('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();7677 const {ipcOutput, stdout} = await subprocess;78 t.deepEqual(ipcOutput, ['.']);79 t.is(stdout, '.');80});8182test('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();8788 const {ipcOutput, stdout} = await subprocess;89 t.deepEqual(ipcOutput, ['.', '.']);90 t.is(stdout, '.');91});9293test('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();9899 const {ipcOutput, stdout} = await subprocess;100 t.deepEqual(ipcOutput, ['.']);101 t.is(stdout, '.');102});
modified:test/ipc/send.js+35 added-54 removed
1import test from 'ava';2import {execa} from '../../index.js';3import {setFixtureDirectory} from '../helpers/fixtures-directory.js';4import {foobarString} from '../helpers/input.js';5import {subprocessSendGetOne, subprocessExchange} from '../helpers/ipc.js';5import {PARALLEL_COUNT} from '../helpers/parallel.js';67setFixtureDirectory();810const testExchange = async (t, exchangeMethod) => {9test('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});1516test('Can exchange IPC messages', testExchange, subprocessSendGetOne);17test('Can exchange IPC messages, exchangeMessage()', testExchange, subprocessExchange);1819const testHeavyLoad = async (t, exchangeMethod) => {16test.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});2629test.serial('Can exchange IPC messages under heavy load', testHeavyLoad, subprocessSendGetOne);30test.serial('Can exchange IPC messages under heavy load, exchangeMessage()', testHeavyLoad, subprocessExchange);3132const testDefaultSerialization = async (t, exchangeMethod) => {27test('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});3439test('The "serialization" option defaults to "advanced"', testDefaultSerialization, subprocessSendGetOne);40test('The "serialization" option defaults to "advanced", exchangeMessage()', testDefaultSerialization, subprocessExchange);4142const testJsonSerialization = async (t, exchangeMethod) => {35test('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});4249test('Can use "serialization: json" option', testJsonSerialization, subprocessSendGetOne);50test('Can use "serialization: json" option, exchangeMessage()', testJsonSerialization, subprocessExchange);5152const testJsonError = async (t, exchangeMethod) => {43test('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});4858test('Validates JSON payload with serialization: "json"', testJsonError, subprocessSendGetOne);59test('Validates JSON payload with serialization: "json", exchangeMessage()', testJsonError, subprocessExchange);6049const BIG_PAYLOAD_SIZE = '.'.repeat(1e6);5063const testBackpressure = async (t, exchangeMethod) => {51test('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});5971test('Handles backpressure', testBackpressure, subprocessSendGetOne);72test('Handles backpressure, exchangeMessage()', testBackpressure, subprocessExchange);60test('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);6474const 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'));6778 const {message} = await t.throwsAsync(subprocess[methodName](0n));79 t.true(message.includes(`subprocess.${methodName}()'s argument type is invalid`));8068 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});7387test('Disconnects IPC on exports.sendMessage() error', testParentDisconnect, 'sendMessage');88test('Disconnects IPC on exports.exchangeMessage() error', testParentDisconnect, 'exchangeMessage');8990const testSubprocessDisconnect = async (t, methodName, fixtureName) => {91 const subprocess = execa(fixtureName, {ipc: true});74test('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'));7879 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};100101test('Disconnects IPC on subprocess.sendMessage() error', testSubprocessDisconnect, 'sendMessage', 'ipc-send-error.js');102test('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 lines
20test('Cannot use subprocess.sendMessage() with stdio: [..., "ipc"]', testRequiredIpcSubprocess, 'sendMessage', stdioIpc);21test('Cannot use subprocess.getOneMessage() without ipc option', testRequiredIpcSubprocess, 'getOneMessage', {});22test('Cannot use subprocess.getOneMessage() with ipc: false', testRequiredIpcSubprocess, 'getOneMessage', {ipc: false});23test('Cannot use subprocess.getOneMessage() with stdio: [..., "ipc"]', testRequiredIpcSubprocess, 'getOneMessage', stdioIpc);24test('Cannot use subprocess.exchangeMessage() without ipc option', testRequiredIpcSubprocess, 'exchangeMessage', {});25test('Cannot use subprocess.exchangeMessage() with ipc: false', testRequiredIpcSubprocess, 'exchangeMessage', {ipc: false});26test('Cannot use subprocess.exchangeMessage() with stdio: [..., "ipc"]', testRequiredIpcSubprocess, 'exchangeMessage', stdioIpc);24test('Cannot use subprocess.getEachMessage() without ipc option', testRequiredIpcSubprocess, 'getEachMessage', {});25test('Cannot use subprocess.getEachMessage() with ipc: false', testRequiredIpcSubprocess, 'getEachMessage', {ipc: false});26test('Cannot use subprocess.getEachMessage() with stdio: [..., "ipc"]', testRequiredIpcSubprocess, 'getEachMessage', stdioIpc);27
5 unmodified lines
33test('Cannot use exports.sendMessage() without ipc option', testRequiredIpcExports, 'sendMessage', {});34test('Cannot use exports.sendMessage() with ipc: false', testRequiredIpcExports, 'sendMessage', {ipc: false});35test('Cannot use exports.getOneMessage() without ipc option', testRequiredIpcExports, 'getOneMessage', {});36test('Cannot use exports.getOneMessage() with ipc: false', testRequiredIpcExports, 'getOneMessage', {ipc: false});40test('Cannot use exports.exchangeMessage() without ipc option', testRequiredIpcExports, 'exchangeMessage', {});41test('Cannot use exports.exchangeMessage() with ipc: false', testRequiredIpcExports, 'exchangeMessage', {ipc: false});37test('Cannot use exports.getEachMessage() without ipc option', testRequiredIpcExports, 'getEachMessage', {});38test('Cannot use exports.getEachMessage() with ipc: false', testRequiredIpcExports, 'getEachMessage', {ipc: false});3940const testPostDisconnection = async (t, methodName) => {
4 unmodified lines
45};4647test('subprocess.sendMessage() after disconnection', testPostDisconnection, 'sendMessage');48test('subprocess.getOneMessage() after disconnection', testPostDisconnection, 'getOneMessage');54test('subprocess.exchangeMessage() after disconnection', testPostDisconnection, 'exchangeMessage');49test('subprocess.getEachMessage() after disconnection', testPostDisconnection, 'getEachMessage');5051const testPostDisconnectionSubprocess = async (t, methodName) => {52 const subprocess = execa('ipc-disconnect.js', [methodName], {ipc: true});
3 unmodified lines
56};5758test('exports.sendMessage() after disconnection', testPostDisconnectionSubprocess, 'sendMessage');59test('exports.getOneMessage() after disconnection', testPostDisconnectionSubprocess, 'getOneMessage');66test('exports.exchangeMessage() after disconnection', testPostDisconnectionSubprocess, 'exchangeMessage');60test('exports.getEachMessage() after disconnection', testPostDisconnectionSubprocess, 'getEachMessage');6169const testInvalidPayload = async (t, methodName, serialization, message) => {62const 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};6768const cycleObject = {};69cycleObject.self = cycleObject;70const toJsonCycle = {toJSON: () => ({test: true, toJsonCycle})};7179test('subprocess.sendMessage() cannot send undefined', testInvalidPayload, 'sendMessage', 'advanced', undefined);80test('subprocess.sendMessage() cannot send bigints', testInvalidPayload, 'sendMessage', 'advanced', 0n);81test('subprocess.sendMessage() cannot send symbols', testInvalidPayload, 'sendMessage', 'advanced', Symbol('test'));82test('subprocess.sendMessage() cannot send functions', testInvalidPayload, 'sendMessage', 'advanced', () => {});83test('subprocess.sendMessage() cannot send promises', testInvalidPayload, 'sendMessage', 'advanced', Promise.resolve());84test('subprocess.sendMessage() cannot send proxies', testInvalidPayload, 'sendMessage', 'advanced', new Proxy({}, {}));85test('subprocess.sendMessage() cannot send Intl', testInvalidPayload, 'sendMessage', 'advanced', new Intl.Collator());86test('subprocess.sendMessage() cannot send undefined, JSON', testInvalidPayload, 'sendMessage', 'json', undefined);87test('subprocess.sendMessage() cannot send bigints, JSON', testInvalidPayload, 'sendMessage', 'json', 0n);88test('subprocess.sendMessage() cannot send symbols, JSON', testInvalidPayload, 'sendMessage', 'json', Symbol('test'));89test('subprocess.sendMessage() cannot send functions, JSON', testInvalidPayload, 'sendMessage', 'json', () => {});90test('subprocess.sendMessage() cannot send cycles, JSON', testInvalidPayload, 'sendMessage', 'json', cycleObject);91test('subprocess.sendMessage() cannot send cycles in toJSON(), JSON', testInvalidPayload, 'sendMessage', 'json', toJsonCycle);92test('subprocess.exchangeMessage() cannot send undefined', testInvalidPayload, 'exchangeMessage', 'advanced', undefined);93test('subprocess.exchangeMessage() cannot send bigints', testInvalidPayload, 'exchangeMessage', 'advanced', 0n);94test('subprocess.exchangeMessage() cannot send symbols', testInvalidPayload, 'exchangeMessage', 'advanced', Symbol('test'));95test('subprocess.exchangeMessage() cannot send functions', testInvalidPayload, 'exchangeMessage', 'advanced', () => {});96test('subprocess.exchangeMessage() cannot send promises', testInvalidPayload, 'exchangeMessage', 'advanced', Promise.resolve());97test('subprocess.exchangeMessage() cannot send proxies', testInvalidPayload, 'exchangeMessage', 'advanced', new Proxy({}, {}));98test('subprocess.exchangeMessage() cannot send Intl', testInvalidPayload, 'exchangeMessage', 'advanced', new Intl.Collator());99test('subprocess.exchangeMessage() cannot send undefined, JSON', testInvalidPayload, 'exchangeMessage', 'json', undefined);100test('subprocess.exchangeMessage() cannot send bigints, JSON', testInvalidPayload, 'exchangeMessage', 'json', 0n);101test('subprocess.exchangeMessage() cannot send symbols, JSON', testInvalidPayload, 'exchangeMessage', 'json', Symbol('test'));102test('subprocess.exchangeMessage() cannot send functions, JSON', testInvalidPayload, 'exchangeMessage', 'json', () => {});103test('subprocess.exchangeMessage() cannot send cycles, JSON', testInvalidPayload, 'exchangeMessage', 'json', cycleObject);104test('subprocess.exchangeMessage() cannot send cycles in toJSON(), JSON', testInvalidPayload, 'exchangeMessage', 'json', toJsonCycle);72test('subprocess.sendMessage() cannot send undefined', testInvalidPayload, 'advanced', undefined);73test('subprocess.sendMessage() cannot send bigints', testInvalidPayload, 'advanced', 0n);74test('subprocess.sendMessage() cannot send symbols', testInvalidPayload, 'advanced', Symbol('test'));75test('subprocess.sendMessage() cannot send functions', testInvalidPayload, 'advanced', () => {});76test('subprocess.sendMessage() cannot send promises', testInvalidPayload, 'advanced', Promise.resolve());77test('subprocess.sendMessage() cannot send proxies', testInvalidPayload, 'advanced', new Proxy({}, {}));78test('subprocess.sendMessage() cannot send Intl', testInvalidPayload, 'advanced', new Intl.Collator());79test('subprocess.sendMessage() cannot send undefined, JSON', testInvalidPayload, 'json', undefined);80test('subprocess.sendMessage() cannot send bigints, JSON', testInvalidPayload, 'json', 0n);81test('subprocess.sendMessage() cannot send symbols, JSON', testInvalidPayload, 'json', Symbol('test'));82test('subprocess.sendMessage() cannot send functions, JSON', testInvalidPayload, 'json', () => {});83test('subprocess.sendMessage() cannot send cycles, JSON', testInvalidPayload, 'json', cycleObject);84test('subprocess.sendMessage() cannot send cycles in toJSON(), JSON', testInvalidPayload, 'json', toJsonCycle);85106const testSubprocessInvalidPayload = async (t, methodName, fixtureName) => {107 const subprocess = execa(fixtureName, {ipc: true});86test('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};112113test('exports.sendMessage() validates payload', testSubprocessInvalidPayload, 'sendMessage', 'ipc-echo-item.js');114test('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 lines
224225const testIpc = async (t, execaMethod, options) => {226 const subprocess = execaMethod('ipc-echo.js', [], options);227228 t.is(await subprocess.exchangeMessage(foobarString), foobarString);228 await subprocess.sendMessage(foobarString);229 t.is(await subprocess.getOneMessage(), foobarString);230231 const {stdio} = await subprocess;232 t.is(stdio.length, 4);233 t.is(stdio[3], undefined);
55 unmodified lines
deleted:test-d/ipc/exchange.test-d.ts-65 removed
1import {expectType, expectError} from 'tsd';2import {3 exchangeMessage,4 execa,5 type Message,6 type Options,7} from '../../index.js';89const subprocess = execa('test', {ipc: true});10expectType<Promise<Message<'advanced'>>>(subprocess.exchangeMessage(''));11const jsonSubprocess = execa('test', {ipc: true, serialization: 'json'});12expectType<Promise<Message<'json'>>>(jsonSubprocess.exchangeMessage(''));13expectType<Promise<Message>>(exchangeMessage(''));1415expectError(await subprocess.exchangeMessage());16expectError(await exchangeMessage());17expectError(await subprocess.exchangeMessage(undefined));18expectError(await exchangeMessage(undefined));19expectError(await subprocess.exchangeMessage(0n));20expectError(await exchangeMessage(0n));21expectError(await subprocess.exchangeMessage(Symbol('test')));22expectError(await exchangeMessage(Symbol('test')));23expectError(await subprocess.exchangeMessage('', ''));24expectError(await exchangeMessage('', ''));25expectError(await subprocess.exchangeMessage('', {}, ''));26expectError(await exchangeMessage('', {}, ''));2728await execa('test', {ipcInput: ''}).exchangeMessage('');29await execa('test', {ipcInput: '' as Message}).exchangeMessage('');30await execa('test', {} as Options).exchangeMessage?.('');31await execa('test', {ipc: true as boolean}).exchangeMessage?.('');32await execa('test', {ipcInput: '' as '' | undefined}).exchangeMessage?.('');3334expectType<undefined>(execa('test').exchangeMessage);35expectType<undefined>(execa('test', {}).exchangeMessage);36expectType<undefined>(execa('test', {ipc: false}).exchangeMessage);37expectType<undefined>(execa('test', {ipcInput: undefined}).exchangeMessage);38expectType<undefined>(execa('test', {ipc: false, ipcInput: ''}).exchangeMessage);3940await subprocess.exchangeMessage('', {filter: undefined} as const);41await subprocess.exchangeMessage('', {filter: (message: Message<'advanced'>) => true} as const);42await jsonSubprocess.exchangeMessage('', {filter: (message: Message<'json'>) => true} as const);43await jsonSubprocess.exchangeMessage('', {filter: (message: Message<'advanced'>) => true} as const);44await subprocess.exchangeMessage('', {filter: (message: Message<'advanced'> | bigint) => true} as const);45await subprocess.exchangeMessage('', {filter: () => true} as const);46expectError(await subprocess.exchangeMessage('', {filter: (message: Message<'advanced'>) => ''} as const));47// eslint-disable-next-line @typescript-eslint/no-empty-function48expectError(await subprocess.exchangeMessage('', {filter(message: Message<'advanced'>) {}} as const));49expectError(await subprocess.exchangeMessage('', {filter: (message: Message<'json'>) => true} as const));50expectError(await subprocess.exchangeMessage('', {filter: (message: '') => true} as const));51expectError(await subprocess.exchangeMessage('', {filter: true} as const));52expectError(await subprocess.exchangeMessage('', {unknownOption: true} as const));5354await exchangeMessage('', {filter: undefined} as const);55await exchangeMessage('', {filter: (message: Message) => true} as const);56await exchangeMessage('', {filter: (message: Message<'advanced'>) => true} as const);57await exchangeMessage('', {filter: (message: Message | bigint) => true} as const);58await exchangeMessage('', {filter: () => true} as const);59expectError(await exchangeMessage('', {filter: (message: Message) => ''} as const));60// eslint-disable-next-line @typescript-eslint/no-empty-function61expectError(await exchangeMessage('', {filter(message: Message) {}} as const));62expectError(await exchangeMessage('', {filter: (message: Message<'json'>) => true} as const));63expectError(await exchangeMessage('', {filter: (message: '') => true} as const));64expectError(await exchangeMessage('', {filter: true} as const));65expectError(await exchangeMessage('', {unknownOption: true} as const));
modified:test-d/ipc/message.test-d.ts+1 added-27 removed
1import {File} from 'node:buffer';2import {expectAssignable, expectNotAssignable} from 'tsd';3import {sendMessage, exchangeMessage, type Message} from '../../index.js';3import {sendMessage, type Message} from '../../index.js';45await sendMessage('');6await exchangeMessage('');6expectAssignable<Message>('');7expectAssignable<Message<'advanced'>>('');8expectAssignable<Message<'json'>>('');910await sendMessage(0);12await exchangeMessage(0);11expectAssignable<Message>(0);12expectAssignable<Message<'advanced'>>(0);13expectAssignable<Message<'json'>>(0);1415await sendMessage(true);18await exchangeMessage(true);16expectAssignable<Message>(true);17expectAssignable<Message<'advanced'>>(true);18expectAssignable<Message<'json'>>(true);1920await sendMessage([] as const);24await exchangeMessage([] as const);21expectAssignable<Message>([] as const);22expectAssignable<Message<'advanced'>>([] as const);23expectAssignable<Message<'json'>>([] as const);2425await sendMessage([true] as const);30await exchangeMessage([true] as const);26expectAssignable<Message>([true] as const);27expectAssignable<Message<'advanced'>>([true] as const);28expectAssignable<Message<'json'>>([true] as const);2930await sendMessage([undefined] as const);36await exchangeMessage([undefined] as const);31expectAssignable<Message>([undefined] as const);32expectAssignable<Message<'advanced'>>([undefined] as const);33expectNotAssignable<Message<'json'>>([undefined] as const);3435await sendMessage([0n] as const);42await exchangeMessage([0n] as const);36expectAssignable<Message>([0n] as const);37expectAssignable<Message<'advanced'>>([0n] as const);38expectNotAssignable<Message<'json'>>([0n] as const);3940await sendMessage({} as const);48await exchangeMessage({} as const);41expectAssignable<Message>({} as const);42expectAssignable<Message<'advanced'>>({} as const);43expectAssignable<Message<'json'>>({} as const);4445await sendMessage({test: true} as const);54await exchangeMessage({test: true} as const);46expectAssignable<Message>({test: true} as const);47expectAssignable<Message<'advanced'>>({test: true} as const);48expectAssignable<Message<'json'>>({test: true} as const);4950await sendMessage({test: undefined} as const);60await exchangeMessage({test: undefined} as const);51expectAssignable<Message>({test: undefined} as const);52expectAssignable<Message<'advanced'>>({test: undefined} as const);53expectNotAssignable<Message<'json'>>({test: undefined} as const);5455await sendMessage({test: 0n} as const);66await exchangeMessage({test: 0n} as const);56expectAssignable<Message>({test: 0n} as const);57expectAssignable<Message<'advanced'>>({test: 0n} as const);58expectNotAssignable<Message<'json'>>({test: 0n} as const);5960await sendMessage(null);72await exchangeMessage(null);61expectAssignable<Message>(null);62expectAssignable<Message<'advanced'>>(null);63expectAssignable<Message<'json'>>(null);6465await sendMessage(Number.NaN);78await exchangeMessage(Number.NaN);66expectAssignable<Message>(Number.NaN);67expectAssignable<Message<'advanced'>>(Number.NaN);68expectAssignable<Message<'json'>>(Number.NaN);6970await sendMessage(Number.POSITIVE_INFINITY);84await exchangeMessage(Number.POSITIVE_INFINITY);71expectAssignable<Message>(Number.POSITIVE_INFINITY);72expectAssignable<Message<'advanced'>>(Number.POSITIVE_INFINITY);73expectAssignable<Message<'json'>>(Number.POSITIVE_INFINITY);7475await sendMessage(new Map());90await exchangeMessage(new Map());76expectAssignable<Message>(new Map());77expectAssignable<Message<'advanced'>>(new Map());78expectNotAssignable<Message<'json'>>(new Map());7980await sendMessage(new Set());96await exchangeMessage(new Set());81expectAssignable<Message>(new Set());82expectAssignable<Message<'advanced'>>(new Set());83expectNotAssignable<Message<'json'>>(new Set());8485await sendMessage(new Date());102await exchangeMessage(new Date());86expectAssignable<Message>(new Date());87expectAssignable<Message<'advanced'>>(new Date());88expectNotAssignable<Message<'json'>>(new Date());8990await sendMessage(/regexp/);108await exchangeMessage(/regexp/);91expectAssignable<Message>(/regexp/);92expectAssignable<Message<'advanced'>>(/regexp/);93expectNotAssignable<Message<'json'>>(/regexp/);9495await sendMessage(new Blob());114await exchangeMessage(new Blob());96expectAssignable<Message>(new Blob());97expectAssignable<Message<'advanced'>>(new Blob());98expectNotAssignable<Message<'json'>>(new Blob());99100await sendMessage(new File([], ''));120await exchangeMessage(new File([], ''));101expectAssignable<Message>(new File([], ''));102expectAssignable<Message<'advanced'>>(new File([], ''));103expectNotAssignable<Message<'json'>>(new File([], ''));104105await sendMessage(new DataView(new ArrayBuffer(0)));126await exchangeMessage(new DataView(new ArrayBuffer(0)));106expectAssignable<Message>(new DataView(new ArrayBuffer(0)));107expectAssignable<Message<'advanced'>>(new DataView(new ArrayBuffer(0)));108expectNotAssignable<Message<'json'>>(new DataView(new ArrayBuffer(0)));109110await sendMessage(new ArrayBuffer(0));132await exchangeMessage(new ArrayBuffer(0));111expectAssignable<Message>(new ArrayBuffer(0));112expectAssignable<Message<'advanced'>>(new ArrayBuffer(0));113expectNotAssignable<Message<'json'>>(new ArrayBuffer(0));114115await sendMessage(new SharedArrayBuffer(0));138await exchangeMessage(new SharedArrayBuffer(0));116expectAssignable<Message>(new SharedArrayBuffer(0));117expectAssignable<Message<'advanced'>>(new SharedArrayBuffer(0));118expectNotAssignable<Message<'json'>>(new SharedArrayBuffer(0));119120await sendMessage(new Uint8Array());144await exchangeMessage(new Uint8Array());121expectAssignable<Message>(new Uint8Array());122expectAssignable<Message<'advanced'>>(new Uint8Array());123expectNotAssignable<Message<'json'>>(new Uint8Array());124125await sendMessage(AbortSignal.abort());150await exchangeMessage(AbortSignal.abort());126expectAssignable<Message>(AbortSignal.abort());127expectAssignable<Message<'advanced'>>(AbortSignal.abort());128expectNotAssignable<Message<'json'>>(AbortSignal.abort());129130await sendMessage(new Error('test'));156await exchangeMessage(new Error('test'));131expectAssignable<Message>(new Error('test'));132expectAssignable<Message<'advanced'>>(new Error('test'));133expectNotAssignable<Message<'json'>>(new Error('test'));
modified:types/arguments/options.d.ts+1 added-1 removed
197 unmodified lines
198 */199 readonly buffer?: FdGenericOption<boolean>;200201 /**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()`.203204 The subprocess must be a Node.js file.205206 @default `true` if either the `node` option or the `ipcInput` option is set, `false` otherwise
176 unmodified lines
modified:types/methods/main-async.d.ts+2 added-1 removed
185 unmodified lines
186// parent.js187import {execaNode} from 'execa';188189const subprocess = execaNode`child.js`;190const message = await subprocess.exchangeMessage('Hello from parent');190await subprocess.sendMessage('Hello from parent');191const message = await subprocess.getOneMessage();192console.log(message); // 'Hello from child'193```194195```
115 unmodified lines
modified:types/ipc.d.ts+2 added-17 removed
16 unmodified lines
17 | readonly JsonMessage[]18 | {readonly [key: string | number]: JsonMessage};1920/**21Type of messages exchanged between a process and its subprocess using `sendMessage()`, `getOneMessage()`, `exchangeMessage()` and `getEachMessage()`.21Type of messages exchanged between a process and its subprocess using `sendMessage()`, `getOneMessage()` and `getEachMessage()`.2223This requires the `ipc` option to be `true`. The type of `message` depends on the `serialization` option.24*/25export type Message<26 Serialization extends Options['serialization'] = Options['serialization'],27> = Serialization extends 'json' ? JsonMessage : AdvancedMessage;2829/**30Options to `getOneMessage()`, `exchangeMessage()`, `subprocess.getOneMessage()` and `subprocess.exchangeMessage()`30Options to `getOneMessage()` and `subprocess.getOneMessage()`31*/32type GetOneMessageOptions<33 Serialization extends Options['serialization'],34> = {
18 unmodified lines
53*/54export function getOneMessage(getOneMessageOptions?: GetOneMessageOptions<Options['serialization']>): Promise<Message>;5556/**57Send a `message` to the parent process, then receive a response from it.5859This requires the `ipc` option to be `true`. The type of `message` depends on the `serialization` option.60*/61export function exchangeMessage(message: Message, getOneMessageOptions?: GetOneMessageOptions<Options['serialization']>): Promise<Message>;6263/**57Iterate over each `message` from the parent process.5859This requires the `ipc` option to be `true`. The type of `message` depends on the `serialization` option.60*/
19 unmodified lines
80 */81 getOneMessage(getOneMessageOptions?: GetOneMessageOptions<Serialization>): Promise<Message<Serialization>>;8283 /**91 Send a `message` to the subprocess, then receive a response from it.9293 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>>;9697 /**84 Iterate over each `message` from the subprocess.8586 This requires the `ipc` option to be `true`. The type of `message` depends on the `serialization` option.87 */
4 unmodified lines
92 // 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 };9899// Whether IPC is enabled, based on the `ipc` and `ipcInput` options
15 unmodified lines
modified:index.d.ts-1 removed
18 unmodified lines
1920export {21 sendMessage,22 getOneMessage,23 exchangeMessage,23 getEachMessage,24 type Message,25} from './types/ipc.js';
modified:index.js-2 removed
15 unmodified lines
1617const {18 sendMessage,19 getOneMessage,20 exchangeMessage,20 getEachMessage,21} = getIpcExport();22export {23 sendMessage,24 getOneMessage,26 exchangeMessage,25 getEachMessage,26};
modified:readme.md+2 added-1 removed
268 unmodified lines
269// parent.js270import {execaNode} from 'execa';271272const subprocess = execaNode`child.js`;273const message = await subprocess.exchangeMessage('Hello from parent');273await subprocess.sendMessage('Hello from parent');274const message = await subprocess.getOneMessage();275console.log(message); // 'Hello from child'276```277278```js
114 unmodified lines