Skip to content
Myr

Add `strict` option to `sendMessage()` (#1098)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by ehmicky · committed by GitHub · parent b959030 · Browse files · 30 files+635 added−46 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

30 files+635 added−46 removed

  • tests:+329 added−6 removed
  • other:+306 added−40 removed

30 files+635 added−46 removed

modified:docs/api.md+21 added-6 removed
90 unmodified lines
91Split a `command` string into an array. For example, `'npm run build'` returns `['npm', 'run', 'build']` and `'argument otherArgument'` returns `['argument', 'otherArgument']`.9293[More info.](escaping.md#user-defined-input)9495### sendMessage(message)95### sendMessage(message, sendMessageOptions?)9697`message`: [`Message`](ipc.md#message-type)\98`sendMessageOptions`: [`SendMessageOptions`](#sendmessageoptions)\99_Returns_: `Promise<void>`100101Send a `message` to the parent process.102103This requires the [`ipc`](#optionsipc) option to be `true`. The [type](ipc.md#message-type) of `message` depends on the [`serialization`](#optionsserialization) option.104105[More info.](ipc.md#exchanging-messages)106107#### sendMessageOptions108109_Type_: `object`110111#### sendMessageOptions.strict112113_Type_: `boolean`\114_Default_: `false`115116Throw when the other process is not receiving or listening to messages.117118[More info.](ipc.md#ensure-messages-are-received)119120### getOneMessage(getOneMessageOptions?)121108_getOneMessageOptions_: [`GetOneMessageOptions`](#getonemessageoptions)\122`getOneMessageOptions`: [`GetOneMessageOptions`](#getonemessageoptions)\123_Returns_: [`Promise<Message>`](ipc.md#message-type)124125Receive a single `message` from the parent process.126
147 unmodified lines
274This is `undefined` if the subprocess failed to spawn.275276[More info.](termination.md#inter-process-termination)277264### subprocess.sendMessage(message)278### subprocess.sendMessage(message, sendMessageOptions)279280`message`: [`Message`](ipc.md#message-type)\281`sendMessageOptions`: [`SendMessageOptions`](#sendmessageoptions)\282_Returns_: `Promise<void>`283284Send a `message` to the subprocess.285
2 unmodified lines
288[More info.](ipc.md#exchanging-messages)289290### subprocess.getOneMessage(getOneMessageOptions?)291277_getOneMessageOptions_: [`GetOneMessageOptions`](#getonemessageoptions)\292`getOneMessageOptions`: [`GetOneMessageOptions`](#getonemessageoptions)\293_Returns_: [`Promise<Message>`](ipc.md#message-type)294295Receive a single `message` from the subprocess.296
202 unmodified lines
499### result.ipcOutput500501_Type_: [`Message[]`](ipc.md#message-type)502488All the messages [sent by the subprocess](#sendmessagemessage) to the current process.503All the messages [sent by the subprocess](#sendmessagemessage-sendmessageoptions) to the current process.504505This is empty unless the [`ipc`](#optionsipc) option is `true`. Also, this is empty if the [`buffer`](#optionsbuffer) option is `false`.506507[More info.](ipc.md#retrieve-all-messages)
420 unmodified lines
928929_Type:_ `boolean`\930_Default:_ `true` if either the [`node`](#optionsnode) option or the [`ipcInput`](#optionsipcinput) is set, `false` otherwise931917Enables exchanging messages with the subprocess using [`subprocess.sendMessage(message)`](#subprocesssendmessagemessage), [`subprocess.getOneMessage()`](#subprocessgetonemessagegetonemessageoptions) and [`subprocess.getEachMessage()`](#subprocessgeteachmessage).932Enables exchanging messages with the subprocess using [`subprocess.sendMessage(message)`](#subprocesssendmessagemessage-sendmessageoptions), [`subprocess.getOneMessage()`](#subprocessgetonemessagegetonemessageoptions) and [`subprocess.getEachMessage()`](#subprocessgeteachmessage).933934The subprocess must be a Node.js file.935936[More info.](ipc.md)
199 unmodified lines
modified:docs/execution.md+1 added-1 removed
modified:docs/ipc.md+38 added-3 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).15The current process sends messages with [`subprocess.sendMessage(message)`](api.md#subprocesssendmessagemessage-sendmessageoptions) and receives them with [`subprocess.getOneMessage()`](api.md#subprocessgetonemessagegetonemessageoptions).1617The subprocess uses [`sendMessage(message)`](api.md#sendmessagemessage) and [`getOneMessage()`](api.md#getonemessagegetonemessageoptions). Those are the same methods, but imported directly from the `'execa'` module.17The subprocess uses [`sendMessage(message)`](api.md#sendmessagemessage-sendmessageoptions) and [`getOneMessage()`](api.md#getonemessagegetonemessageoptions). Those are the same methods, but imported directly from the `'execa'` module.1819```js20// parent.js21import {execaNode} from 'execa';
1 unmodified line
23const subprocess = execaNode`child.js`;24await subprocess.sendMessage('Hello from parent');25const message = await subprocess.getOneMessage();26console.log(message); // 'Hello from child'27await subprocess;28```2930```js31// child.js
59 unmodified lines
91 }92}93```9495## Ensure messages are received9697When a message is sent by one process, the other process must receive it using [`getOneMessage()`](#exchanging-messages), [`getEachMessage()`](#listening-to-messages), or automatically with [`result.ipcOutput`](api.md#resultipcoutput). If not, that message is silently discarded.9899If the [`strict: true`](api.md#sendmessageoptionsstrict) option is passed to [`subprocess.sendMessage(message)`](api.md#subprocesssendmessagemessage-sendmessageoptions) or [`sendMessage(message)`](api.md#sendmessagemessage-sendmessageoptions), an error is thrown instead. This helps identifying subtle race conditions like the following example.100101```js102// main.js103import {execaNode} from 'execa';104105const subprocess = execaNode`build.js`;106// This `build` message is received107await subprocess.sendMessage('build', {strict: true});108// This `lint` message is not received, so it throws109await subprocess.sendMessage('lint', {strict: true});110await subprocess;111```112113```js114// build.js115import {getOneMessage} from 'execa';116117// Receives the 'build' message118const task = await getOneMessage();119// The `lint` message is sent while `runTask()` is ongoing120// Therefore the `lint` message is discarded121await runTask(task);122123// Does not receive the `lint` message124// Without `strict`, this would wait forever125const secondTask = await getOneMessage();126await runTask(secondTask);127```128129## Retrieve all messages130131The [`result.ipcOutput`](api.md#resultipcoutput) array contains all the messages sent by the subprocess. In many situations, this is simpler than using [`subprocess.getOneMessage()`](api.md#subprocessgetonemessagegetonemessageoptions) and [`subprocess.getEachMessage()`](api.md#subprocessgeteachmessage).132
45 unmodified lines
178179```js180import {execaNode} from 'execa';181147const subprocess = execaNode({serialization: 'json'})`child.js`;182await execaNode({serialization: 'json'})`child.js`;183```184185## Messages order186
23 unmodified lines
modified:docs/typescript.md+1 added-1 removed
6 unmodified lines
7# 🤓 TypeScript89## Available types1011The following types can be imported: [`ResultPromise`](api.md#return-value), [`Subprocess`](api.md#subprocess), [`Result`](api.md#result), [`ExecaError`](api.md#execaerror), [`Options`](api.md#options), [`StdinOption`](api.md#optionsstdin), [`StdoutStderrOption`](api.md#optionsstdout), [`TemplateExpression`](api.md#execacommand) and [`Message`](api.md#subprocesssendmessagemessage).11The following types can be imported: [`ResultPromise`](api.md#return-value), [`Subprocess`](api.md#subprocess), [`Result`](api.md#result), [`ExecaError`](api.md#execaerror), [`Options`](api.md#options), [`StdinOption`](api.md#optionsstdin), [`StdoutStderrOption`](api.md#optionsstdout), [`TemplateExpression`](api.md#execacommand) and [`Message`](api.md#subprocesssendmessagemessage-sendmessageoptions).1213```ts14import {15 execa,
156 unmodified lines
modified:lib/ipc/forward.js+7 added-1 removed
28 unmodified lines
29// The `message` and `disconnect` events are buffered in the subprocess until the first listener is setup.30// However, unbuffering happens after one tick, so this give enough time for the caller to setup the listener on the proxy emitter first.31// See https://github.com/nodejs/node/blob/2aaeaa863c35befa2ebaa98fb7737ec84df4d8e9/lib/internal/child_process.js#L72132const forwardEvents = ({ipcEmitter, anyProcess, channel, isSubprocess}) => {33 const boundOnMessage = onMessage.bind(undefined, anyProcess, ipcEmitter);33 const boundOnMessage = onMessage.bind(undefined, {34 anyProcess,35 channel,36 isSubprocess,37 ipcEmitter,38 });39 anyProcess.on('message', boundOnMessage);40 anyProcess.once('disconnect', onDisconnect.bind(undefined, {41 anyProcess,42 channel,43 isSubprocess,44 ipcEmitter,45 boundOnMessage,46 }));47 undoAddedReferences(channel, isSubprocess);
9 unmodified lines
modified:lib/ipc/get-each.js+28 added-3 removed
1import {once, on} from 'node:events';2import {validateIpcMethod, disconnect} from './validation.js';2import {validateIpcMethod, disconnect, getStrictResponseError} from './validation.js';3import {getIpcEmitter, isConnected} from './forward.js';4import {addReference, removeReference} from './reference.js';56// Like `[sub]process.on('message')` but promise-based
16 unmodified lines
2324 addReference(channel);25 const ipcEmitter = getIpcEmitter(anyProcess, channel, isSubprocess);26 const controller = new AbortController();27 const state = {};28 stopOnDisconnect(anyProcess, ipcEmitter, controller);29 abortOnStrictError({30 ipcEmitter,31 isSubprocess,32 controller,33 state,34 });35 return iterateOnMessages({36 anyProcess,37 channel,38 ipcEmitter,39 isSubprocess,40 shouldAwait,41 controller,42 state,43 });44};4546const stopOnDisconnect = async (anyProcess, ipcEmitter, controller) => {
2 unmodified lines
49 controller.abort();50 } catch {}51};5245const iterateOnMessages = async function * ({anyProcess, channel, ipcEmitter, isSubprocess, shouldAwait, controller}) {53const abortOnStrictError = async ({ipcEmitter, isSubprocess, controller, state}) => {54 try {55 const [error] = await once(ipcEmitter, 'strict:error', {signal: controller.signal});56 state.error = getStrictResponseError(error, isSubprocess);57 controller.abort();58 } catch {}59};6061const iterateOnMessages = async function * ({anyProcess, channel, ipcEmitter, isSubprocess, shouldAwait, controller, state}) {62 try {63 for await (const [message] of on(ipcEmitter, 'message', {signal: controller.signal})) {64 throwIfStrictError(state);65 yield message;66 }50 } catch {} finally {67 } catch {68 throwIfStrictError(state);69 } finally {70 controller.abort();71 removeReference(channel);7273 if (!isSubprocess) {
4 unmodified lines
78 await anyProcess;79 }80 }81};8283const throwIfStrictError = ({error}) => {84 if (error) {85 throw error;86 }87};
modified:lib/ipc/get-one.js+12 added-1 removed
1import {once, on} from 'node:events';2import {validateIpcMethod, throwOnEarlyDisconnect, disconnect} from './validation.js';2import {3 validateIpcMethod,4 throwOnEarlyDisconnect,5 disconnect,6 getStrictResponseError,7} from './validation.js';8import {getIpcEmitter, isConnected} from './forward.js';9import {addReference, removeReference} from './reference.js';1011// Like `[sub]process.once('message')` but promise-based
20 unmodified lines
32 try {33 return await Promise.race([34 getMessage(ipcEmitter, filter, controller),35 throwOnDisconnect(ipcEmitter, isSubprocess, controller),36 throwOnStrictError(ipcEmitter, isSubprocess, controller),37 ]);38 } catch (error) {39 disconnect(anyProcess);40 throw error;
19 unmodified lines
60const throwOnDisconnect = async (ipcEmitter, isSubprocess, {signal}) => {61 await once(ipcEmitter, 'disconnect', {signal});62 throwOnEarlyDisconnect(isSubprocess);63};6465const throwOnStrictError = async (ipcEmitter, isSubprocess, {signal}) => {66 const [error] = await once(ipcEmitter, 'strict:error', {signal});67 throw getStrictResponseError(error, isSubprocess);68};
modified:lib/ipc/incoming.js+26 added-9 removed
1import {once} from 'node:events';2import {scheduler} from 'node:timers/promises';3import {waitForOutgoingMessages} from './outgoing.js';4import {redoAddedReferences} from './reference.js';5import {handleStrictRequest, handleStrictResponse} from './strict.js';67// By default, Node.js buffers `message` events.8// - Buffering happens when there is a `message` event is emitted but there is no handler.9// - As soon as a `message` event handler is set, all buffered `message` events are emitted, emptying the buffer.
11 unmodified lines
21// - Forgetting to setup a `message` listener, or setting it up too late, is a programming mistake.22// The default behavior does not allow users to realize they made that mistake.23// To solve those problems, instead of buffering messages, we debounce them.24// The `message` event so it is emitted at most once per macrotask.24export const onMessage = async (anyProcess, ipcEmitter, message) => {25export const onMessage = async ({anyProcess, channel, isSubprocess, ipcEmitter}, wrappedMessage) => {26 if (handleStrictResponse(wrappedMessage)) {27 return;28 }2930 if (!INCOMING_MESSAGES.has(anyProcess)) {31 INCOMING_MESSAGES.set(anyProcess, []);32 }3334 const incomingMessages = INCOMING_MESSAGES.get(anyProcess);30 incomingMessages.push(message);35 incomingMessages.push(wrappedMessage);3637 if (incomingMessages.length > 1) {38 return;39 }4041 while (incomingMessages.length > 0) {42 // eslint-disable-next-line no-await-in-loop38 await waitForOutgoingMessages(anyProcess);43 await waitForOutgoingMessages(anyProcess, ipcEmitter);44 // eslint-disable-next-line no-await-in-loop45 await scheduler.yield();4647 // eslint-disable-next-line no-await-in-loop48 const message = await handleStrictRequest({49 wrappedMessage: incomingMessages[0],50 anyProcess,51 channel,52 isSubprocess,53 ipcEmitter,54 });5556 incomingMessages.shift();41 ipcEmitter.emit('message', incomingMessages.shift());57 ipcEmitter.emit('message', message);58 ipcEmitter.emit('message:done');59 }60};6145const INCOMING_MESSAGES = new WeakMap();4662// If the `message` event is currently debounced, the `disconnect` event must wait for it48export const onDisconnect = async ({anyProcess, channel, ipcEmitter, boundOnMessage}) => {63export const onDisconnect = async ({anyProcess, channel, isSubprocess, ipcEmitter, boundOnMessage}) => {64 const incomingMessages = INCOMING_MESSAGES.get(anyProcess);65 while (incomingMessages?.length > 0) {66 // eslint-disable-next-line no-await-in-loop52 await once(ipcEmitter, 'message');67 await once(ipcEmitter, 'message:done');68 }6970 anyProcess.removeListener('message', boundOnMessage);56 redoAddedReferences(channel);71 redoAddedReferences(channel, isSubprocess);72 ipcEmitter.connected = false;73 ipcEmitter.emit('disconnect');74};7576const INCOMING_MESSAGES = new WeakMap();
modified:lib/ipc/methods.js+1 added
13 unmodified lines
14// Retrieve the `ipc` shared by both the current process and the subprocess15const getIpcMethods = (anyProcess, isSubprocess, ipc) => ({16 sendMessage: sendMessage.bind(undefined, {17 anyProcess,18 channel: anyProcess.channel,19 isSubprocess,20 ipc,21 }),22 getOneMessage: getOneMessage.bind(undefined, {
12 unmodified lines
modified:lib/ipc/outgoing.js+14 added-3 removed
1import {createDeferred} from '../utils/deferred.js';2import {SUBPROCESS_OPTIONS} from '../arguments/fd-options.js';34// When `sendMessage()` is ongoing, any `message` being received waits before being emitted.5// This allows calling one or multiple `await sendMessage()` followed by `await getOneMessage()`/`await getEachMessage()`.6// Without running into a race condition when the other process sends a response too fast, before the current process set up a listener.
12 unmodified lines
19 outgoingMessages.delete(onMessageSent);20 onMessageSent.resolve();21};2222// Await while `sendMessage()` is ongoing23export const waitForOutgoingMessages = async anyProcess => {24 while (OUTGOING_MESSAGES.get(anyProcess)?.size > 0) {23// Await while `sendMessage()` is ongoing, unless there is already a `message` listener24export const waitForOutgoingMessages = async (anyProcess, ipcEmitter) => {25 while (!hasMessageListeners(anyProcess, ipcEmitter) && OUTGOING_MESSAGES.get(anyProcess)?.size > 0) {26 // eslint-disable-next-line no-await-in-loop27 await Promise.all(OUTGOING_MESSAGES.get(anyProcess));28 }29};3031const OUTGOING_MESSAGES = new WeakMap();3233// Whether any `message` listener is setup34export const hasMessageListeners = (anyProcess, ipcEmitter) => ipcEmitter.listenerCount('message') > getMinListenerCount(anyProcess);3536// When `buffer` is `false`, we set up a `message` listener that should be ignored.37// That listener is only meant to intercept `strict` acknowledgement responses.38const getMinListenerCount = anyProcess => SUBPROCESS_OPTIONS.has(anyProcess)39 && !SUBPROCESS_OPTIONS.get(anyProcess).options.buffer.at(-1)40 ? 141 : 0;
modified:lib/ipc/send.js+22 added-4 removed
4 unmodified lines
5 handleSerializationError,6 disconnect,7} from './validation.js';8import {startSendMessage, endSendMessage} from './outgoing.js';9import {handleSendStrict, waitForStrictResponse} from './strict.js';1011// Like `[sub]process.send()` but promise-based.12// We do not `await subprocess` during `.sendMessage()` nor `.getOneMessage()` since those methods are transient.13// Users would still need to `await subprocess` after the method is done.14// Also, this would prevent `unhandledRejection` event from being emitted, making it silent.14export const sendMessage = ({anyProcess, isSubprocess, ipc}, message) => {15export const sendMessage = ({anyProcess, channel, isSubprocess, ipc}, message, {strict = false} = {}) => {16 validateIpcMethod({17 methodName: 'sendMessage',18 isSubprocess,19 ipc,20 isConnected: anyProcess.connected,21 });2222 return sendMessageAsync({anyProcess, isSubprocess, message});23 return sendMessageAsync({24 anyProcess,25 channel,26 isSubprocess,27 message,28 strict,29 });30};3125const sendMessageAsync = async ({anyProcess, isSubprocess, message}) => {32const sendMessageAsync = async ({anyProcess, channel, isSubprocess, message, strict}) => {33 const outgoingMessagesState = startSendMessage(anyProcess);34 const sendMethod = getSendMethod(anyProcess);35 const wrappedMessage = handleSendStrict({36 anyProcess,37 channel,38 isSubprocess,39 message,40 strict,41 });4243 try {29 await sendMethod(message);44 await Promise.all([45 waitForStrictResponse(wrappedMessage, anyProcess, isSubprocess),46 sendMethod(wrappedMessage),47 ]);48 } catch (error) {49 disconnect(anyProcess);50 handleEpipeError(error, isSubprocess);51 handleSerializationError(error, isSubprocess, message);
18 unmodified lines
added:lib/ipc/strict.js+89 added
1import {once} from 'node:events';2import {createDeferred} from '../utils/deferred.js';3import {incrementMaxListeners} from '../utils/max-listeners.js';4import {sendMessage} from './send.js';5import {throwOnMissingStrict, throwOnStrictDisconnect} from './validation.js';6import {getIpcEmitter} from './forward.js';7import {hasMessageListeners} from './outgoing.js';89// When using the `strict` option, wrap the message with metadata during `sendMessage()`10export const handleSendStrict = ({anyProcess, channel, isSubprocess, message, strict}) => {11 if (!strict) {12 return message;13 }1415 getIpcEmitter(anyProcess, channel, isSubprocess);16 return {id: count++, type: REQUEST_TYPE, message};17};1819let count = 0n;2021// The other process then sends the acknowledgment back as a response22export const handleStrictRequest = async ({wrappedMessage, anyProcess, channel, isSubprocess, ipcEmitter}) => {23 if (wrappedMessage?.type !== REQUEST_TYPE) {24 return wrappedMessage;25 }2627 const {id, message} = wrappedMessage;28 const response = {id, type: RESPONSE_TYPE, message: hasMessageListeners(anyProcess, ipcEmitter)};2930 try {31 await sendMessage({32 anyProcess,33 channel,34 isSubprocess,35 ipc: true,36 }, response);37 } catch (error) {38 ipcEmitter.emit('strict:error', error);39 }4041 return message;42};4344// Reception of the acknowledgment response45export const handleStrictResponse = wrappedMessage => {46 if (wrappedMessage?.type !== RESPONSE_TYPE) {47 return false;48 }4950 const {id, message: hasListeners} = wrappedMessage;51 STRICT_RESPONSES[id].resolve(hasListeners);52 return true;53};5455// Wait for the other process to receive the message from `sendMessage()`56export const waitForStrictResponse = async (wrappedMessage, anyProcess, isSubprocess) => {57 if (wrappedMessage?.type !== REQUEST_TYPE) {58 return;59 }6061 const deferred = createDeferred();62 STRICT_RESPONSES[wrappedMessage.id] = deferred;6364 try {65 const controller = new AbortController();66 const hasListeners = await Promise.race([67 deferred,68 throwOnDisconnect(anyProcess, isSubprocess, controller),69 ]);70 controller.abort();7172 if (!hasListeners) {73 throwOnMissingStrict(isSubprocess);74 }75 } finally {76 delete STRICT_RESPONSES[wrappedMessage.id];77 }78};7980const STRICT_RESPONSES = {};8182const throwOnDisconnect = async (anyProcess, isSubprocess, {signal}) => {83 incrementMaxListeners(anyProcess, 1, signal);84 await once(anyProcess, 'disconnect', {signal});85 throwOnStrictDisconnect(isSubprocess);86};8788const REQUEST_TYPE = 'execa:ipc:request';89const RESPONSE_TYPE = 'execa:ipc:response';
modified:lib/ipc/validation.js+13 added
22 unmodified lines
23export const throwOnEarlyDisconnect = isSubprocess => {24 throw new Error(`${getNamespaceName(isSubprocess)}getOneMessage() could not complete: the ${getOtherProcessName(isSubprocess)} exited or disconnected.`);25};2627// When the other process used `strict` but the current process had I/O error calling `sendMessage()` for the response28export const getStrictResponseError = (error, isSubprocess) => new Error(`${getNamespaceName(isSubprocess)}sendMessage() failed when sending an acknowledgment response to the ${getOtherProcessName(isSubprocess)}.`, {cause: error});2930// When using `strict` but the other process was not listening for messages31export const throwOnMissingStrict = isSubprocess => {32 throw new Error(`${getNamespaceName(isSubprocess)}sendMessage() failed: the ${getOtherProcessName(isSubprocess)} is not listening to incoming messages.`);33};3435// When using `strict` but the other process disconnected before receiving the message36export const throwOnStrictDisconnect = isSubprocess => {37 throw new Error(`${getNamespaceName(isSubprocess)}sendMessage() failed: the ${getOtherProcessName(isSubprocess)} exited without listening to incoming messages.`);38};3940const getNamespaceName = isSubprocess => isSubprocess ? '' : 'subprocess.';4142const getOtherProcessName = isSubprocess => isSubprocess ? 'parent process' : 'subprocess';43
44 unmodified lines
added:test/fixtures/ipc-echo-twice-wait.js+10 added
1#!/usr/bin/env node2import {setTimeout} from 'node:timers/promises';3import {sendMessage, getOneMessage} from '../../index.js';45const message = await getOneMessage();6await sendMessage(message);7const secondMessage = await getOneMessage();8await sendMessage(secondMessage);9await setTimeout(1e3);10await sendMessage('.');
added:test/fixtures/ipc-get-io-error.js+7 added
1#!/usr/bin/env node2import process from 'node:process';3import {getOneMessage} from '../../index.js';4import {mockSendIoError} from '../helpers/ipc.js';56mockSendIoError(process);7console.log(await getOneMessage());
added:test/fixtures/ipc-iterate-io-error.js+9 added
1#!/usr/bin/env node2import process from 'node:process';3import {getEachMessage} from '../../index.js';4import {mockSendIoError} from '../helpers/ipc.js';56mockSendIoError(process);7for await (const message of getEachMessage()) {8 console.log(message);9}
added:test/fixtures/ipc-send-echo-strict.js+7 added
1#!/usr/bin/env node2import {setTimeout} from 'node:timers/promises';3import {sendMessage, getOneMessage} from '../../index.js';45await sendMessage('.', {strict: true});6await setTimeout(10);7await sendMessage(await getOneMessage());
added:test/fixtures/ipc-send-echo-wait.js+7 added
1#!/usr/bin/env node2import {setTimeout} from 'node:timers/promises';3import {sendMessage, getOneMessage} from '../../index.js';45await sendMessage('.');6await setTimeout(1e3);7await sendMessage(await getOneMessage());
added:test/fixtures/ipc-send-strict-catch.js+9 added
1#!/usr/bin/env node2import {sendMessage} from '../../index.js';3import {foobarString} from '../helpers/input.js';45try {6 await sendMessage(foobarString, {strict: true});7} catch {8 await sendMessage(foobarString);9}
added:test/fixtures/ipc-send-strict-get.js+6 added
1#!/usr/bin/env node2import {sendMessage, getOneMessage} from '../../index.js';3import {foobarString} from '../helpers/input.js';45await sendMessage(foobarString, {strict: true});6await sendMessage(await getOneMessage());
added:test/fixtures/ipc-send-strict-listen.js+9 added
1#!/usr/bin/env node2import {sendMessage, getOneMessage} from '../../index.js';3import {foobarString} from '../helpers/input.js';45const [message] = await Promise.race([6 getOneMessage(),7 sendMessage(foobarString, {strict: true}),8]);9await sendMessage(message);
added:test/fixtures/ipc-send-strict.js+5 added
1#!/usr/bin/env node2import {sendMessage} from '../../index.js';3import {foobarString} from '../helpers/input.js';45await sendMessage(foobarString, {strict: true});
modified:test/ipc/get-one.js+1 added-1 removed
40 unmodified lines
41 t.deepEqual(ipcOutput, [foobarString]);42});4344test('Throwing from exports.getOneMessage() filter disconnects', async t => {45 const subprocess = execa('ipc-get-filter-throw.js', {ipc: true, ipcInput: 0});45 const subprocess = execa('ipc-get-filter-throw.js', {ipcInput: 0});46 await t.throwsAsync(subprocess.getOneMessage(), {47 message: /subprocess.getOneMessage\(\) could not complete/,48 });49
84 unmodified lines
modified:test/ipc/ipc-input.js+5 added
44 unmodified lines
45 const {message, cause} = await t.throwsAsync(execa('empty.js', {ipcInput: 0n}));46 t.true(message.includes('subprocess.sendMessage()\'s argument type is invalid: the message cannot be serialized: 0.'));47 t.true(cause.cause.message.includes('The "message" argument must be one of type string'));48});4950test('Can use "ipcInput" option even if the subprocess is not listening to messages', async t => {51 const {ipcOutput} = await execa('empty.js', {ipcInput: foobarString});52 t.deepEqual(ipcOutput, []);53});
modified:test/ipc/outgoing.js+2 added-2 removed
34 unmodified lines
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});39 const {ipcOutput} = await execa('ipc-iterate-back.js', [`${filter}`, `${isGetEach}`], {ipcInput: 0});40 const expectedOutput = [...Array.from({length: PARALLEL_COUNT + 1}, (_, index) => index), '.'];41 t.deepEqual(ipcOutput, expectedOutput);42};43
33 unmodified lines
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'});81 const {ipcOutput} = await execa('ipc-iterate-back-serial.js', [`${filter}`, `${isGetEach}`], {ipcInput: 0});82 const expectedOutput = [...Array.from({length: PARALLEL_COUNT + 2}, (_, index) => index), '.'];83 t.deepEqual(ipcOutput, expectedOutput);84};85
3 unmodified lines
modified:test/ipc/pending.js+29 added-2 removed
6 unmodified lines
78setFixtureDirectory();910const testBufferInitial = async (t, buffer) => {11 const subprocess = execa('ipc-echo-wait.js', {ipc: true, buffer, ipcInput: foobarString});11 const subprocess = execa('ipc-echo-wait.js', {buffer, ipcInput: foobarString});12 t.is(await subprocess.getOneMessage(), foobarString);1314 const {ipcOutput} = await subprocess;15 t.deepEqual(ipcOutput, buffer ? [foobarString] : []);
1 unmodified line
1718test('Buffers initial message to subprocess, buffer false', testBufferInitial, false);19test('Buffers initial message to subprocess, buffer true', testBufferInitial, true);2021const testBufferInitialSend = async (t, buffer) => {22 const subprocess = execa('ipc-send-echo-wait.js', {buffer, ipcInput: foobarString});23 t.is(await subprocess.getOneMessage(), '.');24 t.is(await subprocess.getOneMessage(), foobarString);2526 const {ipcOutput} = await subprocess;27 t.deepEqual(ipcOutput, buffer ? ['.', foobarString] : []);28};2930test('sendMessage() does not empty the initial message buffering, buffer false', testBufferInitialSend, false);31test('sendMessage() does not empty the initial message buffering, buffer true', testBufferInitialSend, true);3233const testBufferInitialStrict = async (t, buffer) => {34 const subprocess = execa('ipc-send-echo-strict.js', {buffer, ipcInput: foobarString});35 t.is(await subprocess.getOneMessage(), '.');36 await setTimeout(1e3);37 const promise = subprocess.getOneMessage();38 await subprocess.sendMessage('..');39 t.is(await promise, '..');4041 const {ipcOutput} = await subprocess;42 t.deepEqual(ipcOutput, buffer ? ['.', '..'] : []);43};4445test('sendMessage() with "strict" empties the initial message buffering, buffer false', testBufferInitialStrict, false);46test('sendMessage() with "strict" empties the initial message buffering, buffer true', testBufferInitialStrict, true);4748const testNoBufferInitial = async (t, buffer) => {49 const subprocess = execa('ipc-send-print.js', {ipc: true, buffer});50 const [chunk] = await once(subprocess.stdout, 'data');51 t.is(chunk.toString(), '.');
8 unmodified lines
60test.serial('Does not buffer initial message to current process, buffer false', testNoBufferInitial, false);61test.serial('Does not buffer initial message to current process, buffer true', testNoBufferInitial, true);6263const testReplay = async (t, buffer) => {37 const subprocess = execa('ipc-replay.js', {ipc: true, buffer, ipcInput: foobarString});64 const subprocess = execa('ipc-replay.js', {buffer, ipcInput: foobarString});65 t.is(await subprocess.getOneMessage(), foobarString);66 await subprocess.sendMessage('.');67 await setTimeout(2e3);68 await subprocess.sendMessage(foobarString);
19 unmodified lines
modified:test/ipc/reference.js+1 added-1 removed
25 unmodified lines
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});30 const {ipcOutput, stdout} = await execa('ipc-process-send-get.js', {ipcInput: 0});31 t.deepEqual(ipcOutput, [foobarString]);32 t.is(stdout, '.');33});34
87 unmodified lines
added:test/ipc/strict.js+222 added
1import {once} from 'node:events';2import test from 'ava';3import {execa} from '../../index.js';4import {setFixtureDirectory} from '../helpers/fixtures-directory.js';5import {foobarString} from '../helpers/input.js';6import {assertMaxListeners} from '../helpers/listeners.js';7import {subprocessGetOne, subprocessGetFirst, mockSendIoError} from '../helpers/ipc.js';8import {PARALLEL_COUNT} from '../helpers/parallel.js';910setFixtureDirectory();1112const testStrictSuccessParentOne = async (t, buffer) => {13 const subprocess = execa('ipc-echo.js', {ipc: true, buffer});14 await subprocess.sendMessage(foobarString, {strict: true});15 t.is(await subprocess.getOneMessage(), foobarString);1617 const {ipcOutput} = await subprocess;18 t.deepEqual(ipcOutput, buffer ? [foobarString] : []);19};2021test('subprocess.sendMessage() "strict" succeeds if the subprocess uses exports.getOneMessage(), buffer false', testStrictSuccessParentOne, false);22test('subprocess.sendMessage() "strict" succeeds if the subprocess uses exports.getOneMessage(), buffer true', testStrictSuccessParentOne, true);2324const testStrictSuccessParentEach = async (t, buffer) => {25 const subprocess = execa('ipc-iterate.js', {ipc: true, buffer});26 await subprocess.sendMessage('.', {strict: true});27 t.is(await subprocess.getOneMessage(), '.');28 await subprocess.sendMessage(foobarString);2930 const {ipcOutput} = await subprocess;31 t.deepEqual(ipcOutput, buffer ? ['.'] : []);32};3334test('subprocess.sendMessage() "strict" succeeds if the subprocess uses exports.getEachMessage(), buffer false', testStrictSuccessParentEach, false);35test('subprocess.sendMessage() "strict" succeeds if the subprocess uses exports.getEachMessage(), buffer true', testStrictSuccessParentEach, true);3637const testStrictMissingParent = async (t, buffer) => {38 const subprocess = execa('ipc-echo-twice.js', {ipcInput: foobarString, buffer});39 const promise = subprocess.getOneMessage();40 const secondPromise = subprocess.sendMessage(foobarString, {strict: true});41 const {message} = await t.throwsAsync(subprocess.sendMessage(foobarString, {strict: true}));42 t.is(message, 'subprocess.sendMessage() failed: the subprocess is not listening to incoming messages.');43 t.is(await promise, foobarString);44 await secondPromise;4546 const {ipcOutput} = await subprocess;47 t.deepEqual(ipcOutput, buffer ? [foobarString, foobarString] : []);48};4950test('subprocess.sendMessage() "strict" fails if the subprocess is not listening, buffer false', testStrictMissingParent, false);51test('subprocess.sendMessage() "strict" fails if the subprocess is not listening, buffer true', testStrictMissingParent, true);5253const testStrictExit = async (t, buffer) => {54 const subprocess = execa('ipc-send.js', {ipc: true, buffer});55 const {message} = await t.throwsAsync(subprocess.sendMessage(foobarString, {strict: true}));56 t.is(message, 'subprocess.sendMessage() failed: the subprocess exited without listening to incoming messages.');5758 const {ipcOutput} = await subprocess;59 t.deepEqual(ipcOutput, buffer ? [foobarString] : []);60};6162test('subprocess.sendMessage() "strict" fails if the subprocess exits, buffer false', testStrictExit, false);63test('subprocess.sendMessage() "strict" fails if the subprocess exits, buffer true', testStrictExit, true);6465const testStrictSuccessSubprocess = async (t, getMessage, buffer) => {66 const subprocess = execa('ipc-send-strict.js', {ipc: true, buffer});67 t.is(await getMessage(subprocess), foobarString);6869 const {ipcOutput} = await subprocess;70 t.deepEqual(ipcOutput, buffer ? [foobarString] : []);71};7273test('exports.sendMessage() "strict" succeeds if the current process uses subprocess.getOneMessage(), buffer false', testStrictSuccessSubprocess, subprocessGetOne, false);74test('exports.sendMessage() "strict" succeeds if the current process uses subprocess.getOneMessage(), buffer true', testStrictSuccessSubprocess, subprocessGetOne, true);75test('exports.sendMessage() "strict" succeeds if the current process uses subprocess.getEachMessage(), buffer false', testStrictSuccessSubprocess, subprocessGetFirst, false);76test('exports.sendMessage() "strict" succeeds if the current process uses subprocess.getEachMessage(), buffer true', testStrictSuccessSubprocess, subprocessGetFirst, true);7778test('exports.sendMessage() "strict" succeeds if the current process uses result.ipcOutput', async t => {79 const {ipcOutput} = await execa('ipc-send-strict.js', {ipc: true});80 t.deepEqual(ipcOutput, [foobarString]);81});8283test('exports.sendMessage() "strict" fails if the current process is not listening, buffer false', async t => {84 const {exitCode, isTerminated, stderr, ipcOutput} = await t.throwsAsync(execa('ipc-send-strict.js', {ipc: true, buffer: {ipc: false}}));85 t.is(exitCode, 1);86 t.false(isTerminated);87 t.true(stderr.includes('Error: sendMessage() failed: the parent process is not listening to incoming messages.'));88 t.deepEqual(ipcOutput, []);89});9091test.serial('Multiple subprocess.sendMessage() "strict" at once', async t => {92 const checkMaxListeners = assertMaxListeners(t);9394 const subprocess = execa('ipc-iterate.js', {ipc: true});95 const messages = Array.from({length: PARALLEL_COUNT}, (_, index) => index);96 await Promise.all(messages.map(message => subprocess.sendMessage(message, {strict: true})));97 await subprocess.sendMessage(foobarString);9899 const {ipcOutput} = await subprocess;100 t.deepEqual(ipcOutput, messages);101102 checkMaxListeners();103});104105test('subprocess.sendMessage() "strict" fails if the subprocess uses once()', async t => {106 const subprocess = execa('ipc-once-message.js', {ipc: true});107 const {message} = await t.throwsAsync(subprocess.sendMessage(foobarString, {strict: true}));108 t.is(message, 'subprocess.sendMessage() failed: the subprocess exited without listening to incoming messages.');109110 const {ipcOutput} = await subprocess;111 t.deepEqual(ipcOutput, ['.']);112});113114test('exports.sendMessage() "strict" fails if the current process uses once() and buffer false', async t => {115 const subprocess = execa('ipc-send-strict.js', {ipc: true, buffer: {ipc: false}});116 const [message] = await once(subprocess, 'message');117 t.deepEqual(message, {id: 0n, type: 'execa:ipc:request', message: foobarString});118119 const {exitCode, isTerminated, stderr, ipcOutput} = await t.throwsAsync(subprocess);120 t.is(exitCode, 1);121 t.false(isTerminated);122 t.true(stderr.includes('Error: sendMessage() failed: the parent process is not listening to incoming messages.'));123 t.deepEqual(ipcOutput, []);124});125126test('subprocess.sendMessage() "strict" failure disconnects', async t => {127 const subprocess = execa('ipc-echo-twice-wait.js', {ipcInput: foobarString});128 const promise = subprocess.getOneMessage();129 const secondPromise = subprocess.sendMessage(foobarString, {strict: true});130 const {message} = await t.throwsAsync(subprocess.sendMessage(foobarString, {strict: true}));131 t.is(message, 'subprocess.sendMessage() failed: the subprocess is not listening to incoming messages.');132 t.is(await promise, foobarString);133 await secondPromise;134135 const {exitCode, isTerminated, stderr, ipcOutput} = await t.throwsAsync(subprocess);136 t.is(exitCode, 1);137 t.false(isTerminated);138 t.true(stderr.includes('Error: sendMessage() cannot be used: the parent process has already exited or disconnected.'));139 t.deepEqual(ipcOutput, [foobarString, foobarString]);140});141142test('exports.sendMessage() "strict" failure disconnects', async t => {143 const {exitCode, isTerminated, stderr, ipcOutput} = await t.throwsAsync(execa('ipc-send-strict-catch.js', {ipc: true, buffer: {ipc: false}}));144 t.is(exitCode, 1);145 t.false(isTerminated);146 t.true(stderr.includes('Error: sendMessage() cannot be used: the parent process has already exited or disconnected.'));147 t.deepEqual(ipcOutput, []);148});149150const testIoErrorParent = async (t, getMessage) => {151 const subprocess = execa('ipc-send-strict.js', {ipc: true});152 const cause = mockSendIoError(subprocess);153 const error = await t.throwsAsync(getMessage(subprocess));154 t.true(error.message.includes('subprocess.sendMessage() failed when sending an acknowledgment response to the subprocess.'));155 t.is(getMessage === subprocessGetOne ? error.cause : error.cause.cause, cause);156157 const {exitCode, isTerminated, stderr, ipcOutput} = await t.throwsAsync(subprocess);158 t.is(exitCode, 1);159 t.false(isTerminated);160 t.true(stderr.includes('Error: sendMessage() failed: the parent process exited without listening to incoming messages.'));161 t.deepEqual(ipcOutput, []);162};163164test('subprocess.getOneMessage() acknowledgment I/O error', testIoErrorParent, subprocessGetOne);165test('subprocess.getEachMessage() acknowledgment I/O error', testIoErrorParent, subprocessGetFirst);166167const testIoErrorSubprocess = async (t, fixtureName) => {168 const subprocess = execa(fixtureName, {ipc: true});169 const {message} = await t.throwsAsync(subprocess.sendMessage(foobarString, {strict: true}));170 t.is(message, 'subprocess.sendMessage() failed: the subprocess exited without listening to incoming messages.');171172 const {exitCode, isTerminated, stdout, stderr, ipcOutput} = await t.throwsAsync(subprocess);173 t.is(exitCode, 1);174 t.false(isTerminated);175 t.is(stdout, '');176 t.true(stderr.includes('Error: sendMessage() failed when sending an acknowledgment response to the parent process.'));177 t.true(stderr.includes(`Error: ${foobarString}`));178 t.deepEqual(ipcOutput, []);179};180181test('exports.getOneMessage() acknowledgment I/O error', testIoErrorSubprocess, 'ipc-get-io-error.js');182test('exports.getEachMessage() acknowledgment I/O error', testIoErrorSubprocess, 'ipc-iterate-io-error.js');183184test('Opposite sendMessage() "strict", buffer true', async t => {185 const subprocess = execa('ipc-send-strict-get.js', {ipc: true});186 await subprocess.sendMessage(foobarString, {strict: true});187188 const {ipcOutput} = await subprocess;189 t.deepEqual(ipcOutput, [foobarString, foobarString]);190});191192test('Opposite sendMessage() "strict", current process listening, buffer false', async t => {193 const subprocess = execa('ipc-send-strict-get.js', {ipc: true, buffer: false});194 const [message] = await Promise.all([195 subprocess.getOneMessage(),196 subprocess.sendMessage(foobarString, {strict: true}),197 ]);198 t.is(message, foobarString);199 t.is(await subprocess.getOneMessage(), foobarString);200201 const {ipcOutput} = await subprocess;202 t.deepEqual(ipcOutput, []);203});204205test('Opposite sendMessage() "strict", subprocess listening, buffer false', async t => {206 const subprocess = execa('ipc-send-strict-listen.js', {ipc: true, buffer: false});207 await subprocess.sendMessage(foobarString, {strict: true});208 t.is(await subprocess.getOneMessage(), foobarString);209210 const {ipcOutput} = await subprocess;211 t.deepEqual(ipcOutput, []);212});213214test('Opposite sendMessage() "strict", not listening, buffer false', async t => {215 const subprocess = execa('ipc-send-strict-get.js', {ipc: true, timeout: 1e3, buffer: false});216 const {message} = await t.throwsAsync(subprocess.sendMessage(foobarString, {strict: true}));217 t.is(message, 'subprocess.sendMessage() failed: the subprocess exited without listening to incoming messages.');218219 const {timedOut, ipcOutput} = await t.throwsAsync(subprocess);220 t.true(timedOut);221 t.deepEqual(ipcOutput, []);222});
modified:test-d/ipc/send.test-d.ts+13 added
28 unmodified lines
29expectType<undefined>(execa('test', {}).sendMessage);30expectType<undefined>(execa('test', {ipc: false}).sendMessage);31expectType<undefined>(execa('test', {ipcInput: undefined}).sendMessage);32expectType<undefined>(execa('test', {ipc: false, ipcInput: ''}).sendMessage);3334await subprocess.sendMessage('', {} as const);35await sendMessage('', {} as const);36await subprocess.sendMessage('', {strict: true} as const);37await sendMessage('', {strict: true} as const);38expectError(await subprocess.sendMessage('', true));39expectError(await sendMessage('', true));40expectError(await subprocess.sendMessage('', {strict: 'true'}));41expectError(await sendMessage('', {strict: 'true'}));42expectError(await subprocess.sendMessage('', {unknown: true}));43expectError(await sendMessage('', {unknown: true}));44expectError(await subprocess.sendMessage('', {strict: true}, {}));45expectError(await sendMessage('', {strict: true}, {}));
modified:types/ipc.d.ts+20 added-8 removed
25 unmodified lines
26 Serialization extends Options['serialization'] = Options['serialization'],27> = Serialization extends 'json' ? JsonMessage : AdvancedMessage;2829/**30Options to `getOneMessage()` and `subprocess.getOneMessage()`30Options to `sendMessage()` and `subprocess.sendMessage()`31*/32type GetOneMessageOptions<33 Serialization extends Options['serialization'],34> = {32type SendMessageOptions = {33 /**36 Ignore any `message` that returns `false`.34 Throw when the other process is not receiving or listening to messages.3536 @default false37 */38 readonly filter?: (message: Message<Serialization>) => boolean;38 readonly strict?: boolean;39};4041// IPC methods in subprocess42/**43Send a `message` to the parent process.4445This requires the `ipc` option to be `true`. The type of `message` depends on the `serialization` option.46*/47export function sendMessage(message: Message): Promise<void>;47export function sendMessage(message: Message, sendMessageOptions?: SendMessageOptions): Promise<void>;4849/**50Options to `getOneMessage()` and `subprocess.getOneMessage()`51*/52type GetOneMessageOptions<53 Serialization extends Options['serialization'],54> = {55 /**56 Ignore any `message` that returns `false`.57 */58 readonly filter?: (message: Message<Serialization>) => boolean;59};6061/**62Receive a single `message` from the parent process.6364This requires the `ipc` option to be `true`. The type of `message` depends on the `serialization` option.65*/
16 unmodified lines
82 Send a `message` to the subprocess.8384 This requires the `ipc` option to be `true`. The type of `message` depends on the `serialization` option.85 */74 sendMessage(message: Message<Serialization>): Promise<void>;86 sendMessage(message: Message<Serialization>, sendMessageOptions?: SendMessageOptions): Promise<void>;8788 /**89 Receive a single `message` from the subprocess.90
36 unmodified lines