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
Provenance
- Commit
e085b10- Tree
43c2c3d- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
b959030
30 files changed+635 added−46 removed
modified:docs/api.md+21 added-6 removed
90 unmodified lines91 Split a `command` string into an array. For example, `'npm run build'` returns `['npm', 'run', 'build']` and `'argument otherArgument'` returns `['argument', 'otherArgument']`.92 93 [More info.](escaping.md#user-defined-input)94 95-### sendMessage(message)95+### sendMessage(message, sendMessageOptions?)96 97 `message`: [`Message`](ipc.md#message-type)\98+`sendMessageOptions`: [`SendMessageOptions`](#sendmessageoptions)\99 _Returns_: `Promise<void>`100 101 Send a `message` to the parent process.102 103 This requires the [`ipc`](#optionsipc) option to be `true`. The [type](ipc.md#message-type) of `message` depends on the [`serialization`](#optionsserialization) option.104 105 [More info.](ipc.md#exchanging-messages)106 107+#### sendMessageOptions108+109+_Type_: `object`110+111+#### sendMessageOptions.strict112+113+_Type_: `boolean`\114+_Default_: `false`115+116+Throw when the other process is not receiving or listening to messages.117+118+[More info.](ipc.md#ensure-messages-are-received)119+120 ### getOneMessage(getOneMessageOptions?)121 108-_getOneMessageOptions_: [`GetOneMessageOptions`](#getonemessageoptions)\122+`getOneMessageOptions`: [`GetOneMessageOptions`](#getonemessageoptions)\123 _Returns_: [`Promise<Message>`](ipc.md#message-type)124 125 Receive a single `message` from the parent process.126 147 unmodified lines274 This is `undefined` if the subprocess failed to spawn.275 276 [More info.](termination.md#inter-process-termination)277 264-### subprocess.sendMessage(message)278+### subprocess.sendMessage(message, sendMessageOptions)279 280 `message`: [`Message`](ipc.md#message-type)\281+`sendMessageOptions`: [`SendMessageOptions`](#sendmessageoptions)\282 _Returns_: `Promise<void>`283 284 Send a `message` to the subprocess.285 2 unmodified lines288 [More info.](ipc.md#exchanging-messages)289 290 ### subprocess.getOneMessage(getOneMessageOptions?)291 277-_getOneMessageOptions_: [`GetOneMessageOptions`](#getonemessageoptions)\292+`getOneMessageOptions`: [`GetOneMessageOptions`](#getonemessageoptions)\293 _Returns_: [`Promise<Message>`](ipc.md#message-type)294 295 Receive a single `message` from the subprocess.296 202 unmodified lines499 ### result.ipcOutput500 501 _Type_: [`Message[]`](ipc.md#message-type)502 488-All the messages [sent by the subprocess](#sendmessagemessage) to the current process.503+All the messages [sent by the subprocess](#sendmessagemessage-sendmessageoptions) to the current process.504 505 This is empty unless the [`ipc`](#optionsipc) option is `true`. Also, this is empty if the [`buffer`](#optionsbuffer) option is `false`.506 507 [More info.](ipc.md#retrieve-all-messages)420 unmodified lines928 929 _Type:_ `boolean`\930 _Default:_ `true` if either the [`node`](#optionsnode) option or the [`ipcInput`](#optionsipcinput) is set, `false` otherwise931 917-Enables exchanging messages with the subprocess using [`subprocess.sendMessage(message)`](#subprocesssendmessagemessage), [`subprocess.getOneMessage()`](#subprocessgetonemessagegetonemessageoptions) and [`subprocess.getEachMessage()`](#subprocessgeteachmessage).932+Enables exchanging messages with the subprocess using [`subprocess.sendMessage(message)`](#subprocesssendmessagemessage-sendmessageoptions), [`subprocess.getOneMessage()`](#subprocessgetonemessagegetonemessageoptions) and [`subprocess.getEachMessage()`](#subprocessgeteachmessage).933 934 The subprocess must be a Node.js file.935 936 [More info.](ipc.md)199 unmodified linesmodified:docs/execution.md+1 added-1 removed
133 unmodified linesExpand all1341351361371381381391401411424 unmodified lines133 unmodified linesExpand all- The [`stdin`](api.md#optionsstdin), [`stdout`](api.md#optionsstdout), [`stderr`](api.md#optionsstderr) and [`stdio`](api.md#optionsstdio) options cannot be [`'overlapped'`](api.md#optionsstdout), an [async iterable](lines.md#progressive-splitting), an async [transform](transform.md), a [`Duplex`](transform.md#duplextransform-streams), nor a [web stream](streams.md#web-streams). Node.js streams can be passed but only if either they [have a file descriptor](streams.md#file-descriptors), or the [`input`](api.md#optionsinput) option is used.- Signal termination: [`subprocess.kill()`](api.md#subprocesskillerror), [`subprocess.pid`](api.md#subprocesspid), [`cleanup`](api.md#optionscleanup) option, [`cancelSignal`](api.md#optionscancelsignal) option, [`forceKillAfterDelay`](api.md#optionsforcekillafterdelay) option.- Piping multiple subprocesses: [`subprocess.pipe()`](api.md#subprocesspipefile-arguments-options).- [`subprocess.iterable()`](lines.md#progressive-splitting).- [IPC](ipc.md): [`sendMessage()`](api.md#sendmessagemessage), [`getOneMessage()`](api.md#getonemessagegetonemessageoptions), [`getEachMessage()`](api.md#geteachmessage), [`result.ipcOutput`](output.md#any-output-type), [`ipc`](api.md#optionsipc) option, [`serialization`](api.md#optionsserialization) option, [`ipcInput`](input.md#any-input-type) option.- [IPC](ipc.md): [`sendMessage()`](api.md#sendmessagemessage-sendmessageoptions), [`getOneMessage()`](api.md#getonemessagegetonemessageoptions), [`getEachMessage()`](api.md#geteachmessage), [`result.ipcOutput`](output.md#any-output-type), [`ipc`](api.md#optionsipc) option, [`serialization`](api.md#optionsserialization) option, [`ipcInput`](input.md#any-input-type) option.- [`result.all`](api.md#resultall) is not interleaved.- [`detached`](api.md#optionsdetached) option.- The [`maxBuffer`](api.md#optionsmaxbuffer) option is always measured in bytes, not in characters, [lines](api.md#optionslines) nor [objects](transform.md#object-mode). Also, it ignores transforms and the [`encoding`](api.md#optionsencoding) option.
4 unmodified linesmodified:docs/ipc.md+38 added-3 removed
10 unmodified lines11 When the [`ipc`](api.md#optionsipc) option is `true`, the current process and subprocess can exchange messages. This only works if the subprocess is a [Node.js file](node.md).12 13 The `ipc` option defaults to `true` when using [`execaNode()`](node.md#run-nodejs-files) or the [`node`](node.md#run-nodejs-files) option.14 15-The current process sends messages with [`subprocess.sendMessage(message)`](api.md#subprocesssendmessagemessage) and receives them with [`subprocess.getOneMessage()`](api.md#subprocessgetonemessagegetonemessageoptions).15+The current process sends messages with [`subprocess.sendMessage(message)`](api.md#subprocesssendmessagemessage-sendmessageoptions) and receives them with [`subprocess.getOneMessage()`](api.md#subprocessgetonemessagegetonemessageoptions).16 17-The subprocess uses [`sendMessage(message)`](api.md#sendmessagemessage) and [`getOneMessage()`](api.md#getonemessagegetonemessageoptions). Those are the same methods, but imported directly from the `'execa'` module.17+The 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.18 19 ```js20 // parent.js21 import {execaNode} from 'execa';1 unmodified line23 const subprocess = execaNode`child.js`;24 await subprocess.sendMessage('Hello from parent');25 const message = await subprocess.getOneMessage();26 console.log(message); // 'Hello from child'27+await subprocess;28 ```29 30 ```js31 // child.js59 unmodified lines91 }92 }93 ```94 95+## Ensure messages are received96+97+When 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.98+99+If 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.100+101+```js102+// main.js103+import {execaNode} from 'execa';104+105+const subprocess = execaNode`build.js`;106+// This `build` message is received107+await subprocess.sendMessage('build', {strict: true});108+// This `lint` message is not received, so it throws109+await subprocess.sendMessage('lint', {strict: true});110+await subprocess;111+```112+113+```js114+// build.js115+import {getOneMessage} from 'execa';116+117+// Receives the 'build' message118+const task = await getOneMessage();119+// The `lint` message is sent while `runTask()` is ongoing120+// Therefore the `lint` message is discarded121+await runTask(task);122+123+// Does not receive the `lint` message124+// Without `strict`, this would wait forever125+const secondTask = await getOneMessage();126+await runTask(secondTask);127+```128+129 ## Retrieve all messages130 131 The [`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 lines178 179 ```js180 import {execaNode} from 'execa';181 147-const subprocess = execaNode({serialization: 'json'})`child.js`;182+await execaNode({serialization: 'json'})`child.js`;183 ```184 185 ## Messages order186 23 unmodified linesmodified:docs/typescript.md+1 added-1 removed
6 unmodified lines7 # 🤓 TypeScript8 9 ## Available types10 11-The following types can be imported: [`ResultPromise`](api.md#return-value), [`Subprocess`](api.md#subprocess), [`Result`](api.md#result), [`ExecaError`](api.md#execaerror), [`Options`](api.md#options), [`StdinOption`](api.md#optionsstdin), [`StdoutStderrOption`](api.md#optionsstdout), [`TemplateExpression`](api.md#execacommand) and [`Message`](api.md#subprocesssendmessagemessage).11+The following types can be imported: [`ResultPromise`](api.md#return-value), [`Subprocess`](api.md#subprocess), [`Result`](api.md#result), [`ExecaError`](api.md#execaerror), [`Options`](api.md#options), [`StdinOption`](api.md#optionsstdin), [`StdoutStderrOption`](api.md#optionsstdout), [`TemplateExpression`](api.md#execacommand) and [`Message`](api.md#subprocesssendmessagemessage-sendmessageoptions).12 13 ```ts14 import {15 execa,156 unmodified linesmodified:lib/ipc/forward.js+7 added-1 removed
28 unmodified lines29 // 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#L72132 const 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 linesmodified:lib/ipc/get-each.js+28 added-3 removed
1 import {once, on} from 'node:events';2-import {validateIpcMethod, disconnect} from './validation.js';2+import {validateIpcMethod, disconnect, getStrictResponseError} from './validation.js';3 import {getIpcEmitter, isConnected} from './forward.js';4 import {addReference, removeReference} from './reference.js';5 6 // Like `[sub]process.on('message')` but promise-based16 unmodified lines23 24 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 };45 46 const stopOnDisconnect = async (anyProcess, ipcEmitter, controller) => {2 unmodified lines49 controller.abort();50 } catch {}51 };52 45-const iterateOnMessages = async function * ({anyProcess, channel, ipcEmitter, isSubprocess, shouldAwait, controller}) {53+const 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+};60+61+const 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);72 73 if (!isSubprocess) {4 unmodified lines78 await anyProcess;79 }80 }81 };82+83+const throwIfStrictError = ({error}) => {84+ if (error) {85+ throw error;86+ }87+};modified:lib/ipc/get-one.js+12 added-1 removed
1 import {once, on} from 'node:events';2-import {validateIpcMethod, throwOnEarlyDisconnect, disconnect} from './validation.js';2+import {3+ validateIpcMethod,4+ throwOnEarlyDisconnect,5+ disconnect,6+ getStrictResponseError,7+} from './validation.js';8 import {getIpcEmitter, isConnected} from './forward.js';9 import {addReference, removeReference} from './reference.js';10 11 // Like `[sub]process.once('message')` but promise-based20 unmodified lines32 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 lines60 const throwOnDisconnect = async (ipcEmitter, isSubprocess, {signal}) => {61 await once(ipcEmitter, 'disconnect', {signal});62 throwOnEarlyDisconnect(isSubprocess);63 };64+65+const 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
1 import {once} from 'node:events';2 import {scheduler} from 'node:timers/promises';3 import {waitForOutgoingMessages} from './outgoing.js';4 import {redoAddedReferences} from './reference.js';5+import {handleStrictRequest, handleStrictResponse} from './strict.js';6 7 // 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 lines21 // - 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.24-export const onMessage = async (anyProcess, ipcEmitter, message) => {25+export const onMessage = async ({anyProcess, channel, isSubprocess, ipcEmitter}, wrappedMessage) => {26+ if (handleStrictResponse(wrappedMessage)) {27+ return;28+ }29+30 if (!INCOMING_MESSAGES.has(anyProcess)) {31 INCOMING_MESSAGES.set(anyProcess, []);32 }33 34 const incomingMessages = INCOMING_MESSAGES.get(anyProcess);30- incomingMessages.push(message);35+ incomingMessages.push(wrappedMessage);36 37 if (incomingMessages.length > 1) {38 return;39 }40 41 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();46+47+ // 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+ });55+56+ incomingMessages.shift();41- ipcEmitter.emit('message', incomingMessages.shift());57+ ipcEmitter.emit('message', message);58+ ipcEmitter.emit('message:done');59 }60 };61 45-const INCOMING_MESSAGES = new WeakMap();46-62 // If the `message` event is currently debounced, the `disconnect` event must wait for it48-export const onDisconnect = async ({anyProcess, channel, ipcEmitter, boundOnMessage}) => {63+export 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 }69 70 anyProcess.removeListener('message', boundOnMessage);56- redoAddedReferences(channel);71+ redoAddedReferences(channel, isSubprocess);72 ipcEmitter.connected = false;73 ipcEmitter.emit('disconnect');74 };75+76+const INCOMING_MESSAGES = new WeakMap();modified:lib/ipc/methods.js+1 added
13 unmodified lines14 // Retrieve the `ipc` shared by both the current process and the subprocess15 const 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 linesmodified:lib/ipc/outgoing.js+14 added-3 removed
1 import {createDeferred} from '../utils/deferred.js';2+import {SUBPROCESS_OPTIONS} from '../arguments/fd-options.js';3 4 // 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 lines19 outgoingMessages.delete(onMessageSent);20 onMessageSent.resolve();21 };22 22-// Await while `sendMessage()` is ongoing23-export const waitForOutgoingMessages = async anyProcess => {24- while (OUTGOING_MESSAGES.get(anyProcess)?.size > 0) {23+// Await while `sendMessage()` is ongoing, unless there is already a `message` listener24+export 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 };30 31 const OUTGOING_MESSAGES = new WeakMap();32+33+// Whether any `message` listener is setup34+export const hasMessageListeners = (anyProcess, ipcEmitter) => ipcEmitter.listenerCount('message') > getMinListenerCount(anyProcess);35+36+// 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.38+const 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 lines5 handleSerializationError,6 disconnect,7 } from './validation.js';8 import {startSendMessage, endSendMessage} from './outgoing.js';9+import {handleSendStrict, waitForStrictResponse} from './strict.js';10 11 // 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.14-export const sendMessage = ({anyProcess, isSubprocess, ipc}, message) => {15+export const sendMessage = ({anyProcess, channel, isSubprocess, ipc}, message, {strict = false} = {}) => {16 validateIpcMethod({17 methodName: 'sendMessage',18 isSubprocess,19 ipc,20 isConnected: anyProcess.connected,21 });22 22- return sendMessageAsync({anyProcess, isSubprocess, message});23+ return sendMessageAsync({24+ anyProcess,25+ channel,26+ isSubprocess,27+ message,28+ strict,29+ });30 };31 25-const sendMessageAsync = async ({anyProcess, isSubprocess, message}) => {32+const 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+ });42+43 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 linesadded:lib/ipc/strict.js+89 added
1+import {once} from 'node:events';2+import {createDeferred} from '../utils/deferred.js';3+import {incrementMaxListeners} from '../utils/max-listeners.js';4+import {sendMessage} from './send.js';5+import {throwOnMissingStrict, throwOnStrictDisconnect} from './validation.js';6+import {getIpcEmitter} from './forward.js';7+import {hasMessageListeners} from './outgoing.js';8+9+// When using the `strict` option, wrap the message with metadata during `sendMessage()`10+export const handleSendStrict = ({anyProcess, channel, isSubprocess, message, strict}) => {11+ if (!strict) {12+ return message;13+ }14+15+ getIpcEmitter(anyProcess, channel, isSubprocess);16+ return {id: count++, type: REQUEST_TYPE, message};17+};18+19+let count = 0n;20+21+// The other process then sends the acknowledgment back as a response22+export const handleStrictRequest = async ({wrappedMessage, anyProcess, channel, isSubprocess, ipcEmitter}) => {23+ if (wrappedMessage?.type !== REQUEST_TYPE) {24+ return wrappedMessage;25+ }26+27+ const {id, message} = wrappedMessage;28+ const response = {id, type: RESPONSE_TYPE, message: hasMessageListeners(anyProcess, ipcEmitter)};29+30+ 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+ }40+41+ return message;42+};43+44+// Reception of the acknowledgment response45+export const handleStrictResponse = wrappedMessage => {46+ if (wrappedMessage?.type !== RESPONSE_TYPE) {47+ return false;48+ }49+50+ const {id, message: hasListeners} = wrappedMessage;51+ STRICT_RESPONSES[id].resolve(hasListeners);52+ return true;53+};54+55+// Wait for the other process to receive the message from `sendMessage()`56+export const waitForStrictResponse = async (wrappedMessage, anyProcess, isSubprocess) => {57+ if (wrappedMessage?.type !== REQUEST_TYPE) {58+ return;59+ }60+61+ const deferred = createDeferred();62+ STRICT_RESPONSES[wrappedMessage.id] = deferred;63+64+ try {65+ const controller = new AbortController();66+ const hasListeners = await Promise.race([67+ deferred,68+ throwOnDisconnect(anyProcess, isSubprocess, controller),69+ ]);70+ controller.abort();71+72+ if (!hasListeners) {73+ throwOnMissingStrict(isSubprocess);74+ }75+ } finally {76+ delete STRICT_RESPONSES[wrappedMessage.id];77+ }78+};79+80+const STRICT_RESPONSES = {};81+82+const throwOnDisconnect = async (anyProcess, isSubprocess, {signal}) => {83+ incrementMaxListeners(anyProcess, 1, signal);84+ await once(anyProcess, 'disconnect', {signal});85+ throwOnStrictDisconnect(isSubprocess);86+};87+88+const REQUEST_TYPE = 'execa:ipc:request';89+const RESPONSE_TYPE = 'execa:ipc:response';modified:lib/ipc/validation.js+13 added
22 unmodified lines23 export const throwOnEarlyDisconnect = isSubprocess => {24 throw new Error(`${getNamespaceName(isSubprocess)}getOneMessage() could not complete: the ${getOtherProcessName(isSubprocess)} exited or disconnected.`);25 };26 27+// When the other process used `strict` but the current process had I/O error calling `sendMessage()` for the response28+export const getStrictResponseError = (error, isSubprocess) => new Error(`${getNamespaceName(isSubprocess)}sendMessage() failed when sending an acknowledgment response to the ${getOtherProcessName(isSubprocess)}.`, {cause: error});29+30+// When using `strict` but the other process was not listening for messages31+export const throwOnMissingStrict = isSubprocess => {32+ throw new Error(`${getNamespaceName(isSubprocess)}sendMessage() failed: the ${getOtherProcessName(isSubprocess)} is not listening to incoming messages.`);33+};34+35+// When using `strict` but the other process disconnected before receiving the message36+export const throwOnStrictDisconnect = isSubprocess => {37+ throw new Error(`${getNamespaceName(isSubprocess)}sendMessage() failed: the ${getOtherProcessName(isSubprocess)} exited without listening to incoming messages.`);38+};39+40 const getNamespaceName = isSubprocess => isSubprocess ? '' : 'subprocess.';41 42 const getOtherProcessName = isSubprocess => isSubprocess ? 'parent process' : 'subprocess';43 44 unmodified linesadded:test/fixtures/ipc-echo-twice-wait.js+10 added
1+#!/usr/bin/env node2+import {setTimeout} from 'node:timers/promises';3+import {sendMessage, getOneMessage} from '../../index.js';4+5+const message = await getOneMessage();6+await sendMessage(message);7+const secondMessage = await getOneMessage();8+await sendMessage(secondMessage);9+await setTimeout(1e3);10+await sendMessage('.');added:test/fixtures/ipc-get-io-error.js+7 added
1+#!/usr/bin/env node2+import process from 'node:process';3+import {getOneMessage} from '../../index.js';4+import {mockSendIoError} from '../helpers/ipc.js';5+6+mockSendIoError(process);7+console.log(await getOneMessage());added:test/fixtures/ipc-iterate-io-error.js+9 added
1+#!/usr/bin/env node2+import process from 'node:process';3+import {getEachMessage} from '../../index.js';4+import {mockSendIoError} from '../helpers/ipc.js';5+6+mockSendIoError(process);7+for await (const message of getEachMessage()) {8+ console.log(message);9+}added:test/fixtures/ipc-send-echo-strict.js+7 added
1+#!/usr/bin/env node2+import {setTimeout} from 'node:timers/promises';3+import {sendMessage, getOneMessage} from '../../index.js';4+5+await sendMessage('.', {strict: true});6+await setTimeout(10);7+await sendMessage(await getOneMessage());added:test/fixtures/ipc-send-echo-wait.js+7 added
1+#!/usr/bin/env node2+import {setTimeout} from 'node:timers/promises';3+import {sendMessage, getOneMessage} from '../../index.js';4+5+await sendMessage('.');6+await setTimeout(1e3);7+await sendMessage(await getOneMessage());added:test/fixtures/ipc-send-strict-catch.js+9 added
1+#!/usr/bin/env node2+import {sendMessage} from '../../index.js';3+import {foobarString} from '../helpers/input.js';4+5+try {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 node2+import {sendMessage, getOneMessage} from '../../index.js';3+import {foobarString} from '../helpers/input.js';4+5+await sendMessage(foobarString, {strict: true});6+await sendMessage(await getOneMessage());added:test/fixtures/ipc-send-strict-listen.js+9 added
1+#!/usr/bin/env node2+import {sendMessage, getOneMessage} from '../../index.js';3+import {foobarString} from '../helpers/input.js';4+5+const [message] = await Promise.race([6+ getOneMessage(),7+ sendMessage(foobarString, {strict: true}),8+]);9+await sendMessage(message);added:test/fixtures/ipc-send-strict.js+5 added
1+#!/usr/bin/env node2+import {sendMessage} from '../../index.js';3+import {foobarString} from '../helpers/input.js';4+5+await sendMessage(foobarString, {strict: true});modified:test/ipc/get-one.js+1 added-1 removed
40 unmodified lines41 t.deepEqual(ipcOutput, [foobarString]);42 });43 44 test('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 linesmodified:test/ipc/ipc-input.js+5 added
44 unmodified lines45 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 });49+50+test('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 lines35 test('Multiple parallel subprocess.sendMessage() + subprocess.getEachMessage(), buffer false', testSendHoldParent, subprocessGetFirst, false, undefined);36 test('Multiple parallel subprocess.sendMessage() + subprocess.getEachMessage(), buffer true', testSendHoldParent, subprocessGetFirst, true, undefined);37 38 const testSendHoldSubprocess = async (t, filter, isGetEach) => {39- const {ipcOutput} = await execa('ipc-iterate-back.js', [`${filter}`, `${isGetEach}`], {ipc: true, ipcInput: 0});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 lines77 test('Multiple serial subprocess.sendMessage() + subprocess.getEachMessage(), buffer false', testSendHoldParentSerial, subprocessGetFirst, false, undefined);78 test('Multiple serial subprocess.sendMessage() + subprocess.getEachMessage(), buffer true', testSendHoldParentSerial, subprocessGetFirst, true, undefined);79 80 const testSendHoldSubprocessSerial = async (t, filter, isGetEach) => {81- const {ipcOutput} = await execa('ipc-iterate-back-serial.js', [`${filter}`, `${isGetEach}`], {ipc: true, ipcInput: 0, stdout: 'inherit'});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 linesmodified:test/ipc/pending.js+29 added-2 removed
6 unmodified lines7 8 setFixtureDirectory();9 10 const 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);13 14 const {ipcOutput} = await subprocess;15 t.deepEqual(ipcOutput, buffer ? [foobarString] : []);1 unmodified line17 18 test('Buffers initial message to subprocess, buffer false', testBufferInitial, false);19 test('Buffers initial message to subprocess, buffer true', testBufferInitial, true);20 21+const 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);25+26+ const {ipcOutput} = await subprocess;27+ t.deepEqual(ipcOutput, buffer ? ['.', foobarString] : []);28+};29+30+test('sendMessage() does not empty the initial message buffering, buffer false', testBufferInitialSend, false);31+test('sendMessage() does not empty the initial message buffering, buffer true', testBufferInitialSend, true);32+33+const 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, '..');40+41+ const {ipcOutput} = await subprocess;42+ t.deepEqual(ipcOutput, buffer ? ['.', '..'] : []);43+};44+45+test('sendMessage() with "strict" empties the initial message buffering, buffer false', testBufferInitialStrict, false);46+test('sendMessage() with "strict" empties the initial message buffering, buffer true', testBufferInitialStrict, true);47+48 const 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 lines60 test.serial('Does not buffer initial message to current process, buffer false', testNoBufferInitial, false);61 test.serial('Does not buffer initial message to current process, buffer true', testNoBufferInitial, true);62 63 const 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 linesmodified:test/ipc/reference.js+1 added-1 removed
25 unmodified lines26 t.is(stdout, '.');27 });28 29 test('process.send() keeps the subprocess alive, after getOneMessage()', async t => {30- const {ipcOutput, stdout} = await execa('ipc-process-send-get.js', {ipc: true, ipcInput: 0});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 linesadded:test/ipc/strict.js+222 added
1+import {once} from 'node:events';2+import test from 'ava';3+import {execa} from '../../index.js';4+import {setFixtureDirectory} from '../helpers/fixtures-directory.js';5+import {foobarString} from '../helpers/input.js';6+import {assertMaxListeners} from '../helpers/listeners.js';7+import {subprocessGetOne, subprocessGetFirst, mockSendIoError} from '../helpers/ipc.js';8+import {PARALLEL_COUNT} from '../helpers/parallel.js';9+10+setFixtureDirectory();11+12+const 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);16+17+ const {ipcOutput} = await subprocess;18+ t.deepEqual(ipcOutput, buffer ? [foobarString] : []);19+};20+21+test('subprocess.sendMessage() "strict" succeeds if the subprocess uses exports.getOneMessage(), buffer false', testStrictSuccessParentOne, false);22+test('subprocess.sendMessage() "strict" succeeds if the subprocess uses exports.getOneMessage(), buffer true', testStrictSuccessParentOne, true);23+24+const 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);29+30+ const {ipcOutput} = await subprocess;31+ t.deepEqual(ipcOutput, buffer ? ['.'] : []);32+};33+34+test('subprocess.sendMessage() "strict" succeeds if the subprocess uses exports.getEachMessage(), buffer false', testStrictSuccessParentEach, false);35+test('subprocess.sendMessage() "strict" succeeds if the subprocess uses exports.getEachMessage(), buffer true', testStrictSuccessParentEach, true);36+37+const 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;45+46+ const {ipcOutput} = await subprocess;47+ t.deepEqual(ipcOutput, buffer ? [foobarString, foobarString] : []);48+};49+50+test('subprocess.sendMessage() "strict" fails if the subprocess is not listening, buffer false', testStrictMissingParent, false);51+test('subprocess.sendMessage() "strict" fails if the subprocess is not listening, buffer true', testStrictMissingParent, true);52+53+const 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.');57+58+ const {ipcOutput} = await subprocess;59+ t.deepEqual(ipcOutput, buffer ? [foobarString] : []);60+};61+62+test('subprocess.sendMessage() "strict" fails if the subprocess exits, buffer false', testStrictExit, false);63+test('subprocess.sendMessage() "strict" fails if the subprocess exits, buffer true', testStrictExit, true);64+65+const testStrictSuccessSubprocess = async (t, getMessage, buffer) => {66+ const subprocess = execa('ipc-send-strict.js', {ipc: true, buffer});67+ t.is(await getMessage(subprocess), foobarString);68+69+ const {ipcOutput} = await subprocess;70+ t.deepEqual(ipcOutput, buffer ? [foobarString] : []);71+};72+73+test('exports.sendMessage() "strict" succeeds if the current process uses subprocess.getOneMessage(), buffer false', testStrictSuccessSubprocess, subprocessGetOne, false);74+test('exports.sendMessage() "strict" succeeds if the current process uses subprocess.getOneMessage(), buffer true', testStrictSuccessSubprocess, subprocessGetOne, true);75+test('exports.sendMessage() "strict" succeeds if the current process uses subprocess.getEachMessage(), buffer false', testStrictSuccessSubprocess, subprocessGetFirst, false);76+test('exports.sendMessage() "strict" succeeds if the current process uses subprocess.getEachMessage(), buffer true', testStrictSuccessSubprocess, subprocessGetFirst, true);77+78+test('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+});82+83+test('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+});90+91+test.serial('Multiple subprocess.sendMessage() "strict" at once', async t => {92+ const checkMaxListeners = assertMaxListeners(t);93+94+ 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);98+99+ const {ipcOutput} = await subprocess;100+ t.deepEqual(ipcOutput, messages);101+102+ checkMaxListeners();103+});104+105+test('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.');109+110+ const {ipcOutput} = await subprocess;111+ t.deepEqual(ipcOutput, ['.']);112+});113+114+test('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});118+119+ 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+});125+126+test('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;134+135+ 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+});141+142+test('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+});149+150+const 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);156+157+ 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+};163+164+test('subprocess.getOneMessage() acknowledgment I/O error', testIoErrorParent, subprocessGetOne);165+test('subprocess.getEachMessage() acknowledgment I/O error', testIoErrorParent, subprocessGetFirst);166+167+const 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.');171+172+ 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+};180+181+test('exports.getOneMessage() acknowledgment I/O error', testIoErrorSubprocess, 'ipc-get-io-error.js');182+test('exports.getEachMessage() acknowledgment I/O error', testIoErrorSubprocess, 'ipc-iterate-io-error.js');183+184+test('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});187+188+ const {ipcOutput} = await subprocess;189+ t.deepEqual(ipcOutput, [foobarString, foobarString]);190+});191+192+test('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);200+201+ const {ipcOutput} = await subprocess;202+ t.deepEqual(ipcOutput, []);203+});204+205+test('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);209+210+ const {ipcOutput} = await subprocess;211+ t.deepEqual(ipcOutput, []);212+});213+214+test('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.');218+219+ 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 lines29 expectType<undefined>(execa('test', {}).sendMessage);30 expectType<undefined>(execa('test', {ipc: false}).sendMessage);31 expectType<undefined>(execa('test', {ipcInput: undefined}).sendMessage);32 expectType<undefined>(execa('test', {ipc: false, ipcInput: ''}).sendMessage);33+34+await subprocess.sendMessage('', {} as const);35+await sendMessage('', {} as const);36+await subprocess.sendMessage('', {strict: true} as const);37+await sendMessage('', {strict: true} as const);38+expectError(await subprocess.sendMessage('', true));39+expectError(await sendMessage('', true));40+expectError(await subprocess.sendMessage('', {strict: 'true'}));41+expectError(await sendMessage('', {strict: 'true'}));42+expectError(await subprocess.sendMessage('', {unknown: true}));43+expectError(await sendMessage('', {unknown: true}));44+expectError(await subprocess.sendMessage('', {strict: true}, {}));45+expectError(await sendMessage('', {strict: true}, {}));modified:types/ipc.d.ts+20 added-8 removed
25 unmodified lines26 Serialization extends Options['serialization'] = Options['serialization'],27 > = Serialization extends 'json' ? JsonMessage : AdvancedMessage;28 29 /**30-Options to `getOneMessage()` and `subprocess.getOneMessage()`30+Options to `sendMessage()` and `subprocess.sendMessage()`31 */32-type GetOneMessageOptions<33- Serialization extends Options['serialization'],34-> = {32+type SendMessageOptions = {33 /**36- Ignore any `message` that returns `false`.34+ Throw when the other process is not receiving or listening to messages.35+36+ @default false37 */38- readonly filter?: (message: Message<Serialization>) => boolean;38+ readonly strict?: boolean;39 };40 41 // IPC methods in subprocess42 /**43 Send a `message` to the parent process.44 45 This requires the `ipc` option to be `true`. The type of `message` depends on the `serialization` option.46 */47-export function sendMessage(message: Message): Promise<void>;47+export function sendMessage(message: Message, sendMessageOptions?: SendMessageOptions): Promise<void>;48 49 /**50+Options to `getOneMessage()` and `subprocess.getOneMessage()`51+*/52+type GetOneMessageOptions<53+ Serialization extends Options['serialization'],54+> = {55+ /**56+ Ignore any `message` that returns `false`.57+ */58+ readonly filter?: (message: Message<Serialization>) => boolean;59+};60+61+/**62 Receive a single `message` from the parent process.63 64 This requires the `ipc` option to be `true`. The type of `message` depends on the `serialization` option.65 */16 unmodified lines82 Send a `message` to the subprocess.83 84 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>;87 88 /**89 Receive a single `message` from the subprocess.90 36 unmodified lines