Add `filter` option to `getOneMessage()` (#1076)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent ae9b360 · Browse files · 15 files·+215 added−64 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
15 files+215 added−64 removed
- tests:+90 added−31 removed
- other:+125 added−33 removed
Provenance
- Commit
571e052- Tree
cfd0037- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
ae9b360
15 files changed+215 added−64 removed
modified:docs/api.md+17 added-3 removed
101 unmodified lines102 This requires the [`ipc`](#optionsipc) option to be `true`. The [type](ipc.md#message-type) of `message` depends on the [`serialization`](#optionsserialization) option.103 104 [More info.](ipc.md#exchanging-messages)105 106-### getOneMessage()106+### getOneMessage(getOneMessageOptions?)107 108+_getOneMessageOptions_: [`GetOneMessageOptions`](#getonemessageoptions)\109 _Returns_: [`Promise<Message>`](ipc.md#message-type)110 111 Receive a single `message` from the parent process.112 113 This requires the [`ipc`](#optionsipc) option to be `true`. The [type](ipc.md#message-type) of `message` depends on the [`serialization`](#optionsserialization) option.114 115 [More info.](ipc.md#exchanging-messages)116 117+#### getOneMessageOptions118+119+_Type_: `object`120+121+#### getOneMessageOptions.filter122+123+_Type_: [`(Message) => boolean`](ipc.md#message-type)124+125+Ignore any `message` that returns `false`.126+127+[More info.](ipc.md#filter-messages)128+129 ### getEachMessage()130 131 _Returns_: [`AsyncIterable<Message>`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols)132 138 unmodified lines271 This requires the [`ipc`](#optionsipc) option to be `true`. The [type](ipc.md#message-type) of `message` depends on the [`serialization`](#optionsserialization) option.272 273 [More info.](ipc.md#exchanging-messages)274 262-### subprocess.getOneMessage()275+### subprocess.getOneMessage(getOneMessageOptions?)276 277+_getOneMessageOptions_: [`GetOneMessageOptions`](#getonemessageoptions)\278 _Returns_: [`Promise<Message>`](ipc.md#message-type)279 280 Receive a single `message` from the subprocess.281 631 unmodified lines913 914 _Type:_ `boolean`\915 _Default:_ `true` if either the [`node`](#optionsnode) option or the [`ipcInput`](#optionsipcinput) is set, `false` otherwise916 903-Enables exchanging messages with the subprocess using [`subprocess.sendMessage(message)`](#subprocesssendmessagemessage), [`subprocess.getOneMessage()`](#subprocessgetonemessage) and [`subprocess.getEachMessage()`](#subprocessgeteachmessage).917+Enables exchanging messages with the subprocess using [`subprocess.sendMessage(message)`](#subprocesssendmessagemessage), [`subprocess.getOneMessage()`](#subprocessgetonemessagegetonemessageoptions) and [`subprocess.getEachMessage()`](#subprocessgeteachmessage).918 919 The subprocess must be a Node.js file.920 921 [More info.](ipc.md)199 unmodified linesmodified:docs/execution.md+1 added-1 removed
124 unmodified linesExpand all1251261271281291291301311321334 unmodified lines124 unmodified linesExpand all- The [`stdin`](api.md#optionsstdin), [`stdout`](api.md#optionsstdout), [`stderr`](api.md#optionsstderr) and [`stdio`](api.md#optionsstdio) options cannot be [`'overlapped'`](api.md#optionsstdout), an [async iterable](lines.md#progressive-splitting), an async [transform](transform.md), a [`Duplex`](transform.md#duplextransform-streams), nor a [web stream](streams.md#web-streams). Node.js streams can be passed but only if either they [have a file descriptor](streams.md#file-descriptors), or the [`input`](api.md#optionsinput) option is used.- Signal termination: [`subprocess.kill()`](api.md#subprocesskillerror), [`subprocess.pid`](api.md#subprocesspid), [`cleanup`](api.md#optionscleanup) option, [`cancelSignal`](api.md#optionscancelsignal) option, [`forceKillAfterDelay`](api.md#optionsforcekillafterdelay) option.- Piping multiple subprocesses: [`subprocess.pipe()`](api.md#subprocesspipefile-arguments-options).- [`subprocess.iterable()`](lines.md#progressive-splitting).- [IPC](ipc.md): [`sendMessage()`](api.md#sendmessagemessage), [`getOneMessage()`](api.md#getonemessage), [`getEachMessage()`](api.md#geteachmessage), [`result.ipcOutput`](output.md#any-output-type), [`ipc`](api.md#optionsipc) option, [`serialization`](api.md#optionsserialization) option, [`ipcInput`](input.md#any-input-type) option.- [IPC](ipc.md): [`sendMessage()`](api.md#sendmessagemessage), [`getOneMessage()`](api.md#getonemessagegetonemessageoptions), [`getEachMessage()`](api.md#geteachmessage), [`result.ipcOutput`](output.md#any-output-type), [`ipc`](api.md#optionsipc) option, [`serialization`](api.md#optionsserialization) option, [`ipcInput`](input.md#any-input-type) option.- [`result.all`](api.md#resultall) is not interleaved.- [`detached`](api.md#optionsdetached) option.- The [`maxBuffer`](api.md#optionsmaxbuffer) option is always measured in bytes, not in characters, [lines](api.md#optionslines) nor [objects](transform.md#object-mode). Also, it ignores transforms and the [`encoding`](api.md#optionsencoding) option.
4 unmodified linesmodified:docs/input.md+1 added-1 removed
90 unmodified lines91 ```92 93 ## Any input type94 95-If the subprocess [uses Node.js](node.md), [almost any type](ipc.md#message-type) can be passed to the subprocess using the [`ipcInput`](ipc.md#send-an-initial-message) option. The subprocess retrieves that input using [`getOneMessage()`](api.md#getonemessage).95+If the subprocess [uses Node.js](node.md), [almost any type](ipc.md#message-type) can be passed to the subprocess using the [`ipcInput`](ipc.md#send-an-initial-message) option. The subprocess retrieves that input using [`getOneMessage()`](api.md#getonemessagegetonemessageoptions).96 97 ```js98 // main.js99 import {execaNode} from 'execa';31 unmodified linesmodified:docs/ipc.md+25 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#subprocessgetonemessage). The subprocess uses [`sendMessage(message)`](api.md#sendmessagemessage) and [`getOneMessage()`](api.md#getonemessage) instead.15+The 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.16 17 ```js18 // parent.js19 import {execaNode} from 'execa';12 unmodified lines32 ```33 34 ## Listening to messages35 36-[`subprocess.getOneMessage()`](api.md#subprocessgetonemessage) and [`getOneMessage()`](api.md#getonemessage) 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.36+[`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.37 38 [`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).39 40 ```js25 unmodified lines66 await sendMessage(message + 1);67 }68 ```69 70+## Filter messages71+72+```js73+import {getOneMessage} from 'execa';74+75+const startMessage = await getOneMessage({76+ filter: message => message.type === 'start',77+});78+```79+80+```js81+import {getEachMessage} from 'execa';82+83+for await (const message of getEachMessage()) {84+ if (message.type === 'start') {85+ // ...86+ }87+}88+```89+90 ## Retrieve all messages91 72-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#subprocessgetonemessage) and [`subprocess.getEachMessage()`](api.md#subprocessgeteachmessage).92+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).93 94 ```js95 // main.js96 import {execaNode} from 'execa';40 unmodified lines137 138 To limit messages to JSON instead, the [`serialization`](api.md#optionsserialization) option can be set to `'json'`.139 140 ```js141+import {execaNode} from 'execa';142+143 const subprocess = execaNode({serialization: 'json'})`child.js`;144 ```145 146 ## Debugging10 unmodified linesmodified:lib/ipc/get-one.js+24 added-7 removed
11234567891010111213141515161718192021221823242521222627282930313233343035363738394041424344454647484950515253545556575859import {once} from 'node:events';import {once, on} from 'node:events';import { validateIpcOption, validateConnection, disconnect, throwOnEarlyDisconnect,} from './validation.js';
// Like `[sub]process.once('message')` but promise-basedexport const getOneMessage = ({anyProcess, isSubprocess, ipc}) => {export const getOneMessage = ({anyProcess, isSubprocess, ipc}, {filter} = {}) => { const methodName = 'getOneMessage'; validateIpcOption(methodName, isSubprocess, ipc); validateConnection(methodName, isSubprocess, anyProcess.channel !== null);
return onceMessage(anyProcess, isSubprocess, methodName); return onceMessage({ anyProcess, isSubprocess, methodName, filter, });};
const onceMessage = async (anyProcess, isSubprocess, methodName) => {const onceMessage = async ({anyProcess, isSubprocess, methodName, filter}) => { const controller = new AbortController(); try { const [message] = await Promise.race([ once(anyProcess, 'message', {signal: controller.signal}), return await Promise.race([ getMessage(anyProcess, filter, controller), throwOnDisconnect({ anyProcess, isSubprocess, methodName, controller, }), ]); return message; } catch (error) { disconnect(anyProcess); throw error; } finally { controller.abort(); }};
const getMessage = async (anyProcess, filter, {signal}) => { if (filter === undefined) { const [message] = await once(anyProcess, 'message', {signal}); return message; }
for await (const [message] of on(anyProcess, 'message', {signal})) { if (filter(message)) { return message; } }};
const throwOnDisconnect = async ({anyProcess, isSubprocess, methodName, controller: {signal}}) => { await once(anyProcess, 'disconnect', {signal}); throwOnEarlyDisconnect(methodName, isSubprocess);};added:test/fixtures/ipc-echo-filter.js+5 added
12345#!/usr/bin/env nodeimport {sendMessage, getOneMessage} from '../../index.js';import {foobarArray} from '../helpers/input.js';
await sendMessage(await getOneMessage(({filter: message => message === foobarArray[1]})));added:test/fixtures/ipc-echo-twice-filter.js+8 added
12345678#!/usr/bin/env nodeimport {sendMessage, getOneMessage} from '../../index.js';import {alwaysPass} from '../helpers/ipc.js';
const message = await getOneMessage({filter: alwaysPass});const secondMessagePromise = getOneMessage({filter: alwaysPass});await sendMessage(message);await sendMessage(await secondMessagePromise);added:test/fixtures/ipc-process-error-filter.js+11 added
1+#!/usr/bin/env node2+import process from 'node:process';3+import {getOneMessage} from '../../index.js';4+import {foobarString} from '../helpers/input.js';5+import {alwaysPass} from '../helpers/ipc.js';6+7+const cause = new Error(foobarString);8+await Promise.all([9+ getOneMessage({filter: alwaysPass}),10+ process.emit('error', cause),11+]);modified:test/helpers/ipc.js+2 added
5 unmodified lines6 }7 8 return messages;9 };10+11+export const alwaysPass = () => true;modified:test/ipc/buffer-messages.js+11 added
54 unmodified lines55 test('Sets empty error.ipcOutput, sync', t => {56 const {ipcOutput} = t.throws(() => execaSync('fail.js'));57 t.deepEqual(ipcOutput, []);58 });59+60+test('"error" event interrupts result.ipcOutput', async t => {61+ const subprocess = execa('ipc-echo-twice.js', {ipcInput: foobarString});62+ t.is(await subprocess.getOneMessage(), foobarString);63+64+ const cause = new Error(foobarString);65+ subprocess.emit('error', cause);66+ const error = await t.throwsAsync(subprocess);67+ t.is(error.cause, cause);68+ t.deepEqual(error.ipcOutput, [foobarString]);69+});modified:test/ipc/get-one.js+53 added-31 removed
1 unmodified line2 import {setTimeout} from 'node:timers/promises';3 import test from 'ava';4 import {execa} from '../../index.js';5 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6-import {foobarString} from '../helpers/input.js';7-import {iterateAllMessages} from '../helpers/ipc.js';6+import {foobarString, foobarArray} from '../helpers/input.js';7+import {iterateAllMessages, alwaysPass} from '../helpers/ipc.js';8 9 setFixtureDirectory();10 11 const getOneSubprocessMessage = subprocess => subprocess.getOneMessage();12+const getOneFilteredMessage = subprocess => subprocess.getOneMessage({filter: alwaysPass});13 14 const testKeepAlive = async (t, buffer) => {15 const subprocess = execa('ipc-echo-twice.js', {ipc: true, buffer});16 await subprocess.sendMessage(foobarString);24 unmodified lines41 await subprocess.sendMessage('.');42 await subprocess;43 });44 44-test('Does not buffer initial message to current process, buffer true', async t => {45+test.serial('Does not buffer initial message to current process, buffer true', async t => {46 const subprocess = execa('ipc-send-print.js', {ipc: true});47 const [chunk] = await once(subprocess.stdout, 'data');48 t.is(chunk.toString(), '.');49+ await setTimeout(1e3);48- t.is(await Promise.race([setTimeout(1e3), subprocess.getOneMessage()]), undefined);50+ t.is(await Promise.race([setTimeout(0), subprocess.getOneMessage()]), undefined);51 await subprocess.sendMessage('.');52 const {ipcOutput} = await subprocess;53 t.deepEqual(ipcOutput, [foobarString]);54 });55 56 const HIGH_CONCURRENCY_COUNT = 100;57 58+test('subprocess.getOneMessage() can filter messages', async t => {59+ const subprocess = execa('ipc-send-twice.js', {ipc: true});60+ const message = await subprocess.getOneMessage({filter: message => message === foobarArray[1]});61+ t.is(message, foobarArray[1]);62+63+ const {ipcOutput} = await subprocess;64+ t.deepEqual(ipcOutput, foobarArray);65+});66+67+test('exports.getOneMessage() can filter messages', async t => {68+ const subprocess = execa('ipc-echo-filter.js', {ipc: true});69+ await subprocess.sendMessage(foobarArray[0]);70+ await subprocess.sendMessage(foobarArray[1]);71+72+ const {ipcOutput} = await subprocess;73+ t.deepEqual(ipcOutput, [foobarArray[1]]);74+});75+76 test.serial('Can retrieve initial IPC messages under heavy load, buffer false', async t => {77 await Promise.all(78 Array.from({length: HIGH_CONCURRENCY_COUNT}, async (_, index) => {79 const subprocess = execa('ipc-send-argv.js', [`${index}`], {ipc: true, buffer: false});11 unmodified lines91 }),92 );93 });94 75-const testTwice = async (t, buffer) => {95+const testTwice = async (t, buffer, filter) => {96 const subprocess = execa('ipc-send.js', {ipc: true, buffer});97 t.deepEqual(78- await Promise.all([subprocess.getOneMessage(), subprocess.getOneMessage()]),98+ await Promise.all([subprocess.getOneMessage({filter}), subprocess.getOneMessage({filter})]),99 [foobarString, foobarString],100 );101 await subprocess;102 };103 84-test('subprocess.getOneMessage() can be called twice at the same time, buffer false', testTwice, false);85-test('subprocess.getOneMessage() can be called twice at the same time, buffer true', testTwice, true);104+test('subprocess.getOneMessage() can be called twice at the same time, buffer false', testTwice, false, undefined);105+test('subprocess.getOneMessage() can be called twice at the same time, buffer true', testTwice, true, undefined);106+test('subprocess.getOneMessage() can be called twice at the same time, buffer false, filter', testTwice, false, alwaysPass);107+test('subprocess.getOneMessage() can be called twice at the same time, buffer true, filter', testTwice, true, alwaysPass);108 87-const testCleanupListeners = async (t, buffer) => {109+const testCleanupListeners = async (t, buffer, filter) => {110 const subprocess = execa('ipc-send.js', {ipc: true, buffer});111 const bufferCount = buffer ? 1 : 0;112 113 t.is(subprocess.listenerCount('message'), bufferCount);114 t.is(subprocess.listenerCount('disconnect'), bufferCount);115 94- const promise = subprocess.getOneMessage();116+ const promise = subprocess.getOneMessage({filter});117 t.is(subprocess.listenerCount('message'), bufferCount + 1);118 t.is(subprocess.listenerCount('disconnect'), bufferCount + 1);119 t.is(await promise, foobarString);120 5 unmodified lines126 t.is(subprocess.listenerCount('message'), 0);127 t.is(subprocess.listenerCount('disconnect'), 0);128 };129 108-test('Cleans up subprocess.getOneMessage() listeners, buffer false', testCleanupListeners, false);109-test('Cleans up subprocess.getOneMessage() listeners, buffer true', testCleanupListeners, true);130+test('Cleans up subprocess.getOneMessage() listeners, buffer false', testCleanupListeners, false, undefined);131+test('Cleans up subprocess.getOneMessage() listeners, buffer true', testCleanupListeners, true, undefined);132+test('Cleans up subprocess.getOneMessage() listeners, buffer false, filter', testCleanupListeners, false, alwaysPass);133+test('Cleans up subprocess.getOneMessage() listeners, buffer true, filter', testCleanupListeners, true, alwaysPass);134 111-test('"error" event interrupts result.ipcOutput', async t => {112- const subprocess = execa('ipc-echo-twice.js', {ipcInput: foobarString});113- t.is(await subprocess.getOneMessage(), foobarString);114-115- const cause = new Error(foobarString);116- subprocess.emit('error', cause);117- const error = await t.throwsAsync(subprocess);118- t.is(error.cause, cause);119- t.deepEqual(error.ipcOutput, [foobarString]);120-});121-122-const testParentDisconnect = async (t, buffer) => {123- const subprocess = execa('ipc-echo-twice.js', {ipc: true, buffer});135+const testParentDisconnect = async (t, buffer, filter) => {136+ const fixtureName = filter ? 'ipc-echo-twice-filter.js' : 'ipc-echo-twice.js';137+ const subprocess = execa(fixtureName, {ipc: true, buffer});138 await subprocess.sendMessage(foobarString);139 t.is(await subprocess.getOneMessage(), foobarString);140 141 subprocess.disconnect();5 unmodified lines147 t.true(message.includes('Error: getOneMessage() could not complete'));148 }149 };150 137-test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer false', testParentDisconnect, false);138-test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer true', testParentDisconnect, true);151+test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer false', testParentDisconnect, false, false);152+test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer true', testParentDisconnect, true, false);153+test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer false, filter', testParentDisconnect, false, true);154+test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer true, filter', testParentDisconnect, true, true);155 140-const testSubprocessDisconnect = async (t, buffer) => {156+const testSubprocessDisconnect = async (t, buffer, filter) => {157 const subprocess = execa('empty.js', {ipc: true, buffer});142- await t.throwsAsync(subprocess.getOneMessage(), {158+ await t.throwsAsync(subprocess.getOneMessage({filter}), {159 message: /subprocess\.getOneMessage\(\) could not complete/,160 });161 await subprocess;162 };163 148-test('Subprocess exit interrupts disconnect.getOneMessage(), buffer false', testSubprocessDisconnect, false);149-test('Subprocess exit interrupts disconnect.getOneMessage(), buffer true', testSubprocessDisconnect, true);164+test('Subprocess exit interrupts disconnect.getOneMessage(), buffer false', testSubprocessDisconnect, false, undefined);165+test('Subprocess exit interrupts disconnect.getOneMessage(), buffer true', testSubprocessDisconnect, true, undefined);166+test('Subprocess exit interrupts disconnect.getOneMessage(), buffer false, filter', testSubprocessDisconnect, false, alwaysPass);167+test('Subprocess exit interrupts disconnect.getOneMessage(), buffer true, filter', testSubprocessDisconnect, true, alwaysPass);168 169 const testParentError = async (t, getMessages, useCause, buffer) => {170 const subprocess = execa('ipc-echo.js', {ipc: true, buffer});171 await subprocess.sendMessage(foobarString);15 unmodified lines187 };188 189 test('"error" event interrupts subprocess.getOneMessage(), buffer false', testParentError, getOneSubprocessMessage, false, false);190 test('"error" event interrupts subprocess.getOneMessage(), buffer true', testParentError, getOneSubprocessMessage, false, true);191+test('"error" event interrupts subprocess.getOneMessage(), buffer false, filter', testParentError, getOneFilteredMessage, false, false);192+test('"error" event interrupts subprocess.getOneMessage(), buffer true, filter', testParentError, getOneFilteredMessage, false, true);193 test('"error" event interrupts subprocess.getEachMessage(), buffer false', testParentError, iterateAllMessages, true, false);194 test('"error" event interrupts subprocess.getEachMessage(), buffer true', testParentError, iterateAllMessages, true, true);195 196 const testSubprocessError = async (t, fixtureName, buffer) => {11 unmodified lines208 };209 210 test('"error" event interrupts exports.getOneMessage(), buffer false', testSubprocessError, 'ipc-process-error.js', false);211 test('"error" event interrupts exports.getOneMessage(), buffer true', testSubprocessError, 'ipc-process-error.js', true);212+test('"error" event interrupts exports.getOneMessage(), buffer false, filter', testSubprocessError, 'ipc-process-error-filter.js', false);213+test('"error" event interrupts exports.getOneMessage(), buffer true, filter', testSubprocessError, 'ipc-process-error-filter.js', true);214 test('"error" event interrupts exports.getEachMessage(), buffer false', testSubprocessError, 'ipc-iterate-error.js', false);215 test('"error" event interrupts exports.getEachMessage(), buffer true', testSubprocessError, 'ipc-iterate-error.js', true);modified:test-d/ipc/get-each.test-d.ts+5 added-6 removed
4 unmodified lines5 type Message,6 type Options,7 } from '../../index.js';8 9-for await (const message of getEachMessage()) {10- expectType<Message>(message);11-}12-13-expectError(getEachMessage(''));14-9 const subprocess = execa('test', {ipc: true});10 11 for await (const message of subprocess.getEachMessage()) {12 expectType<Message<'advanced'>>(message);2 unmodified lines15 for await (const message of execa('test', {ipc: true, serialization: 'json'}).getEachMessage()) {16 expectType<Message<'json'>>(message);17 }18 19+for await (const message of getEachMessage()) {20+ expectType<Message>(message);21+}22+23 expectError(subprocess.getEachMessage(''));24+expectError(getEachMessage(''));25 26 execa('test', {ipcInput: ''}).getEachMessage();27 execa('test', {ipcInput: '' as Message}).getEachMessage();28 execa('test', {} as Options).getEachMessage?.();9 unmodified linesmodified:test-d/ipc/get-one.test-d.ts+32 added-5 removed
4 unmodified lines5 type Message,6 type Options,7 } from '../../index.js';8 9+const subprocess = execa('test', {ipc: true});10+expectType<Promise<Message<'advanced'>>>(subprocess.getOneMessage());11+const jsonSubprocess = execa('test', {ipc: true, serialization: 'json'});12+expectType<Promise<Message<'json'>>>(jsonSubprocess.getOneMessage());13 expectType<Promise<Message>>(getOneMessage());10-expectError(await getOneMessage(''));14 12-const subprocess = execa('test', {ipc: true});13-expectType<Message<'advanced'>>(await subprocess.getOneMessage());14-expectType<Message<'json'>>(await execa('test', {ipc: true, serialization: 'json'}).getOneMessage());15-15 expectError(await subprocess.getOneMessage(''));16+expectError(await getOneMessage(''));17 18 await execa('test', {ipcInput: ''}).getOneMessage();19 await execa('test', {ipcInput: '' as Message}).getOneMessage();20 await execa('test', {} as Options).getOneMessage?.();4 unmodified lines25 expectType<undefined>(execa('test', {}).getOneMessage);26 expectType<undefined>(execa('test', {ipc: false}).getOneMessage);27 expectType<undefined>(execa('test', {ipcInput: undefined}).getOneMessage);28 expectType<undefined>(execa('test', {ipc: false, ipcInput: ''}).getOneMessage);29+30+await subprocess.getOneMessage({filter: undefined} as const);31+await subprocess.getOneMessage({filter: (message: Message<'advanced'>) => true} as const);32+await jsonSubprocess.getOneMessage({filter: (message: Message<'json'>) => true} as const);33+await jsonSubprocess.getOneMessage({filter: (message: Message<'advanced'>) => true} as const);34+await subprocess.getOneMessage({filter: (message: Message<'advanced'> | bigint) => true} as const);35+await subprocess.getOneMessage({filter: () => true} as const);36+expectError(await subprocess.getOneMessage({filter: (message: Message<'advanced'>) => ''} as const));37+// eslint-disable-next-line @typescript-eslint/no-empty-function38+expectError(await subprocess.getOneMessage({filter(message: Message<'advanced'>) {}} as const));39+expectError(await subprocess.getOneMessage({filter: (message: Message<'json'>) => true} as const));40+expectError(await subprocess.getOneMessage({filter: (message: '') => true} as const));41+expectError(await subprocess.getOneMessage({filter: true} as const));42+expectError(await subprocess.getOneMessage({unknownOption: true} as const));43+44+await getOneMessage({filter: undefined} as const);45+await getOneMessage({filter: (message: Message) => true} as const);46+await getOneMessage({filter: (message: Message<'advanced'>) => true} as const);47+await getOneMessage({filter: (message: Message | bigint) => true} as const);48+await getOneMessage({filter: () => true} as const);49+expectError(await getOneMessage({filter: (message: Message) => ''} as const));50+// eslint-disable-next-line @typescript-eslint/no-empty-function51+expectError(await getOneMessage({filter(message: Message) {}} as const));52+expectError(await getOneMessage({filter: (message: Message<'json'>) => true} as const));53+expectError(await getOneMessage({filter: (message: '') => true} as const));54+expectError(await getOneMessage({filter: true} as const));55+expectError(await getOneMessage({unknownOption: true} as const));modified:test-d/ipc/send.test-d.ts+6 added-5 removed
4 unmodified lines5 type Message,6 type Options,7 } from '../../index.js';8 9+const subprocess = execa('test', {ipc: true});10+expectType<void>(await subprocess.sendMessage(''));11 expectType<Promise<void>>(sendMessage(''));12 13+expectError(await subprocess.sendMessage());14 expectError(await sendMessage());15+expectError(await subprocess.sendMessage(undefined));16 expectError(await sendMessage(undefined));17+expectError(await subprocess.sendMessage(0n));18 expectError(await sendMessage(0n));19+expectError(await subprocess.sendMessage(Symbol('test')));20 expectError(await sendMessage(Symbol('test')));21 16-const subprocess = execa('test', {ipc: true});17-expectType<void>(await subprocess.sendMessage(''));18-19-expectError(await subprocess.sendMessage());20-22 await execa('test', {ipcInput: ''}).sendMessage('');23 await execa('test', {ipcInput: '' as Message}).sendMessage('');24 await execa('test', {} as Options).sendMessage?.('');25 await execa('test', {ipc: true as boolean}).sendMessage?.('');7 unmodified linesmodified:types/ipc.d.ts+14 added-2 removed
24 unmodified lines25 export type Message<26 Serialization extends Options['serialization'] = Options['serialization'],27 > = Serialization extends 'json' ? JsonMessage : AdvancedMessage;28 29+/**30+Options to `getOneMessage()` and `subprocess.getOneMessage()`31+*/32+type GetOneMessageOptions<33+ Serialization extends Options['serialization'],34+> = {35+ /**36+ Ignore any `message` that returns `false`.37+ */38+ readonly filter?: (message: Message<Serialization>) => boolean;39+};40+41 // IPC methods in subprocess42 /**43 Send a `message` to the parent process.44 5 unmodified lines50 Receive a single `message` from the parent process.51 52 This requires the `ipc` option to be `true`. The type of `message` depends on the `serialization` option.53 */42-export function getOneMessage(): Promise<Message>;54+export function getOneMessage(getOneMessageOptions?: GetOneMessageOptions<Options['serialization']>): Promise<Message>;55 56 /**57 Iterate over each `message` from the parent process.58 18 unmodified lines77 Receive a single `message` from the subprocess.78 79 This requires the `ipc` option to be `true`. The type of `message` depends on the `serialization` option.80 */69- getOneMessage(): Promise<Message<Serialization>>;81+ getOneMessage(getOneMessageOptions?: GetOneMessageOptions<Serialization>): Promise<Message<Serialization>>;82 83 /**84 Iterate over each `message` from the subprocess.85 29 unmodified lines