Skip to content
Myr

Add `exchangeMessage()` method (#1077)

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

authored by ehmicky · committed by GitHub · parent 571e052 · Browse files · 39 files+649 added−229 removed
This commit

State

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

Diff stats

39 files+649 added−229 removed

  • tests:+332 added−182 removed
  • other:+317 added−47 removed

39 files+649 added−229 removed

modified:docs/api.md+25 added-1 removed
134 unmodified lines
135This requires the [`ipc`](#optionsipc) option to be `true`. The [type](ipc.md#message-type) of `message` depends on the [`serialization`](#optionsserialization) option.136137[More info.](ipc.md#listening-to-messages)138139### exchangeMessage(message, getOneMessageOptions?)140141`message`: [`Message`](ipc.md#message-type)\142_getOneMessageOptions_: [`GetOneMessageOptions`](#getonemessageoptions)\143_Returns_: [`Promise<Message>`](ipc.md#message-type)144145Send a `message` to the parent process, then receive a response from it.146147This requires the [`ipc`](#optionsipc) option to be `true`. The [type](ipc.md#message-type) of `message` depends on the [`serialization`](#optionsserialization) option.148149[More info.](ipc.md#exchanging-messages)150151## Return value152153_TypeScript:_ [`ResultPromise`](typescript.md)\154_Type:_ `Promise<object> | Subprocess`
149 unmodified lines
304This requires the [`ipc`](#optionsipc) option to be `true`. The [type](ipc.md#message-type) of `message` depends on the [`serialization`](#optionsserialization) option.305306[More info.](ipc.md#listening-to-messages)307308### subprocess.exchangeMessage(message, getOneMessageOptions?)309310`message`: [`Message`](ipc.md#message-type)\311_getOneMessageOptions_: [`GetOneMessageOptions`](#getonemessageoptions)\312_Returns_: [`Promise<Message>`](ipc.md#message-type)313314Send a `message` to the subprocess, then receive a response from it.315316This requires the [`ipc`](#optionsipc) option to be `true`. The [type](ipc.md#message-type) of `message` depends on the [`serialization`](#optionsserialization) option.317318[More info.](ipc.md#exchanging-messages)319320### subprocess.stdin321322_Type:_ [`Writable | null`](https://nodejs.org/api/stream.html#class-streamwritable)323
613 unmodified lines
937938_Type:_ `boolean`\939_Default:_ `true` if either the [`node`](#optionsnode) option or the [`ipcInput`](#optionsipcinput) is set, `false` otherwise940917Enables exchanging messages with the subprocess using [`subprocess.sendMessage(message)`](#subprocesssendmessagemessage), [`subprocess.getOneMessage()`](#subprocessgetonemessagegetonemessageoptions) and [`subprocess.getEachMessage()`](#subprocessgeteachmessage).941Enables exchanging messages with the subprocess using [`subprocess.sendMessage(message)`](#subprocesssendmessagemessage), [`subprocess.getOneMessage()`](#subprocessgetonemessagegetonemessageoptions), [`subprocess.exchangeMessage(message)`](#subprocessexchangemessagemessage-getonemessageoptions) and [`subprocess.getEachMessage()`](#subprocessgeteachmessage).942943The subprocess must be a Node.js file.944945[More info.](ipc.md)
199 unmodified lines
modified:docs/execution.md+1 added-1 removed
modified:docs/ipc.md+61 added-7 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). The subprocess uses [`sendMessage(message)`](api.md#sendmessagemessage) and [`getOneMessage()`](api.md#getonemessagegetonemessageoptions) instead.15The current process sends messages with [`subprocess.sendMessage(message)`](api.md#subprocesssendmessagemessage) and receives them with [`subprocess.getOneMessage()`](api.md#subprocessgetonemessagegetonemessageoptions). [`subprocess.exchangeMessage(message)`](api.md#subprocessexchangemessagemessage-getonemessageoptions) combines both: first it sends a message, then it returns the response.1617The subprocess uses [`sendMessage(message)`](api.md#sendmessagemessage), [`getOneMessage()`](api.md#getonemessagegetonemessageoptions) and [`exchangeMessage(message)`](api.md#exchangemessagemessage-getonemessageoptions) instead. Those are the same methods, but imported directly from the `'execa'` module.1819```js20// parent.js21import {execaNode} from 'execa';2223const subprocess = execaNode`child.js`;22console.log(await subprocess.getOneMessage()); // 'Hello from child'23await subprocess.sendMessage('Hello from parent');24const message = await subprocess.exchangeMessage('Hello from parent');25console.log(message); // 'Hello from child'26```2728```js29// child.js28import {sendMessage, getOneMessage} from 'execa';30import {getOneMessage, sendMessage} from 'execa';3130await sendMessage('Hello from child');31console.log(await getOneMessage()); // 'Hello from parent'32const message = await getOneMessage(); // 'Hello from parent'33const newMessage = message.replace('parent', 'child'); // 'Hello from child'34await sendMessage(newMessage);35```3637## Listening to messages3836[`subprocess.getOneMessage()`](api.md#subprocessgetonemessagegetonemessageoptions) and [`getOneMessage()`](api.md#getonemessagegetonemessageoptions) read a single message. To listen to multiple messages in a row, [`subprocess.getEachMessage()`](api.md#subprocessgeteachmessage) and [`getEachMessage()`](api.md#geteachmessage) should be used instead.39The methods described above read a single message. On the other hand, [`subprocess.getEachMessage()`](api.md#subprocessgeteachmessage) and [`getEachMessage()`](api.md#geteachmessage) return an [async iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols). This should be preferred when listening to multiple messages.4041[`subprocess.getEachMessage()`](api.md#subprocessgeteachmessage) waits for the subprocess to end (even when using [`break`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/break) or [`return`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return)). It throws if the subprocess [fails](api.md#result). This means you do not need to `await` the subprocess' [promise](execution.md#result).4243```js
101 unmodified lines
145146const subprocess = execaNode({serialization: 'json'})`child.js`;147```148149## Messages order150151The messages are always received in the same order they were sent.152153## Debugging154155When the [`verbose`](api.md#optionsverbose) option is `'full'`, the IPC messages sent by the subprocess to the current process are [printed on the console](debugging.md#full-mode).156157Also, when the subprocess [failed](errors.md#subprocess-failure), [`error.ipcOutput`](api.md) contains all the messages sent by the subprocess. Those are also shown at the end of the [error message](errors.md#error-message).158159## Best practices160161### Call `getOneMessage()`/`getEachMessage()` early162163If a process sends a message but the other process is not listening/receiving it, that message is silently ignored.164165This means if [`getOneMessage()`](api.md#getonemessagegetonemessageoptions) or [`getEachMessage()`](api.md#geteachmessage) is called too late (i.e. after the other process called [`sendMessage()`](api.md#sendmessagemessage)), it will miss the message. Also, it will keep waiting for the missed message, which might either make it hang forever, or throw when the other process exits.166167Therefore, listening to messages should always be done early, before the other process sends any message.168169### Prefer `exchangeMessage()` over `sendMessage()` + `getOneMessage()`170171When _first_ sending a message, _then_ receiving a response, the following code should be avoided.172173```js174import {sendMessage, getOneMessage} from 'execa';175176await sendMessage(message);177178// The other process might respond between those two calls179180const response = await getOneMessage();181```182183Indeed, when [`getOneMessage()`](api.md#getonemessagegetonemessageoptions) is called, the other process might have already sent a response. This only happens when the other process is very fast. However, when it does happen, `getOneMessage()` will miss that response.184185Using [`exchangeMessage()`](api.md#exchangemessagemessage-getonemessageoptions) prevents this race condition.186187```js188import {exchangeMessage} from 'execa';189190const response = await exchangeMessage(message);191```192193However please note that, when doing the reverse (_first_ receiving a message, _then_ sending a response), the following code is correct.194195```js196import {sendMessage, getOneMessage} from 'execa';197198const message = await getOneMessage();199200// The other process is just waiting for a response between those two calls.201// So there is no race condition here.202203await sendMessage('response');204```205206<hr>207208[**Next**: 🐛 Debugging](debugging.md)\209[**Previous**: ⏳️ Streams](streams.md)\
1 unmodified line
added:lib/ipc/exchange.js+43 added
modified:lib/ipc/get-each.js+7 added-4 removed
1import {once, on} from 'node:events';2import {validateIpcOption, validateConnection, disconnect} from './validation.js';2import {validateIpcMethod, disconnect} from './validation.js';34// Like `[sub]process.on('message')` but promise-based5export const getEachMessage = ({anyProcess, isSubprocess, ipc}) => loopOnMessages({6 anyProcess,
3 unmodified lines
10});1112// Same but used internally13export const loopOnMessages = ({anyProcess, isSubprocess, ipc, shouldAwait}) => {14 const methodName = 'getEachMessage';15 validateIpcOption(methodName, isSubprocess, ipc);16 validateConnection(methodName, isSubprocess, anyProcess.channel !== null);14 validateIpcMethod({15 methodName: 'getEachMessage',16 isSubprocess,17 ipc,18 isConnected: anyProcess.channel !== null,19 });2021 const controller = new AbortController();22 stopOnExit(anyProcess, controller);23 return iterateOnMessages(anyProcess, shouldAwait, controller);
37 unmodified lines
modified:lib/ipc/get-one.js+9 added-5 removed
1import {once, on} from 'node:events';2import {3 validateIpcOption,4 validateConnection,3 validateIpcMethod,4 disconnect,5 throwOnEarlyDisconnect,6} from './validation.js';78// Like `[sub]process.once('message')` but promise-based9export const getOneMessage = ({anyProcess, isSubprocess, ipc}, {filter} = {}) => {10 const methodName = 'getOneMessage';12 validateIpcOption(methodName, isSubprocess, ipc);13 validateConnection(methodName, isSubprocess, anyProcess.channel !== null);11 validateIpcMethod({12 methodName,13 isSubprocess,14 ipc,15 isConnected: anyProcess.channel !== null,16 });1718 return onceMessage({19 anyProcess,20 isSubprocess,
1 unmodified line
22 filter,23 });24};2526// Same but used internally23const onceMessage = async ({anyProcess, isSubprocess, methodName, filter}) => {27export const onceMessage = async ({anyProcess, isSubprocess, methodName, filter}) => {28 const controller = new AbortController();29 try {30 return await Promise.race([31 getMessage(anyProcess, filter, controller),
32 unmodified lines
modified:lib/ipc/methods.js+7 added
modified:lib/ipc/send.js+17 added-7 removed
1import {2 validateIpcOption,3 validateConnection,2 validateIpcMethod,3 handleSerializationError,4 disconnect,5} from './validation.js';67// Like `[sub]process.send()` but promise-based.9// We do not `await subprocess` during `.sendMessage()` nor `.getOneMessage()` since those methods are transient.8// We do not `await subprocess` during `.sendMessage()`, `.getOneMessage()` nor `.exchangeMessage()` since those methods are transient.9// Users would still need to `await subprocess` after the method is done.10// Also, this would prevent `unhandledRejection` event from being emitted, making it silent.11export const sendMessage = ({anyProcess, anyProcessSend, isSubprocess, ipc}, message) => {12 const methodName = 'sendMessage';14 validateIpcOption(methodName, isSubprocess, ipc);15 validateConnection(methodName, isSubprocess, anyProcess.connected);13 validateIpcMethod({14 methodName,15 isSubprocess,16 ipc,17 isConnected: anyProcess.connected,18 });1920 return sendOneMessage({21 anyProcess,22 anyProcessSend,23 isSubprocess,24 methodName,25 message,26 });27};2825const sendOneMessage = async ({anyProcess, anyProcessSend, isSubprocess, message}) => {29// Same but used internally30export const sendOneMessage = async ({anyProcess, anyProcessSend, isSubprocess, methodName, message}) => {31 try {32 await anyProcessSend(message);33 } catch (error) {34 disconnect(anyProcess);30 handleSerializationError(error, isSubprocess, message);35 handleSerializationError({36 error,37 isSubprocess,38 methodName,39 message,40 });41 throw error;42 }43};
modified:lib/ipc/validation.js+10 added-4 removed
1// Validate the IPC channel is connected before receiving/sending messages2export const validateIpcMethod = ({methodName, isSubprocess, ipc, isConnected}) => {3 validateIpcOption(methodName, isSubprocess, ipc);4 validateConnection(methodName, isSubprocess, isConnected);5};67// Better error message when forgetting to set `ipc: true` and using the IPC methods2export const validateIpcOption = (methodName, isSubprocess, ipc) => {8const validateIpcOption = (methodName, isSubprocess, ipc) => {9 if (!ipc) {10 throw new Error(`${getNamespaceName(isSubprocess)}${methodName}() can only be used if the \`ipc\` option is \`true\`.`);11 }12};1314// Better error message when one process does not send/receive messages once the other process has disconnected.15// This also makes it clear that any buffered messages are lost once either process has disconnected.10export const validateConnection = (methodName, isSubprocess, isConnected) => {16const validateConnection = (methodName, isSubprocess, isConnected) => {17 if (!isConnected) {18 throw new Error(`${getNamespaceName(isSubprocess)}${methodName}() cannot be used: the ${getOtherProcessName(isSubprocess)} has already exited or disconnected.`);19 }20};
8 unmodified lines
29const getOtherProcessName = isSubprocess => isSubprocess ? 'parent process' : 'subprocess';3031// Better error message when sending messages which cannot be serialized.32// Works with both `serialization: 'advanced'` and `serialization: 'json'`.27export const handleSerializationError = (error, isSubprocess, message) => {33export const handleSerializationError = ({error, isSubprocess, methodName, message}) => {34 if (isSerializationError(error)) {29 error.message = `${getNamespaceName(isSubprocess)}sendMessage()'s argument type is invalid: the message cannot be serialized: ${String(message)}.\n${error.message}`;35 error.message = `${getNamespaceName(isSubprocess)}${methodName}()'s argument type is invalid: the message cannot be serialized: ${String(message)}.\n${error.message}`;36 }37};3839const isSerializationError = ({code, message}) => SERIALIZATION_ERROR_CODES.has(code)
28 unmodified lines
modified:test/convert/readable.js+2 added-4 removed
116 unmodified lines
117 const subprocess = execa('ipc-echo.js', {ipc: true});118 const stream = subprocess[methodName]();119120 subprocess.stdout.destroy();121 await subprocess.sendMessage(foobarString);121122 const [error, message] = await Promise.all([123 t.throwsAsync(finishedStream(stream)),125 subprocess.getOneMessage(),124 subprocess.exchangeMessage(foobarString),125 ]);126 t.like(error, prematureClose);127 t.is(message, foobarString);128 assertWritableAborted(t, subprocess.stdin);
10 unmodified lines
139 const stream = subprocess[methodName]();140141 const cause = new Error(foobarString);142 subprocess.stdout.destroy(cause);144 await subprocess.sendMessage(foobarString);143144 const [error, message] = await Promise.all([145 t.throwsAsync(finishedStream(stream)),148 subprocess.getOneMessage(),146 subprocess.exchangeMessage(foobarString),147 ]);148 t.is(message, foobarString);149 t.is(error.cause, cause);150 assertProcessNormalExit(t, error);
307 unmodified lines
added:test/fixtures/ipc-echo-filter-exchange.js+5 added
1#!/usr/bin/env node2import {sendMessage, exchangeMessage} from '../../index.js';3import {foobarArray} from '../helpers/input.js';45await sendMessage(await exchangeMessage('.', ({filter: message => message === foobarArray[1]})));
added:test/fixtures/ipc-echo-item-exchange.js+5 added
1#!/usr/bin/env node2import {exchangeMessage, getOneMessage} from '../../index.js';34const [message] = await getOneMessage();5await exchangeMessage(message);
added:test/fixtures/ipc-echo-twice-filter-get.js+10 added
1#!/usr/bin/env node2import {sendMessage, getOneMessage} from '../../index.js';3import {alwaysPass} from '../helpers/ipc.js';45const message = await getOneMessage({filter: alwaysPass});6const [secondMessage] = await Promise.all([7 getOneMessage({filter: alwaysPass}),8 sendMessage(message),9]);10await sendMessage(secondMessage);
modified:test/fixtures/ipc-echo-twice-filter.js+3 added-4 removed
1#!/usr/bin/env node2import {sendMessage, getOneMessage} from '../../index.js';2import {sendMessage, getOneMessage, exchangeMessage} from '../../index.js';3import {alwaysPass} from '../helpers/ipc.js';45const message = await getOneMessage({filter: alwaysPass});6const secondMessagePromise = getOneMessage({filter: alwaysPass});7await sendMessage(message);8await sendMessage(await secondMessagePromise);6const secondMessage = await exchangeMessage(message, {filter: alwaysPass});7await sendMessage(secondMessage);
added:test/fixtures/ipc-echo-twice-get.js+9 added
1#!/usr/bin/env node2import {sendMessage, getOneMessage} from '../../index.js';34const message = await getOneMessage();5const [secondMessage] = await Promise.all([6 getOneMessage(),7 sendMessage(message),8]);9await sendMessage(await secondMessage);
modified:test/fixtures/ipc-echo-twice.js+3 added-4 removed
1#!/usr/bin/env node2import {sendMessage, getOneMessage} from '../../index.js';2import {sendMessage, getOneMessage, exchangeMessage} from '../../index.js';34const message = await getOneMessage();5const secondMessagePromise = getOneMessage();6await sendMessage(message);7await sendMessage(await secondMessagePromise);5const secondMessage = await exchangeMessage(message);6await sendMessage(await secondMessage);
added:test/fixtures/ipc-exchange-error.js+4 added
1#!/usr/bin/env node2import {exchangeMessage} from '../../index.js';34await exchangeMessage(0n);
modified:test/fixtures/ipc-iterate-error.js+1 added-11 removed
1#!/usr/bin/env node2import process from 'node:process';3import {getEachMessage} from '../../index.js';3import {foobarString} from '../helpers/input.js';4import {iterateAllMessages} from '../helpers/ipc.js';56// @todo: replace with Array.fromAsync(subprocess.getEachMessage()) after dropping support for Node <22.0.07const iterateAllMessages = async () => {8 const messages = [];9 for await (const message of getEachMessage()) {10 messages.push(message);11 }1213 return messages;14};156const cause = new Error(foobarString);7await Promise.all([8 iterateAllMessages(),9 process.emit('error', cause),
1 unmodified line
added:test/fixtures/ipc-process-error-exchange.js+10 added
1#!/usr/bin/env node2import process from 'node:process';3import {exchangeMessage} from '../../index.js';4import {foobarString} from '../helpers/input.js';56const cause = new Error(foobarString);7await Promise.all([8 exchangeMessage('.'),9 process.emit('error', cause),10]);
added:test/fixtures/ipc-process-error-filter-exchange.js+11 added
1#!/usr/bin/env node2import process from 'node:process';3import {exchangeMessage} from '../../index.js';4import {foobarString} from '../helpers/input.js';5import {alwaysPass} from '../helpers/ipc.js';67const cause = new Error(foobarString);8await Promise.all([9 exchangeMessage('.', {filter: alwaysPass}),10 process.emit('error', cause),11]);
modified:test/fixtures/ipc-send-print.js+2 added-1 removed
1 unmodified line
2import process from 'node:process';3import {sendMessage, getOneMessage} from '../../index.js';4import {foobarString} from '../helpers/input.js';56const promise = getOneMessage();7await sendMessage(foobarString);89process.stdout.write('.');1010await getOneMessage();11await promise;
modified:test/fixtures/ipc-send-twice-wait.js+2 added-3 removed
1#!/usr/bin/env node2import {sendMessage, getOneMessage} from '../../index.js';2import {sendMessage, exchangeMessage} from '../../index.js';3import {foobarString} from '../helpers/input.js';45await sendMessage(foobarString);6await sendMessage(foobarString);7await getOneMessage();6await exchangeMessage(foobarString);
modified:test/helpers/ipc.js+16 added
1import isPlainObj from 'is-plain-obj';23export const subprocessGetOne = (subprocess, options) => subprocess.getOneMessage(options);45export const subprocessSendGetOne = async (subprocess, message) => {6 const [response] = await Promise.all([7 subprocess.getOneMessage(),8 subprocess.sendMessage(message),9 ]);10 return response;11};1213export const subprocessExchange = (subprocess, messageOrOptions) => isPlainObj(messageOrOptions)14 ? subprocess.exchangeMessage('.', messageOrOptions)15 : subprocess.exchangeMessage(messageOrOptions);1617// @todo: replace with Array.fromAsync(subprocess.getEachMessage()) after dropping support for Node <22.0.018export const iterateAllMessages = async subprocess => {19 const messages = [];20 for await (const message of subprocess.getEachMessage()) {
7 unmodified lines
modified:test/io/max-buffer.js+1 added-1 removed
276 unmodified lines
277 } = await t.throwsAsync(execa('ipc-send-twice-wait.js', {ipc: true, maxBuffer: {ipc: 1}}));278 t.true(isMaxBuffer);279 t.is(shortMessage, 'Command\'s IPC output was larger than 1 messages: ipc-send-twice-wait.js\nmaxBuffer exceeded');280 t.true(message.endsWith(`\n\n${foobarString}`));281 t.true(stderr.includes('Error: getOneMessage() could not complete'));281 t.true(stderr.includes('Error: exchangeMessage() could not complete'));282 t.deepEqual(ipcOutput, [foobarString]);283});284285test('maxBuffer is ignored with result.ipcOutput if buffer is false', async t => {
8 unmodified lines
modified:test/ipc/buffer-messages.js+11 added
55 unmodified lines
56 const {ipcOutput} = t.throws(() => execaSync('fail.js'));57 t.deepEqual(ipcOutput, []);58});5960const HIGH_CONCURRENCY_COUNT = 10;6162test.serial('Can retrieve initial IPC messages under heavy load', async t => {63 await Promise.all(64 Array.from({length: HIGH_CONCURRENCY_COUNT}, async (_, index) => {65 const {ipcOutput} = await execa('ipc-send-argv.js', [`${index}`], {ipc: true});66 t.deepEqual(ipcOutput, [`${index}`]);67 }),68 );69});7071test('"error" event interrupts result.ipcOutput', async t => {72 const subprocess = execa('ipc-echo-twice.js', {ipcInput: foobarString});73 t.is(await subprocess.getOneMessage(), foobarString);74
6 unmodified lines
modified:test/ipc/get-each.js+28 added-10 removed
29 unmodified lines
3031test('Can iterate multiple times over IPC messages in subprocess', async t => {32 const subprocess = execa('ipc-iterate-twice.js', {ipc: true});3334 await subprocess.sendMessage('.');35 t.is(await subprocess.getOneMessage(), '.');36 await subprocess.sendMessage(foobarString);37 t.is(await subprocess.getOneMessage(), foobarString);38 await subprocess.sendMessage('.');39 t.is(await subprocess.getOneMessage(), '.');40 await subprocess.sendMessage(foobarString);41 t.is(await subprocess.getOneMessage(), foobarString);34 t.is(await subprocess.exchangeMessage('.'), '.');35 t.is(await subprocess.exchangeMessage(foobarString), foobarString);36 t.is(await subprocess.exchangeMessage('.'), '.');37 t.is(await subprocess.exchangeMessage(foobarString), foobarString);3839 const {ipcOutput} = await subprocess;40 t.deepEqual(ipcOutput, ['.', foobarString, '.', foobarString]);41});
8 unmodified lines
50 const {ipcOutput} = await subprocess;51 t.deepEqual(ipcOutput, foobarArray);52});5358const HIGH_CONCURRENCY_COUNT = 100;54const HIGH_CONCURRENCY_COUNT = 10;5560test('Can send many messages at once with exports.getEachMessage()', async t => {56test.serial('Can send many messages at once with exports.getEachMessage()', async t => {57 const subprocess = execa('ipc-iterate.js', {ipc: true});58 await Promise.all(Array.from({length: HIGH_CONCURRENCY_COUNT}, (_, index) => subprocess.sendMessage(index)));59 await subprocess.sendMessage(foobarString);60
30 unmodified lines
91 const {ipcOutput} = await subprocess;92 t.deepEqual(ipcOutput, [foobarString]);93});9495const testParentError = async (t, buffer) => {96 const subprocess = execa('ipc-send-twice.js', {ipc: true, buffer});97 const promise = iterateAllMessages(subprocess);9899 const cause = new Error(foobarString);100 subprocess.emit('error', cause);101102 const ipcError = await t.throwsAsync(promise);103 t.is(ipcError.cause, cause);104105 const error = await t.throwsAsync(subprocess);106 t.is(error.exitCode, undefined);107 t.false(error.isTerminated);108 t.is(error.cause, cause);109 if (buffer) {110 t.true(error.message.includes('Error: sendMessage() cannot be used'));111 }112};113114test('"error" event interrupts subprocess.getEachMessage(), buffer false', testParentError, false);115test('error" event interrupts subprocess.getEachMessage(), buffer true', testParentError, true);116117const loopAndBreak = async (t, subprocess) => {118 // eslint-disable-next-line no-unreachable-loop119 for await (const message of subprocess.getEachMessage()) {120 t.is(message, foobarString);
29 unmodified lines
modified:test/ipc/get-one.js+105 added-80 removed
2 unmodified lines
3import test from 'ava';4import {execa} from '../../index.js';5import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6import {foobarString, foobarArray} from '../helpers/input.js';7import {iterateAllMessages, alwaysPass} from '../helpers/ipc.js';7import {8 subprocessGetOne,9 subprocessSendGetOne,10 subprocessExchange,11 alwaysPass,12} from '../helpers/ipc.js';1314setFixtureDirectory();1511const getOneSubprocessMessage = subprocess => subprocess.getOneMessage();12const getOneFilteredMessage = subprocess => subprocess.getOneMessage({filter: alwaysPass});1314const testKeepAlive = async (t, buffer) => {16const testKeepAlive = async (t, buffer, exchangeMethod) => {17 const subprocess = execa('ipc-echo-twice.js', {ipc: true, buffer});16 await subprocess.sendMessage(foobarString);17 t.is(await subprocess.getOneMessage(), foobarString);18 await subprocess.sendMessage(foobarString);19 t.is(await subprocess.getOneMessage(), foobarString);18 t.is(await exchangeMethod(subprocess, foobarString), foobarString);19 t.is(await exchangeMethod(subprocess, foobarString), foobarString);20 await subprocess;21};2223test('subprocess.getOneMessage() keeps the subprocess alive, buffer false', testKeepAlive, false);24test('subprocess.getOneMessage() keeps the subprocess alive, buffer true', testKeepAlive, true);23test('subprocess.getOneMessage() keeps the subprocess alive, buffer false', testKeepAlive, false, subprocessSendGetOne);24test('subprocess.getOneMessage() keeps the subprocess alive, buffer true', testKeepAlive, true, subprocessSendGetOne);25test('subprocess.getOneMessage() keeps the subprocess alive, buffer false, exchangeMessage()', testKeepAlive, false, subprocessExchange);26test('subprocess.getOneMessage() keeps the subprocess alive, buffer true, exchangeMessage()', testKeepAlive, true, subprocessExchange);2726const testBufferInitial = async (t, buffer) => {28const testBufferInitial = async (t, buffer, exchangeMethod) => {29 const subprocess = execa('ipc-echo-wait.js', {ipc: true, buffer});28 await subprocess.sendMessage(foobarString);29 t.is(await subprocess.getOneMessage(), foobarString);30 t.is(await exchangeMethod(subprocess, foobarString), foobarString);31 await subprocess;32};3333test('Buffers initial message to subprocess, buffer false', testBufferInitial, false);34test('Buffers initial message to subprocess, buffer true', testBufferInitial, true);34test('Buffers initial message to subprocess, buffer false', testBufferInitial, false, subprocessSendGetOne);35test('Buffers initial message to subprocess, buffer true', testBufferInitial, true, subprocessSendGetOne);36test('Buffers initial message to subprocess, buffer false, exchangeMessage()', testBufferInitial, false, subprocessExchange);37test('Buffers initial message to subprocess, buffer true, exchangeMessage()', testBufferInitial, true, subprocessExchange);3839test('Buffers initial message to current process, buffer false', async t => {40 const subprocess = execa('ipc-send-print.js', {ipc: true, buffer: false});41 const [chunk] = await once(subprocess.stdout, 'data');
13 unmodified lines
55 const {ipcOutput} = await subprocess;56 t.deepEqual(ipcOutput, [foobarString]);57});5856const HIGH_CONCURRENCY_COUNT = 100;5758test('subprocess.getOneMessage() can filter messages', async t => {59const testFilterParent = async (t, exchangeMethod) => {60 const subprocess = execa('ipc-send-twice.js', {ipc: true});60 const message = await subprocess.getOneMessage({filter: message => message === foobarArray[1]});61 const message = await exchangeMethod(subprocess, {filter: message => message === foobarArray[1]});62 t.is(message, foobarArray[1]);6364 const {ipcOutput} = await subprocess;65 t.deepEqual(ipcOutput, foobarArray);65});66};6767test('exports.getOneMessage() can filter messages', async t => {68 const subprocess = execa('ipc-echo-filter.js', {ipc: true});68test('subprocess.getOneMessage() can filter messages', testFilterParent, subprocessGetOne);69test('subprocess.exchangeMessage() can filter messages', testFilterParent, subprocessExchange);7071const testFilterSubprocess = async (t, fixtureName, expectedOutput) => {72 const subprocess = execa(fixtureName, {ipc: true});73 await subprocess.sendMessage(foobarArray[0]);74 await subprocess.sendMessage(foobarArray[1]);7576 const {ipcOutput} = await subprocess;73 t.deepEqual(ipcOutput, [foobarArray[1]]);74});77 t.deepEqual(ipcOutput, expectedOutput);78};7976test.serial('Can retrieve initial IPC messages under heavy load, buffer false', async t => {80test('exports.getOneMessage() can filter messages', testFilterSubprocess, 'ipc-echo-filter.js', [foobarArray[1]]);81test('exports.exchangeMessage() can filter messages', testFilterSubprocess, 'ipc-echo-filter-exchange.js', ['.', foobarArray[1]]);8283const HIGH_CONCURRENCY_COUNT = 10;8485const testHeavyLoad = async (t, exchangeMethod) => {86 await Promise.all(87 Array.from({length: HIGH_CONCURRENCY_COUNT}, async (_, index) => {88 const subprocess = execa('ipc-send-argv.js', [`${index}`], {ipc: true, buffer: false});80 t.is(await subprocess.getOneMessage(), `${index}`);89 t.is(await exchangeMethod(subprocess, {}), `${index}`);90 await subprocess;91 }),92 );84});93};9486test.serial('Can retrieve initial IPC messages under heavy load, buffer true', async t => {87 await Promise.all(88 Array.from({length: HIGH_CONCURRENCY_COUNT}, async (_, index) => {89 const {ipcOutput} = await execa('ipc-send-argv.js', [`${index}`], {ipc: true});90 t.deepEqual(ipcOutput, [`${index}`]);91 }),92 );93});95test.serial('Can retrieve initial IPC messages under heavy load', testHeavyLoad, subprocessGetOne);96test.serial('Can retrieve initial IPC messages under heavy load, exchangeMessage()', testHeavyLoad, subprocessExchange);9795const testTwice = async (t, buffer, filter) => {98const testTwice = async (t, exchangeMethod, buffer, filter) => {99 const subprocess = execa('ipc-send.js', {ipc: true, buffer});100 t.deepEqual(98 await Promise.all([subprocess.getOneMessage({filter}), subprocess.getOneMessage({filter})]),101 await Promise.all([exchangeMethod(subprocess, {filter}), exchangeMethod(subprocess, {filter})]),102 [foobarString, foobarString],103 );104 await subprocess;105};106104test('subprocess.getOneMessage() can be called twice at the same time, buffer false', testTwice, false, undefined);105test('subprocess.getOneMessage() can be called twice at the same time, buffer true', testTwice, true, undefined);106test('subprocess.getOneMessage() can be called twice at the same time, buffer false, filter', testTwice, false, alwaysPass);107test('subprocess.getOneMessage() can be called twice at the same time, buffer true, filter', testTwice, true, alwaysPass);107test('subprocess.getOneMessage() can be called twice at the same time, buffer false', testTwice, subprocessGetOne, false, undefined);108test('subprocess.getOneMessage() can be called twice at the same time, buffer true', testTwice, subprocessGetOne, true, undefined);109test('subprocess.getOneMessage() can be called twice at the same time, buffer false, filter', testTwice, subprocessGetOne, false, alwaysPass);110test('subprocess.getOneMessage() can be called twice at the same time, buffer true, filter', testTwice, subprocessGetOne, true, alwaysPass);111test('subprocess.exchangeMessage() can be called twice at the same time, buffer false', testTwice, subprocessExchange, false, undefined);112test('subprocess.exchangeMessage() can be called twice at the same time, buffer true', testTwice, subprocessExchange, true, undefined);113test('subprocess.exchangeMessage() can be called twice at the same time, buffer false, filter', testTwice, subprocessExchange, false, alwaysPass);114test('subprocess.exchangeMessage() can be called twice at the same time, buffer true, filter', testTwice, subprocessExchange, true, alwaysPass);115109const testCleanupListeners = async (t, buffer, filter) => {116const testCleanupListeners = async (t, exchangeMethod, buffer, filter) => {117 const subprocess = execa('ipc-send.js', {ipc: true, buffer});118 const bufferCount = buffer ? 1 : 0;119120 t.is(subprocess.listenerCount('message'), bufferCount);121 t.is(subprocess.listenerCount('disconnect'), bufferCount);122116 const promise = subprocess.getOneMessage({filter});123 const promise = exchangeMethod(subprocess, {filter});124 t.is(subprocess.listenerCount('message'), bufferCount + 1);125 t.is(subprocess.listenerCount('disconnect'), bufferCount + 1);126 t.is(await promise, foobarString);127
5 unmodified lines
133 t.is(subprocess.listenerCount('message'), 0);134 t.is(subprocess.listenerCount('disconnect'), 0);135};136130test('Cleans up subprocess.getOneMessage() listeners, buffer false', testCleanupListeners, false, undefined);131test('Cleans up subprocess.getOneMessage() listeners, buffer true', testCleanupListeners, true, undefined);132test('Cleans up subprocess.getOneMessage() listeners, buffer false, filter', testCleanupListeners, false, alwaysPass);133test('Cleans up subprocess.getOneMessage() listeners, buffer true, filter', testCleanupListeners, true, alwaysPass);137test('Cleans up subprocess.getOneMessage() listeners, buffer false', testCleanupListeners, subprocessGetOne, false, undefined);138test('Cleans up subprocess.getOneMessage() listeners, buffer true', testCleanupListeners, subprocessGetOne, true, undefined);139test('Cleans up subprocess.getOneMessage() listeners, buffer false, filter', testCleanupListeners, subprocessGetOne, false, alwaysPass);140test('Cleans up subprocess.getOneMessage() listeners, buffer true, filter', testCleanupListeners, subprocessGetOne, true, alwaysPass);141test('Cleans up subprocess.exchangeMessage() listeners, buffer false', testCleanupListeners, subprocessExchange, false, undefined);142test('Cleans up subprocess.exchangeMessage() listeners, buffer true', testCleanupListeners, subprocessExchange, true, undefined);143test('Cleans up subprocess.exchangeMessage() listeners, buffer false, filter', testCleanupListeners, subprocessExchange, false, alwaysPass);144test('Cleans up subprocess.exchangeMessage() listeners, buffer true, filter', testCleanupListeners, subprocessExchange, true, alwaysPass);145135const testParentDisconnect = async (t, buffer, filter) => {136 const fixtureName = filter ? 'ipc-echo-twice-filter.js' : 'ipc-echo-twice.js';146const testParentDisconnect = async (t, buffer, filter, exchange) => {147 const fixtureStart = filter ? 'ipc-echo-twice-filter' : 'ipc-echo-twice';148 const fixtureName = exchange ? `${fixtureStart}.js` : `${fixtureStart}-get.js`;149 const subprocess = execa(fixtureName, {ipc: true, buffer});150 await subprocess.sendMessage(foobarString);151 t.is(await subprocess.getOneMessage(), foobarString);152
2 unmodified lines
155 const {exitCode, isTerminated, message} = await t.throwsAsync(subprocess);156 t.is(exitCode, 1);157 t.false(isTerminated);158 if (buffer) {147 t.true(message.includes('Error: getOneMessage() could not complete'));159 const methodName = exchange ? 'exchangeMessage()' : 'getOneMessage()';160 t.true(message.includes(`Error: ${methodName} could not complete`));161 }162};163151test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer false', testParentDisconnect, false, false);152test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer true', testParentDisconnect, true, false);153test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer false, filter', testParentDisconnect, false, true);154test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer true, filter', testParentDisconnect, true, true);164test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer false', testParentDisconnect, false, false, false);165test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer true', testParentDisconnect, true, false, false);166test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer false, filter', testParentDisconnect, false, true, false);167test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer true, filter', testParentDisconnect, true, false);168test('subprocess.disconnect() interrupts exports.exchangeMessage(), buffer false', testParentDisconnect, false, false, true);169test('subprocess.disconnect() interrupts exports.exchangeMessage(), buffer true', testParentDisconnect, true, false, true);170test('subprocess.disconnect() interrupts exports.exchangeMessage(), buffer false, filter', testParentDisconnect, false, true, true);171test('subprocess.disconnect() interrupts exports.exchangeMessage(), buffer true, filter', testParentDisconnect, true, true, true);172173// eslint-disable-next-line max-params156const testSubprocessDisconnect = async (t, buffer, filter) => {174const testSubprocessDisconnect = async (t, exchangeMethod, methodName, buffer, filter) => {175 const subprocess = execa('empty.js', {ipc: true, buffer});158 await t.throwsAsync(subprocess.getOneMessage({filter}), {159 message: /subprocess\.getOneMessage\(\) could not complete/,160 });176 const {message} = await t.throwsAsync(exchangeMethod(subprocess, {filter}));177 t.true(message.includes(`subprocess.${methodName}() could not complete`));178 await subprocess;179};180164test('Subprocess exit interrupts disconnect.getOneMessage(), buffer false', testSubprocessDisconnect, false, undefined);165test('Subprocess exit interrupts disconnect.getOneMessage(), buffer true', testSubprocessDisconnect, true, undefined);166test('Subprocess exit interrupts disconnect.getOneMessage(), buffer false, filter', testSubprocessDisconnect, false, alwaysPass);167test('Subprocess exit interrupts disconnect.getOneMessage(), buffer true, filter', testSubprocessDisconnect, true, alwaysPass);181test('Subprocess exit interrupts subprocess.getOneMessage(), buffer false', testSubprocessDisconnect, subprocessGetOne, 'getOneMessage', false, undefined);182test('Subprocess exit interrupts subprocess.getOneMessage(), buffer true', testSubprocessDisconnect, subprocessGetOne, 'getOneMessage', true, undefined);183test('Subprocess exit interrupts subprocess.getOneMessage(), buffer false, filter', testSubprocessDisconnect, subprocessGetOne, 'getOneMessage', false, alwaysPass);184test('Subprocess exit interrupts subprocess.getOneMessage(), buffer true, filter', testSubprocessDisconnect, subprocessGetOne, 'getOneMessage', true, alwaysPass);185test('Subprocess exit interrupts subprocess.exchangeMessage(), buffer false', testSubprocessDisconnect, subprocessExchange, 'exchangeMessage', false, undefined);186test('Subprocess exit interrupts subprocess.exchangeMessage(), buffer true', testSubprocessDisconnect, subprocessExchange, 'exchangeMessage', true, undefined);187test('Subprocess exit interrupts subprocess.exchangeMessage(), buffer false, filter', testSubprocessDisconnect, subprocessExchange, 'exchangeMessage', false, alwaysPass);188test('Subprocess exit interrupts subprocess.exchangeMessage(), buffer true, filter', testSubprocessDisconnect, subprocessExchange, 'exchangeMessage', true, alwaysPass);189169const testParentError = async (t, getMessages, useCause, buffer) => {170 const subprocess = execa('ipc-echo.js', {ipc: true, buffer});171 await subprocess.sendMessage(foobarString);172 const promise = getMessages(subprocess);190const testParentError = async (t, exchangeMethod, filter, buffer) => {191 const subprocess = execa('forever.js', {ipc: true, buffer});192 const promise = exchangeMethod(subprocess, {filter});193194 const cause = new Error(foobarString);195 subprocess.emit('error', cause);196 t.is(await t.throwsAsync(promise), cause);197177 const ipcError = await t.throwsAsync(promise);178 t.is(useCause ? ipcError.cause : ipcError, cause);179198 subprocess.kill();199 const error = await t.throwsAsync(subprocess);181 t.is(error.exitCode, 1);200 t.is(error.exitCode, undefined);201 t.false(error.isTerminated);202 t.is(error.cause, cause);184 if (buffer) {185 t.true(error.message.includes('Error: getOneMessage() cannot be used'));186 }203};204189test('"error" event interrupts subprocess.getOneMessage(), buffer false', testParentError, getOneSubprocessMessage, false, false);190test('"error" event interrupts subprocess.getOneMessage(), buffer true', testParentError, getOneSubprocessMessage, false, true);191test('"error" event interrupts subprocess.getOneMessage(), buffer false, filter', testParentError, getOneFilteredMessage, false, false);192test('"error" event interrupts subprocess.getOneMessage(), buffer true, filter', testParentError, getOneFilteredMessage, false, true);193test('"error" event interrupts subprocess.getEachMessage(), buffer false', testParentError, iterateAllMessages, true, false);194test('"error" event interrupts subprocess.getEachMessage(), buffer true', testParentError, iterateAllMessages, true, true);205test('"error" event interrupts subprocess.getOneMessage(), buffer false', testParentError, subprocessGetOne, undefined, false);206test('"error" event interrupts subprocess.getOneMessage(), buffer true', testParentError, subprocessGetOne, undefined, true);207test('"error" event interrupts subprocess.getOneMessage(), buffer false, filter', testParentError, subprocessGetOne, alwaysPass, false);208test('"error" event interrupts subprocess.getOneMessage(), buffer true, filter', testParentError, subprocessGetOne, alwaysPass, true);209test('"error" event interrupts subprocess.exchangeMessage(), buffer false', testParentError, subprocessExchange, undefined, false);210test('"error" event interrupts subprocess.exchangeMessage(), buffer true', testParentError, subprocessExchange, undefined, true);211test('"error" event interrupts subprocess.exchangeMessage(), buffer false, filter', testParentError, subprocessExchange, alwaysPass, false);212test('"error" event interrupts subprocess.exchangeMessage(), buffer true, filter', testParentError, subprocessExchange, alwaysPass, true);213214const testSubprocessError = async (t, fixtureName, buffer) => {215 const subprocess = execa(fixtureName, {ipc: true, buffer});216 if (fixtureName.includes('exchange')) {217 await subprocess.getOneMessage();218 }219220 const ipcError = await t.throwsAsync(subprocess.getOneMessage());221 t.true(ipcError.message.includes('subprocess.getOneMessage() could not complete'));222
8 unmodified lines
231test('"error" event interrupts exports.getOneMessage(), buffer false', testSubprocessError, 'ipc-process-error.js', false);232test('"error" event interrupts exports.getOneMessage(), buffer true', testSubprocessError, 'ipc-process-error.js', true);233test('"error" event interrupts exports.getOneMessage(), buffer false, filter', testSubprocessError, 'ipc-process-error-filter.js', false);234test('"error" event interrupts exports.getOneMessage(), buffer true, filter', testSubprocessError, 'ipc-process-error-filter.js', true);235test('"error" event interrupts exports.exchangeMessage(), buffer false', testSubprocessError, 'ipc-process-error-exchange.js', false);236test('"error" event interrupts exports.exchangeMessage(), buffer true', testSubprocessError, 'ipc-process-error-exchange.js', true);237test('"error" event interrupts exports.exchangeMessage(), buffer false, filter', testSubprocessError, 'ipc-process-error-filter-exchange.js', false);238test('"error" event interrupts exports.exchangeMessage(), buffer true, filter', testSubprocessError, 'ipc-process-error-filter-exchange.js', true);239test('"error" event interrupts exports.getEachMessage(), buffer false', testSubprocessError, 'ipc-iterate-error.js', false);240test('"error" event interrupts exports.getEachMessage(), buffer true', testSubprocessError, 'ipc-iterate-error.js', true);
modified:test/ipc/send.js+60 added-41 removed
1import test from 'ava';2import {execa} from '../../index.js';3import {setFixtureDirectory} from '../helpers/fixtures-directory.js';4import {foobarString} from '../helpers/input.js';5import {subprocessSendGetOne, subprocessExchange} from '../helpers/ipc.js';67setFixtureDirectory();88test('Can exchange IPC messages', async t => {9const testExchange = async (t, exchangeMethod) => {10 const subprocess = execa('ipc-echo.js', {ipc: true});10 await subprocess.sendMessage(foobarString);11 t.is(await subprocess.getOneMessage(), foobarString);11 t.is(await exchangeMethod(subprocess, foobarString), foobarString);12 await subprocess;13});13};1415const HIGH_CONCURRENCY_COUNT = 100;15test('Can exchange IPC messages', testExchange, subprocessSendGetOne);16test('Can exchange IPC messages, exchangeMessage()', testExchange, subprocessExchange);1717test.serial('Can exchange IPC messages under heavy load', async t => {18const HIGH_CONCURRENCY_COUNT = 10;1920const testHeavyLoad = async (t, exchangeMethod) => {21 await Promise.all(22 Array.from({length: HIGH_CONCURRENCY_COUNT}, async (_, index) => {23 const subprocess = execa('ipc-echo.js', {ipc: true});21 await subprocess.sendMessage(index);22 t.is(await subprocess.getOneMessage(), index);24 t.is(await exchangeMethod(subprocess, index), index);25 await subprocess;26 }),27 );26});28};2928test('Can use "serialization: json" option', async t => {30test.serial('Can exchange IPC messages under heavy load', testHeavyLoad, subprocessSendGetOne);31test.serial('Can exchange IPC messages under heavy load, exchangeMessage()', testHeavyLoad, subprocessExchange);3233const testDefaultSerialization = async (t, exchangeMethod) => {34 const subprocess = execa('ipc-echo.js', {ipc: true});35 const message = await exchangeMethod(subprocess, [0n]);36 t.is(message[0], 0n);37 await subprocess;38};3940test('The "serialization" option defaults to "advanced"', testDefaultSerialization, subprocessSendGetOne);41test('The "serialization" option defaults to "advanced", exchangeMessage()', testDefaultSerialization, subprocessExchange);4243const testJsonSerialization = async (t, exchangeMethod) => {44 const subprocess = execa('ipc-echo.js', {ipc: true, serialization: 'json'});45 const date = new Date();31 await subprocess.sendMessage(date);32 t.is(await subprocess.getOneMessage(), date.toJSON());46 t.is(await exchangeMethod(subprocess, date), date.toJSON());47 await subprocess;34});48};4950test('Can use "serialization: json" option', testJsonSerialization, subprocessSendGetOne);51test('Can use "serialization: json" option, exchangeMessage()', testJsonSerialization, subprocessExchange);5253const testJsonError = async (t, exchangeMethod) => {54 const subprocess = execa('ipc-echo.js', {ipc: true, serialization: 'json'});55 await t.throwsAsync(exchangeMethod(subprocess, [0n]), {message: /serialize a BigInt/});56 await t.throwsAsync(subprocess);57};5859test('Validates JSON payload with serialization: "json"', testJsonError, subprocessSendGetOne);60test('Validates JSON payload with serialization: "json", exchangeMessage()', testJsonError, subprocessExchange);6162const BIG_PAYLOAD_SIZE = '.'.repeat(1e6);6338test('Handles backpressure', async t => {64const testBackpressure = async (t, exchangeMethod) => {65 const subprocess = execa('ipc-iterate.js', {ipc: true});40 await subprocess.sendMessage(BIG_PAYLOAD_SIZE);66 await exchangeMethod(subprocess, BIG_PAYLOAD_SIZE);67 t.true(subprocess.send(foobarString));68 const {ipcOutput} = await subprocess;69 t.deepEqual(ipcOutput, [BIG_PAYLOAD_SIZE]);44});70};7146test('Disconnects IPC on exports.sendMessage() error', async t => {72test('Handles backpressure', testBackpressure, subprocessSendGetOne);73test('Handles backpressure, exchangeMessage()', testBackpressure, subprocessExchange);7475const testParentDisconnect = async (t, methodName) => {76 const subprocess = execa('ipc-echo-twice.js', {ipc: true});48 await subprocess.sendMessage(foobarString);49 t.is(await subprocess.getOneMessage(), foobarString);77 t.is(await subprocess.exchangeMessage(foobarString), foobarString);7851 await t.throwsAsync(subprocess.sendMessage(0n), {52 message: /subprocess.sendMessage\(\)'s argument type is invalid/,53 });79 const {message} = await t.throwsAsync(subprocess[methodName](0n));80 t.true(message.includes(`subprocess.${methodName}()'s argument type is invalid`));8182 const {exitCode, isTerminated, stderr} = await t.throwsAsync(subprocess);83 t.is(exitCode, 1);84 t.false(isTerminated);58 t.true(stderr.includes('Error: getOneMessage() could not complete'));59});85 t.true(stderr.includes('Error: exchangeMessage() could not complete'));86};8761test('Disconnects IPC on subprocess.sendMessage() error', async t => {62 const subprocess = execa('ipc-send-error.js', {ipc: true});88test('Disconnects IPC on exports.sendMessage() error', testParentDisconnect, 'sendMessage');89test('Disconnects IPC on exports.exchangeMessage() error', testParentDisconnect, 'exchangeMessage');9091const testSubprocessDisconnect = async (t, methodName, fixtureName) => {92 const subprocess = execa(fixtureName, {ipc: true});93 const ipcError = await t.throwsAsync(subprocess.getOneMessage());94 t.true(ipcError.message.includes('subprocess.getOneMessage() could not complete'));9596 const {exitCode, isTerminated, stderr} = await t.throwsAsync(subprocess);97 t.is(exitCode, 1);98 t.false(isTerminated);69 t.true(stderr.includes('sendMessage()\'s argument type is invalid'));70});99 t.true(stderr.includes(`${methodName}()'s argument type is invalid`));100};10172test('The "serialization" option defaults to "advanced"', async t => {73 const subprocess = execa('ipc-echo.js', {ipc: true});74 await subprocess.sendMessage([0n]);75 const message = await subprocess.getOneMessage();76 t.is(message[0], 0n);77 await subprocess;78});7980test('The "serialization" option can be set to "json"', async t => {81 const subprocess = execa('ipc-echo.js', {ipc: true, serialization: 'json'});82 await t.throwsAsync(subprocess.sendMessage([0n]), {message: /serialize a BigInt/});83 await t.throwsAsync(subprocess);84});102test('Disconnects IPC on subprocess.sendMessage() error', testSubprocessDisconnect, 'sendMessage', 'ipc-send-error.js');103test('Disconnects IPC on subprocess.exchangeMessage() error', testSubprocessDisconnect, 'exchangeMessage', 'ipc-exchange-error.js');
modified:test/ipc/validation.js+43 added-21 removed
19 unmodified lines
20test('Cannot use subprocess.sendMessage() with stdio: [..., "ipc"]', testRequiredIpcSubprocess, 'sendMessage', stdioIpc);21test('Cannot use subprocess.getOneMessage() without ipc option', testRequiredIpcSubprocess, 'getOneMessage', {});22test('Cannot use subprocess.getOneMessage() with ipc: false', testRequiredIpcSubprocess, 'getOneMessage', {ipc: false});23test('Cannot use subprocess.getOneMessage() with stdio: [..., "ipc"]', testRequiredIpcSubprocess, 'getOneMessage', stdioIpc);24test('Cannot use subprocess.exchangeMessage() without ipc option', testRequiredIpcSubprocess, 'exchangeMessage', {});25test('Cannot use subprocess.exchangeMessage() with ipc: false', testRequiredIpcSubprocess, 'exchangeMessage', {ipc: false});26test('Cannot use subprocess.exchangeMessage() with stdio: [..., "ipc"]', testRequiredIpcSubprocess, 'exchangeMessage', stdioIpc);27test('Cannot use subprocess.getEachMessage() without ipc option', testRequiredIpcSubprocess, 'getEachMessage', {});28test('Cannot use subprocess.getEachMessage() with ipc: false', testRequiredIpcSubprocess, 'getEachMessage', {ipc: false});29test('Cannot use subprocess.getEachMessage() with stdio: [..., "ipc"]', testRequiredIpcSubprocess, 'getEachMessage', stdioIpc);30
5 unmodified lines
36test('Cannot use exports.sendMessage() without ipc option', testRequiredIpcExports, 'sendMessage', {});37test('Cannot use exports.sendMessage() with ipc: false', testRequiredIpcExports, 'sendMessage', {ipc: false});38test('Cannot use exports.getOneMessage() without ipc option', testRequiredIpcExports, 'getOneMessage', {});39test('Cannot use exports.getOneMessage() with ipc: false', testRequiredIpcExports, 'getOneMessage', {ipc: false});40test('Cannot use exports.exchangeMessage() without ipc option', testRequiredIpcExports, 'exchangeMessage', {});41test('Cannot use exports.exchangeMessage() with ipc: false', testRequiredIpcExports, 'exchangeMessage', {ipc: false});42test('Cannot use exports.getEachMessage() without ipc option', testRequiredIpcExports, 'getEachMessage', {});43test('Cannot use exports.getEachMessage() with ipc: false', testRequiredIpcExports, 'getEachMessage', {ipc: false});4445const testPostDisconnection = async (t, methodName) => {
4 unmodified lines
50};5152test('subprocess.sendMessage() after disconnection', testPostDisconnection, 'sendMessage');53test('subprocess.getOneMessage() after disconnection', testPostDisconnection, 'getOneMessage');54test('subprocess.exchangeMessage() after disconnection', testPostDisconnection, 'exchangeMessage');55test('subprocess.getEachMessage() after disconnection', testPostDisconnection, 'getEachMessage');5657const testPostDisconnectionSubprocess = async (t, methodName) => {58 const subprocess = execa('ipc-disconnect.js', [methodName], {ipc: true});
3 unmodified lines
62};6364test('exports.sendMessage() after disconnection', testPostDisconnectionSubprocess, 'sendMessage');65test('exports.getOneMessage() after disconnection', testPostDisconnectionSubprocess, 'getOneMessage');66test('exports.exchangeMessage() after disconnection', testPostDisconnectionSubprocess, 'exchangeMessage');67test('exports.getEachMessage() after disconnection', testPostDisconnectionSubprocess, 'getEachMessage');6862const testInvalidPayload = async (t, serialization, message) => {69const testInvalidPayload = async (t, methodName, serialization, message) => {70 const subprocess = execa('empty.js', {ipc: true, serialization});64 await t.throwsAsync(subprocess.sendMessage(message), {message: /type is invalid/});71 await t.throwsAsync(subprocess[methodName](message), {message: /type is invalid/});72 await subprocess;73};7475const cycleObject = {};76cycleObject.self = cycleObject;77const toJsonCycle = {toJSON: () => ({test: true, toJsonCycle})};7872test('subprocess.sendMessage() cannot send undefined', testInvalidPayload, 'advanced', undefined);73test('subprocess.sendMessage() cannot send bigints', testInvalidPayload, 'advanced', 0n);74test('subprocess.sendMessage() cannot send symbols', testInvalidPayload, 'advanced', Symbol('test'));75test('subprocess.sendMessage() cannot send functions', testInvalidPayload, 'advanced', () => {});76test('subprocess.sendMessage() cannot send promises', testInvalidPayload, 'advanced', Promise.resolve());77test('subprocess.sendMessage() cannot send proxies', testInvalidPayload, 'advanced', new Proxy({}, {}));78test('subprocess.sendMessage() cannot send Intl', testInvalidPayload, 'advanced', new Intl.Collator());79test('subprocess.sendMessage() cannot send undefined, JSON', testInvalidPayload, 'json', undefined);80test('subprocess.sendMessage() cannot send bigints, JSON', testInvalidPayload, 'json', 0n);81test('subprocess.sendMessage() cannot send symbols, JSON', testInvalidPayload, 'json', Symbol('test'));82test('subprocess.sendMessage() cannot send functions, JSON', testInvalidPayload, 'json', () => {});83test('subprocess.sendMessage() cannot send cycles, JSON', testInvalidPayload, 'json', cycleObject);84test('subprocess.sendMessage() cannot send cycles in toJSON(), JSON', testInvalidPayload, 'json', toJsonCycle);79test('subprocess.sendMessage() cannot send undefined', testInvalidPayload, 'sendMessage', 'advanced', undefined);80test('subprocess.sendMessage() cannot send bigints', testInvalidPayload, 'sendMessage', 'advanced', 0n);81test('subprocess.sendMessage() cannot send symbols', testInvalidPayload, 'sendMessage', 'advanced', Symbol('test'));82test('subprocess.sendMessage() cannot send functions', testInvalidPayload, 'sendMessage', 'advanced', () => {});83test('subprocess.sendMessage() cannot send promises', testInvalidPayload, 'sendMessage', 'advanced', Promise.resolve());84test('subprocess.sendMessage() cannot send proxies', testInvalidPayload, 'sendMessage', 'advanced', new Proxy({}, {}));85test('subprocess.sendMessage() cannot send Intl', testInvalidPayload, 'sendMessage', 'advanced', new Intl.Collator());86test('subprocess.sendMessage() cannot send undefined, JSON', testInvalidPayload, 'sendMessage', 'json', undefined);87test('subprocess.sendMessage() cannot send bigints, JSON', testInvalidPayload, 'sendMessage', 'json', 0n);88test('subprocess.sendMessage() cannot send symbols, JSON', testInvalidPayload, 'sendMessage', 'json', Symbol('test'));89test('subprocess.sendMessage() cannot send functions, JSON', testInvalidPayload, 'sendMessage', 'json', () => {});90test('subprocess.sendMessage() cannot send cycles, JSON', testInvalidPayload, 'sendMessage', 'json', cycleObject);91test('subprocess.sendMessage() cannot send cycles in toJSON(), JSON', testInvalidPayload, 'sendMessage', 'json', toJsonCycle);92test('subprocess.exchangeMessage() cannot send undefined', testInvalidPayload, 'exchangeMessage', 'advanced', undefined);93test('subprocess.exchangeMessage() cannot send bigints', testInvalidPayload, 'exchangeMessage', 'advanced', 0n);94test('subprocess.exchangeMessage() cannot send symbols', testInvalidPayload, 'exchangeMessage', 'advanced', Symbol('test'));95test('subprocess.exchangeMessage() cannot send functions', testInvalidPayload, 'exchangeMessage', 'advanced', () => {});96test('subprocess.exchangeMessage() cannot send promises', testInvalidPayload, 'exchangeMessage', 'advanced', Promise.resolve());97test('subprocess.exchangeMessage() cannot send proxies', testInvalidPayload, 'exchangeMessage', 'advanced', new Proxy({}, {}));98test('subprocess.exchangeMessage() cannot send Intl', testInvalidPayload, 'exchangeMessage', 'advanced', new Intl.Collator());99test('subprocess.exchangeMessage() cannot send undefined, JSON', testInvalidPayload, 'exchangeMessage', 'json', undefined);100test('subprocess.exchangeMessage() cannot send bigints, JSON', testInvalidPayload, 'exchangeMessage', 'json', 0n);101test('subprocess.exchangeMessage() cannot send symbols, JSON', testInvalidPayload, 'exchangeMessage', 'json', Symbol('test'));102test('subprocess.exchangeMessage() cannot send functions, JSON', testInvalidPayload, 'exchangeMessage', 'json', () => {});103test('subprocess.exchangeMessage() cannot send cycles, JSON', testInvalidPayload, 'exchangeMessage', 'json', cycleObject);104test('subprocess.exchangeMessage() cannot send cycles in toJSON(), JSON', testInvalidPayload, 'exchangeMessage', 'json', toJsonCycle);10586test('exports.sendMessage() validates payload', async t => {87 const subprocess = execa('ipc-echo-item.js', {ipc: true});106const testSubprocessInvalidPayload = async (t, methodName, fixtureName) => {107 const subprocess = execa(fixtureName, {ipc: true});108 await subprocess.sendMessage([undefined]);89 await t.throwsAsync(subprocess, {90 message: /sendMessage\(\)'s argument type is invalid/,91 });92});109 const {message} = await t.throwsAsync(subprocess);110 t.true(message.includes(`${methodName}()'s argument type is invalid`));111};112113test('exports.sendMessage() validates payload', testSubprocessInvalidPayload, 'sendMessage', 'ipc-echo-item.js');114test('exports.exchangeMessage() validates payload', testSubprocessInvalidPayload, 'exchangeMessage', 'ipc-echo-item-exchange.js');
modified:test/methods/node.js+1 added-2 removed
223 unmodified lines
224225const testIpc = async (t, execaMethod, options) => {226 const subprocess = execaMethod('ipc-echo.js', [], options);227228 await subprocess.sendMessage(foobarString);229 t.is(await subprocess.getOneMessage(), foobarString);228 t.is(await subprocess.exchangeMessage(foobarString), foobarString);229230 const {stdio} = await subprocess;231 t.is(stdio.length, 4);232 t.is(stdio[3], undefined);
55 unmodified lines
added:test-d/ipc/exchange.test-d.ts+65 added
1import {expectType, expectError} from 'tsd';2import {3 exchangeMessage,4 execa,5 type Message,6 type Options,7} from '../../index.js';89const subprocess = execa('test', {ipc: true});10expectType<Promise<Message<'advanced'>>>(subprocess.exchangeMessage(''));11const jsonSubprocess = execa('test', {ipc: true, serialization: 'json'});12expectType<Promise<Message<'json'>>>(jsonSubprocess.exchangeMessage(''));13expectType<Promise<Message>>(exchangeMessage(''));1415expectError(await subprocess.exchangeMessage());16expectError(await exchangeMessage());17expectError(await subprocess.exchangeMessage(undefined));18expectError(await exchangeMessage(undefined));19expectError(await subprocess.exchangeMessage(0n));20expectError(await exchangeMessage(0n));21expectError(await subprocess.exchangeMessage(Symbol('test')));22expectError(await exchangeMessage(Symbol('test')));23expectError(await subprocess.exchangeMessage('', ''));24expectError(await exchangeMessage('', ''));25expectError(await subprocess.exchangeMessage('', {}, ''));26expectError(await exchangeMessage('', {}, ''));2728await execa('test', {ipcInput: ''}).exchangeMessage('');29await execa('test', {ipcInput: '' as Message}).exchangeMessage('');30await execa('test', {} as Options).exchangeMessage?.('');31await execa('test', {ipc: true as boolean}).exchangeMessage?.('');32await execa('test', {ipcInput: '' as '' | undefined}).exchangeMessage?.('');3334expectType<undefined>(execa('test').exchangeMessage);35expectType<undefined>(execa('test', {}).exchangeMessage);36expectType<undefined>(execa('test', {ipc: false}).exchangeMessage);37expectType<undefined>(execa('test', {ipcInput: undefined}).exchangeMessage);38expectType<undefined>(execa('test', {ipc: false, ipcInput: ''}).exchangeMessage);3940await subprocess.exchangeMessage('', {filter: undefined} as const);41await subprocess.exchangeMessage('', {filter: (message: Message<'advanced'>) => true} as const);42await jsonSubprocess.exchangeMessage('', {filter: (message: Message<'json'>) => true} as const);43await jsonSubprocess.exchangeMessage('', {filter: (message: Message<'advanced'>) => true} as const);44await subprocess.exchangeMessage('', {filter: (message: Message<'advanced'> | bigint) => true} as const);45await subprocess.exchangeMessage('', {filter: () => true} as const);46expectError(await subprocess.exchangeMessage('', {filter: (message: Message<'advanced'>) => ''} as const));47// eslint-disable-next-line @typescript-eslint/no-empty-function48expectError(await subprocess.exchangeMessage('', {filter(message: Message<'advanced'>) {}} as const));49expectError(await subprocess.exchangeMessage('', {filter: (message: Message<'json'>) => true} as const));50expectError(await subprocess.exchangeMessage('', {filter: (message: '') => true} as const));51expectError(await subprocess.exchangeMessage('', {filter: true} as const));52expectError(await subprocess.exchangeMessage('', {unknownOption: true} as const));5354await exchangeMessage('', {filter: undefined} as const);55await exchangeMessage('', {filter: (message: Message) => true} as const);56await exchangeMessage('', {filter: (message: Message<'advanced'>) => true} as const);57await exchangeMessage('', {filter: (message: Message | bigint) => true} as const);58await exchangeMessage('', {filter: () => true} as const);59expectError(await exchangeMessage('', {filter: (message: Message) => ''} as const));60// eslint-disable-next-line @typescript-eslint/no-empty-function61expectError(await exchangeMessage('', {filter(message: Message) {}} as const));62expectError(await exchangeMessage('', {filter: (message: Message<'json'>) => true} as const));63expectError(await exchangeMessage('', {filter: (message: '') => true} as const));64expectError(await exchangeMessage('', {filter: true} as const));65expectError(await exchangeMessage('', {unknownOption: true} as const));
modified:test-d/ipc/get-one.test-d.ts+2 added
12 unmodified lines
13expectType<Promise<Message>>(getOneMessage());1415expectError(await subprocess.getOneMessage(''));16expectError(await getOneMessage(''));17expectError(await subprocess.getOneMessage({}, ''));18expectError(await getOneMessage({}, ''));1920await execa('test', {ipcInput: ''}).getOneMessage();21await execa('test', {ipcInput: '' as Message}).getOneMessage();22await execa('test', {} as Options).getOneMessage?.();
35 unmodified lines
modified:test-d/ipc/message.test-d.ts+27 added-1 removed
1import {File} from 'node:buffer';2import {expectAssignable, expectNotAssignable} from 'tsd';3import {sendMessage, type Message} from '../../index.js';3import {sendMessage, exchangeMessage, type Message} from '../../index.js';45await sendMessage('');6await exchangeMessage('');7expectAssignable<Message>('');8expectAssignable<Message<'advanced'>>('');9expectAssignable<Message<'json'>>('');1011await sendMessage(0);12await exchangeMessage(0);13expectAssignable<Message>(0);14expectAssignable<Message<'advanced'>>(0);15expectAssignable<Message<'json'>>(0);1617await sendMessage(true);18await exchangeMessage(true);19expectAssignable<Message>(true);20expectAssignable<Message<'advanced'>>(true);21expectAssignable<Message<'json'>>(true);2223await sendMessage([] as const);24await exchangeMessage([] as const);25expectAssignable<Message>([] as const);26expectAssignable<Message<'advanced'>>([] as const);27expectAssignable<Message<'json'>>([] as const);2829await sendMessage([true] as const);30await exchangeMessage([true] as const);31expectAssignable<Message>([true] as const);32expectAssignable<Message<'advanced'>>([true] as const);33expectAssignable<Message<'json'>>([true] as const);3435await sendMessage([undefined] as const);36await exchangeMessage([undefined] as const);37expectAssignable<Message>([undefined] as const);38expectAssignable<Message<'advanced'>>([undefined] as const);39expectNotAssignable<Message<'json'>>([undefined] as const);4041await sendMessage([0n] as const);42await exchangeMessage([0n] as const);43expectAssignable<Message>([0n] as const);44expectAssignable<Message<'advanced'>>([0n] as const);45expectNotAssignable<Message<'json'>>([0n] as const);4647await sendMessage({} as const);48await exchangeMessage({} as const);49expectAssignable<Message>({} as const);50expectAssignable<Message<'advanced'>>({} as const);51expectAssignable<Message<'json'>>({} as const);5253await sendMessage({test: true} as const);54await exchangeMessage({test: true} as const);55expectAssignable<Message>({test: true} as const);56expectAssignable<Message<'advanced'>>({test: true} as const);57expectAssignable<Message<'json'>>({test: true} as const);5859await sendMessage({test: undefined} as const);60await exchangeMessage({test: undefined} as const);61expectAssignable<Message>({test: undefined} as const);62expectAssignable<Message<'advanced'>>({test: undefined} as const);63expectNotAssignable<Message<'json'>>({test: undefined} as const);6465await sendMessage({test: 0n} as const);66await exchangeMessage({test: 0n} as const);67expectAssignable<Message>({test: 0n} as const);68expectAssignable<Message<'advanced'>>({test: 0n} as const);69expectNotAssignable<Message<'json'>>({test: 0n} as const);7071await sendMessage(null);72await exchangeMessage(null);73expectAssignable<Message>(null);74expectAssignable<Message<'advanced'>>(null);75expectAssignable<Message<'json'>>(null);7677await sendMessage(Number.NaN);78await exchangeMessage(Number.NaN);79expectAssignable<Message>(Number.NaN);80expectAssignable<Message<'advanced'>>(Number.NaN);81expectAssignable<Message<'json'>>(Number.NaN);8283await sendMessage(Number.POSITIVE_INFINITY);84await exchangeMessage(Number.POSITIVE_INFINITY);85expectAssignable<Message>(Number.POSITIVE_INFINITY);86expectAssignable<Message<'advanced'>>(Number.POSITIVE_INFINITY);87expectAssignable<Message<'json'>>(Number.POSITIVE_INFINITY);8889await sendMessage(new Map());90await exchangeMessage(new Map());91expectAssignable<Message>(new Map());92expectAssignable<Message<'advanced'>>(new Map());93expectNotAssignable<Message<'json'>>(new Map());9495await sendMessage(new Set());96await exchangeMessage(new Set());97expectAssignable<Message>(new Set());98expectAssignable<Message<'advanced'>>(new Set());99expectNotAssignable<Message<'json'>>(new Set());100101await sendMessage(new Date());102await exchangeMessage(new Date());103expectAssignable<Message>(new Date());104expectAssignable<Message<'advanced'>>(new Date());105expectNotAssignable<Message<'json'>>(new Date());106107await sendMessage(/regexp/);108await exchangeMessage(/regexp/);109expectAssignable<Message>(/regexp/);110expectAssignable<Message<'advanced'>>(/regexp/);111expectNotAssignable<Message<'json'>>(/regexp/);112113await sendMessage(new Blob());114await exchangeMessage(new Blob());115expectAssignable<Message>(new Blob());116expectAssignable<Message<'advanced'>>(new Blob());117expectNotAssignable<Message<'json'>>(new Blob());118119await sendMessage(new File([], ''));120await exchangeMessage(new File([], ''));121expectAssignable<Message>(new File([], ''));122expectAssignable<Message<'advanced'>>(new File([], ''));123expectNotAssignable<Message<'json'>>(new File([], ''));124125await sendMessage(new DataView(new ArrayBuffer(0)));126await exchangeMessage(new DataView(new ArrayBuffer(0)));127expectAssignable<Message>(new DataView(new ArrayBuffer(0)));128expectAssignable<Message<'advanced'>>(new DataView(new ArrayBuffer(0)));129expectNotAssignable<Message<'json'>>(new DataView(new ArrayBuffer(0)));130131await sendMessage(new ArrayBuffer(0));132await exchangeMessage(new ArrayBuffer(0));133expectAssignable<Message>(new ArrayBuffer(0));134expectAssignable<Message<'advanced'>>(new ArrayBuffer(0));135expectNotAssignable<Message<'json'>>(new ArrayBuffer(0));136137await sendMessage(new SharedArrayBuffer(0));138await exchangeMessage(new SharedArrayBuffer(0));139expectAssignable<Message>(new SharedArrayBuffer(0));140expectAssignable<Message<'advanced'>>(new SharedArrayBuffer(0));141expectNotAssignable<Message<'json'>>(new SharedArrayBuffer(0));142143await sendMessage(new Uint8Array());144await exchangeMessage(new Uint8Array());145expectAssignable<Message>(new Uint8Array());146expectAssignable<Message<'advanced'>>(new Uint8Array());147expectNotAssignable<Message<'json'>>(new Uint8Array());148149await sendMessage(AbortSignal.abort());150await exchangeMessage(AbortSignal.abort());151expectAssignable<Message>(AbortSignal.abort());152expectAssignable<Message<'advanced'>>(AbortSignal.abort());153expectNotAssignable<Message<'json'>>(AbortSignal.abort());154155await sendMessage(new Error('test'));156await exchangeMessage(new Error('test'));157expectAssignable<Message>(new Error('test'));158expectAssignable<Message<'advanced'>>(new Error('test'));159expectNotAssignable<Message<'json'>>(new Error('test'));
modified:types/arguments/options.d.ts+1 added-1 removed
197 unmodified lines
198 */199 readonly buffer?: FdGenericOption<boolean>;200201 /**202 Enables exchanging messages with the subprocess using `subprocess.sendMessage(message)`, `subprocess.getOneMessage()` and `subprocess.getEachMessage()`.202 Enables exchanging messages with the subprocess using `subprocess.sendMessage(message)`, `subprocess.getOneMessage()`, `subprocess.exchangeMessage(message)` and `subprocess.getEachMessage()`.203204 The subprocess must be a Node.js file.205206 @default `true` if either the `node` option or the `ipcInput` option is set, `false` otherwise
176 unmodified lines
modified:types/methods/main-async.d.ts+6 added-6 removed
185 unmodified lines
186// parent.js187import {execaNode} from 'execa';188189const subprocess = execaNode`child.js`;190console.log(await subprocess.getOneMessage()); // 'Hello from child'191await subprocess.sendMessage('Hello from parent');192const result = await subprocess;190const message = await subprocess.exchangeMessage('Hello from parent');191console.log(message); // 'Hello from child'192```193194```195// child.js197import {sendMessage, getOneMessage} from 'execa';196import {getOneMessage, sendMessage} from 'execa';197199await sendMessage('Hello from child');200console.log(await getOneMessage()); // 'Hello from parent'198const message = await getOneMessage(); // 'Hello from parent'199const newMessage = message.replace('parent', 'child'); // 'Hello from child'200await sendMessage(newMessage);201```202203@example <caption>Any input type</caption>204
105 unmodified lines
modified:types/ipc.d.ts+17 added-2 removed
16 unmodified lines
17 | readonly JsonMessage[]18 | {readonly [key: string | number]: JsonMessage};1920/**21Type of messages exchanged between a process and its subprocess using `sendMessage()`, `getOneMessage()` and `getEachMessage()`.21Type of messages exchanged between a process and its subprocess using `sendMessage()`, `getOneMessage()`, `exchangeMessage()` and `getEachMessage()`.2223This requires the `ipc` option to be `true`. The type of `message` depends on the `serialization` option.24*/25export type Message<26 Serialization extends Options['serialization'] = Options['serialization'],27> = Serialization extends 'json' ? JsonMessage : AdvancedMessage;2829/**30Options to `getOneMessage()` and `subprocess.getOneMessage()`30Options to `getOneMessage()`, `exchangeMessage()`, `subprocess.getOneMessage()` and `subprocess.exchangeMessage()`31*/32type GetOneMessageOptions<33 Serialization extends Options['serialization'],34> = {
18 unmodified lines
53*/54export function getOneMessage(getOneMessageOptions?: GetOneMessageOptions<Options['serialization']>): Promise<Message>;5556/**57Send a `message` to the parent process, then receive a response from it.5859This requires the `ipc` option to be `true`. The type of `message` depends on the `serialization` option.60*/61export function exchangeMessage(message: Message, getOneMessageOptions?: GetOneMessageOptions<Options['serialization']>): Promise<Message>;6263/**64Iterate over each `message` from the parent process.6566This requires the `ipc` option to be `true`. The type of `message` depends on the `serialization` option.67*/
19 unmodified lines
87 */88 getOneMessage(getOneMessageOptions?: GetOneMessageOptions<Serialization>): Promise<Message<Serialization>>;8990 /**91 Send a `message` to the subprocess, then receive a response from it.9293 This requires the `ipc` option to be `true`. The type of `message` depends on the `serialization` option.94 */95 exchangeMessage(message: Message<Serialization>, getOneMessageOptions?: GetOneMessageOptions<Serialization>): Promise<Message<Serialization>>;9697 /**98 Iterate over each `message` from the subprocess.99100 This requires the `ipc` option to be `true`. The type of `message` depends on the `serialization` option.101 */
4 unmodified lines
106 // At type check time, they are typed as `undefined` to prevent calling them.107 : {108 sendMessage: undefined;109 getOneMessage: undefined;110 exchangeMessage: undefined;111 getEachMessage: undefined;112 };113114// Whether IPC is enabled, based on the `ipc` and `ipcInput` options
15 unmodified lines
modified:index.d.ts+1 added
18 unmodified lines
1920export {21 sendMessage,22 getOneMessage,23 exchangeMessage,24 getEachMessage,25 type Message,26} from './types/ipc.js';
modified:index.js+12 added-2 removed
12 unmodified lines
13export const execaCommandSync = createExeca(mapCommandSync);14export const execaNode = createExeca(mapNode);15export const $ = createExeca(mapScriptAsync, {}, deepScriptOptions, setScriptSync);1617const {sendMessage, getOneMessage, getEachMessage} = getIpcExport();18export {sendMessage, getOneMessage, getEachMessage};17const {18 sendMessage,19 getOneMessage,20 exchangeMessage,21 getEachMessage,22} = getIpcExport();23export {24 sendMessage,25 getOneMessage,26 exchangeMessage,27 getEachMessage,28};
modified:readme.md+6 added-6 removed
268 unmodified lines
269// parent.js270import {execaNode} from 'execa';271272const subprocess = execaNode`child.js`;273console.log(await subprocess.getOneMessage()); // 'Hello from child'274await subprocess.sendMessage('Hello from parent');275const result = await subprocess;273const message = await subprocess.exchangeMessage('Hello from parent');274console.log(message); // 'Hello from child'275```276277```js278// child.js280import {sendMessage, getOneMessage} from 'execa';279import {getOneMessage, sendMessage} from 'execa';280282await sendMessage('Hello from child');283console.log(await getOneMessage()); // 'Hello from parent'281const message = await getOneMessage(); // 'Hello from parent'282const newMessage = message.replace('parent', 'child'); // 'Hello from child'283await sendMessage(newMessage);284```285286#### Any input type287
104 unmodified lines