Add `ipcInput` option (#1068)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent 69152ec · Browse files · 27 files·+542 added−173 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
27 files+542 added−173 removed
- tests:+123 added−82 removed
- other:+419 added−91 removed
Provenance
- Commit
46cae30- Tree
5fe797e- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
69152ec
27 files changed+542 added−173 removed
modified:docs/api.md+13 added-1 removed
896 unmodified lines897 898 ### options.ipc899 900 _Type:_ `boolean`\901-_Default:_ `true` if the [`node`](#optionsnode) option is enabled, `false` otherwise901+_Default:_ `true` if either the [`node`](#optionsnode) option or the [`ipcInput`](#optionsipcinput) is set, `false` otherwise902 903 Enables exchanging messages with the subprocess using [`subprocess.sendMessage(message)`](#subprocesssendmessagemessage), [`subprocess.getOneMessage()`](#subprocessgetonemessage) and [`subprocess.getEachMessage()`](#subprocessgeteachmessage).904 905+The subprocess must be a Node.js file.906+907 [More info.](ipc.md)908 909 ### options.serialization910 3 unmodified lines914 Specify the kind of serialization used for sending messages between subprocesses when using the [`ipc`](#optionsipc) option.915 916 [More info.](ipc.md#message-type)917 918+### options.ipcInput919+920+_Type_: [`Message`](ipc.md#message-type)921+922+Sends an IPC message when the subprocess starts.923+924+The subprocess must be a [Node.js file](#optionsnode). The value's [type](ipc.md#message-type) depends on the [`serialization`](#optionsserialization) option.925+926+More info [here](ipc.md#send-an-initial-message) and [there](input.md#any-input-type).927+928 ### options.verbose929 930 _Type:_ `'none' | 'short' | 'full'`\931 _Default:_ `'none'`175 unmodified linesmodified:docs/input.md+22 added
88 unmodified lines899091929394959697989910010110210310410510610710810911011111211311411511611711812 unmodified lines88 unmodified lines```jsawait execa({stdin: 'inherit'})`npm run scaffold`;```
## Any input type
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).
```js// main.jsimport {execaNode} from 'execa';
const ipcInput = [ {task: 'lint', ignore: /test\.js/}, {task: 'copy', files: new Set(['main.js', 'index.js']),}];await execaNode({ipcInput})`build.js`;```
```js// build.jsimport {getOneMessage} from 'execa';
const ipcInput = await getOneMessage();```
## Additional file descriptors
The [`stdio`](api.md#optionsstdio) option can be used to pass some input to any [file descriptor](https://en.wikipedia.org/wiki/File_descriptor), as opposed to only [`stdin`](api.md#optionsstdin).
12 unmodified linesmodified:docs/ipc.md+23 added-1 removed
6 unmodified lines7 # 📞 Inter-process communication8 9 ## Exchanging messages10 11-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.11+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.72 unmodified lines88 await runBuild();89 await sendMessage({kind: 'stop', timestamp: new Date()});90 ```91 92+## Send an initial message93+94+The [`ipcInput`](api.md#optionsipcinput) option sends a message to the [Node.js subprocess](node.md) when it starts.95+96+```js97+// main.js98+import {execaNode} from 'execa';99+100+const ipcInput = [101+ {task: 'lint', ignore: /test\.js/},102+ {task: 'copy', files: new Set(['main.js', 'index.js']),103+}];104+await execaNode({ipcInput})`build.js`;105+```106+107+```js108+// build.js109+import {getOneMessage} from 'execa';110+111+const ipcInput = await getOneMessage();112+```113+114 ## Message type115 116 By default, messages are serialized using [`structuredClone()`](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm). This supports most types including objects, arrays, `Error`, `Date`, `RegExp`, `Map`, `Set`, `bigint`, `Uint8Array`, and circular references. This throws when passing functions, symbols or promises (including inside an object or array).117 17 unmodified linesmodified:lib/arguments/options.js+5 added-1 removed
4 unmodified lines5 import {normalizeForceKillAfterDelay} from '../terminate/kill.js';6 import {normalizeKillSignal} from '../terminate/signal.js';7 import {validateTimeout} from '../terminate/timeout.js';8 import {handleNodeOption} from '../methods/node.js';9+import {validateIpcInputOption} from '../ipc/ipc-input.js';10 import {validateEncoding, BINARY_ENCODINGS} from './encoding-option.js';11 import {normalizeCwd} from './cwd.js';12 import {normalizeFileUrl} from './file-url.js';13 import {normalizeFdSpecificOptions} from './specific.js';9 unmodified lines23 const fdOptions = normalizeFdSpecificOptions(initialOptions);24 const options = addDefaultOptions(fdOptions);25 validateTimeout(options);26 validateEncoding(options);27+ validateIpcInputOption(options);28 options.shell = normalizeFileUrl(options.shell);29 options.env = getEnv(options);30 options.killSignal = normalizeKillSignal(options.killSignal);31 options.forceKillAfterDelay = normalizeForceKillAfterDelay(options.forceKillAfterDelay);18 unmodified lines50 all = false,51 windowsHide = true,52 killSignal = 'SIGTERM',53 forceKillAfterDelay = true,52- ipc = false,54+ ipcInput,55+ ipc = ipcInput !== undefined,56 serialization = 'advanced',57 ...options58 }) => ({59 ...options,7 unmodified lines67 all,68 windowsHide,69 killSignal,70 forceKillAfterDelay,71+ ipcInput,72 ipc,73 serialization,74 });75 15 unmodified linesadded:lib/ipc/buffer-messages.js+43 added
12345678910111213141516171819202122232425262728293031323334353637383940414243import {checkIpcMaxBuffer} from '../io/max-buffer.js';import {shouldLogIpc, logIpcMessage} from '../verbose/ipc.js';import {loopOnMessages} from './get-each.js';
// Iterate through IPC messages sent by the subprocessexport const waitForIpcMessages = async ({ subprocess, buffer: bufferArray, maxBuffer: maxBufferArray, ipc, ipcMessages, verboseInfo,}) => { if (!ipc) { return ipcMessages; }
const isVerbose = shouldLogIpc(verboseInfo); const buffer = bufferArray.at(-1); const maxBuffer = maxBufferArray.at(-1);
if (!isVerbose && !buffer) { return ipcMessages; }
for await (const message of loopOnMessages({ anyProcess: subprocess, isSubprocess: false, ipc, shouldAwait: false, })) { if (buffer) { checkIpcMaxBuffer(subprocess, ipcMessages, maxBuffer); ipcMessages.push(message); }
if (isVerbose) { logIpcMessage(message, verboseInfo); } }
return ipcMessages;};added:lib/ipc/ipc-input.js+44 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344import {serialize} from 'node:v8';
// Validate the `ipcInput` optionexport const validateIpcInputOption = ({ipcInput, ipc, serialization}) => { if (ipcInput === undefined) { return; }
if (!ipc) { throw new Error('The `ipcInput` option cannot be set unless the `ipc` option is `true`.'); }
validateIpcInput[serialization](ipcInput);};
const validateAdvancedInput = ipcInput => { try { serialize(ipcInput); } catch (error) { throw new Error(`The \`ipcInput\` option is not serializable with a structured clone.\n${error.message}`); }};
const validateJsonInput = ipcInput => { try { JSON.stringify(ipcInput); } catch (error) { throw new Error(`The \`ipcInput\` option is not serializable with JSON.\n${error.message}`); }};
const validateIpcInput = { advanced: validateAdvancedInput, json: validateJsonInput,};
// When the `ipcInput` option is set, it is sent as an initial IPC message to the subprocessexport const sendIpcInput = async (subprocess, ipcInput) => { if (ipcInput === undefined) { return; }
await subprocess.sendMessage(ipcInput);};deleted:lib/ipc/messages.js-43 removed
12345678910111213141516171819202122232425262728293031323334353637383940414243import {checkIpcMaxBuffer} from '../io/max-buffer.js';import {shouldLogIpc, logIpcMessage} from '../verbose/ipc.js';import {loopOnMessages} from './get-each.js';
// Iterate through IPC messages sent by the subprocessexport const waitForIpcMessages = async ({ subprocess, buffer: bufferArray, maxBuffer: maxBufferArray, ipc, ipcMessages, verboseInfo,}) => { if (!ipc) { return ipcMessages; }
const isVerbose = shouldLogIpc(verboseInfo); const buffer = bufferArray.at(-1); const maxBuffer = maxBufferArray.at(-1);
if (!isVerbose && !buffer) { return ipcMessages; }
for await (const message of loopOnMessages({ anyProcess: subprocess, isSubprocess: false, ipc, shouldAwait: false, })) { if (buffer) { checkIpcMaxBuffer(subprocess, ipcMessages, maxBuffer); ipcMessages.push(message); }
if (isVerbose) { logIpcMessage(message, verboseInfo); } }
return ipcMessages;};modified:lib/methods/main-sync.js+5 added-1 removed
55 unmodified lines56 // Options normalization logic specific to sync methods57 const normalizeSyncOptions = options => options.node && !options.ipc ? {...options, ipc: false} : options;58 59 // Options validation logic specific to sync methods60-const validateSyncOptions = ({ipc, detached, cancelSignal}) => {60+const validateSyncOptions = ({ipc, ipcInput, detached, cancelSignal}) => {61+ if (ipcInput) {62+ throwInvalidSyncOption('ipcInput');63+ }64+65 if (ipc) {66 throwInvalidSyncOption('ipc: true');67 }68 99 unmodified linesmodified:lib/resolve/wait-subprocess.js+4 added-1 removed
2 unmodified lines3 import {throwOnTimeout} from '../terminate/timeout.js';4 import {isStandardStream} from '../utils/standard-stream.js';5 import {TRANSFORM_TYPES} from '../stdio/type.js';6 import {getBufferedData} from '../io/contents.js';7-import {waitForIpcMessages} from '../ipc/messages.js';7+import {waitForIpcMessages} from '../ipc/buffer-messages.js';8+import {sendIpcInput} from '../ipc/ipc-input.js';9 import {waitForAllStream} from './all-async.js';10 import {waitForStdioStreams} from './stdio.js';11 import {waitForExit, waitForSuccessfulExit} from './exit-async.js';12 import {waitForStream} from './wait-stream.js';8 unmodified lines21 lines,22 timeoutDuration: timeout,23 stripFinalNewline,24 ipc,25+ ipcInput,26 },27 context,28 verboseInfo,29 fileDescriptors,48 unmodified lines78 ipc,79 ipcMessages,80 verboseInfo,81 }),82+ sendIpcInput(subprocess, ipcInput),83 ...originalPromises,84 ...customStreamsEndPromises,85 ]),86 onInternalError,38 unmodified linesadded:test/ipc/buffer-messages.js+58 added
1+import test from 'ava';2+import {execa, execaSync} from '../../index.js';3+import {setFixtureDirectory} from '../helpers/fixtures-directory.js';4+import {foobarString, foobarArray} from '../helpers/input.js';5+6+setFixtureDirectory();7+8+const testResultIpc = async (t, options) => {9+ const {ipc} = await execa('ipc-send-twice.js', {...options, ipc: true});10+ t.deepEqual(ipc, foobarArray);11+};12+13+test('Sets result.ipc', testResultIpc, {});14+test('Sets result.ipc, fd-specific buffer', testResultIpc, {buffer: {stdout: false}});15+16+const testResultNoBuffer = async (t, options) => {17+ const {ipc} = await execa('ipc-send.js', {...options, ipc: true});18+ t.deepEqual(ipc, []);19+};20+21+test('Sets empty result.ipc if buffer is false', testResultNoBuffer, {buffer: false});22+test('Sets empty result.ipc if buffer is false, fd-specific buffer', testResultNoBuffer, {buffer: {ipc: false}});23+24+test('Sets empty result.ipc if ipc is false', async t => {25+ const {ipc} = await execa('empty.js');26+ t.deepEqual(ipc, []);27+});28+29+test('Sets empty result.ipc, sync', t => {30+ const {ipc} = execaSync('empty.js');31+ t.deepEqual(ipc, []);32+});33+34+const testErrorIpc = async (t, options) => {35+ const {ipc} = await t.throwsAsync(execa('ipc-send-fail.js', {...options, ipc: true}));36+ t.deepEqual(ipc, [foobarString]);37+};38+39+test('Sets error.ipc', testErrorIpc, {});40+test('Sets error.ipc, fd-specific buffer', testErrorIpc, {buffer: {stdout: false}});41+42+const testErrorNoBuffer = async (t, options) => {43+ const {ipc} = await t.throwsAsync(execa('ipc-send-fail.js', {...options, ipc: true}));44+ t.deepEqual(ipc, []);45+};46+47+test('Sets empty error.ipc if buffer is false', testErrorNoBuffer, {buffer: false});48+test('Sets empty error.ipc if buffer is false, fd-specific buffer', testErrorNoBuffer, {buffer: {ipc: false}});49+50+test('Sets empty error.ipc if ipc is false', async t => {51+ const {ipc} = await t.throwsAsync(execa('fail.js'));52+ t.deepEqual(ipc, []);53+});54+55+test('Sets empty error.ipc, sync', t => {56+ const {ipc} = t.throws(() => execaSync('fail.js'));57+ t.deepEqual(ipc, []);58+});modified:test/ipc/get-one.js+1 added-2 removed
107 unmodified lines108 test('Cleans up subprocess.getOneMessage() listeners, buffer false', testCleanupListeners, false);109 test('Cleans up subprocess.getOneMessage() listeners, buffer true', testCleanupListeners, true);110 111 test('"error" event interrupts result.ipc', async t => {112- const subprocess = execa('ipc-echo-twice.js', {ipc: true});113- await subprocess.sendMessage(foobarString);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);77 unmodified linesadded:test/ipc/ipc-input.js+46 added
1+import test from 'ava';2+import {execa, execaSync} from '../../index.js';3+import {setFixtureDirectory} from '../helpers/fixtures-directory.js';4+import {foobarString} from '../helpers/input.js';5+6+setFixtureDirectory();7+8+const testSuccess = async (t, options) => {9+ const {ipc} = await execa('ipc-echo.js', {ipcInput: foobarString, ...options});10+ t.deepEqual(ipc, [foobarString]);11+};12+13+test('Sends a message with the "ipcInput" option, ipc undefined', testSuccess, {});14+test('Sends a message with the "ipcInput" option, ipc true', testSuccess, {ipc: true});15+16+test('Cannot use the "ipcInput" option with "ipc" false', t => {17+ t.throws(() => {18+ execa('empty.js', {ipcInput: foobarString, ipc: false});19+ }, {message: /unless the `ipc` option is `true`/});20+});21+22+test('Cannot use the "ipcInput" option with execaSync()', t => {23+ t.throws(() => {24+ execaSync('empty.js', {ipcInput: foobarString});25+ }, {message: /The "ipcInput" option cannot be used with synchronous/});26+});27+28+test('Invalid "ipcInput" option v8 format', t => {29+ const {message} = t.throws(() => {30+ execa('empty.js', {ipcInput() {}});31+ });32+ t.is(message, 'The `ipcInput` option is not serializable with a structured clone.\nipcInput() {} could not be cloned.');33+});34+35+test('Invalid "ipcInput" option JSON format', t => {36+ const {message} = t.throws(() => {37+ execa('empty.js', {ipcInput: 0n, serialization: 'json'});38+ });39+ t.is(message, 'The `ipcInput` option is not serializable with JSON.\nDo not know how to serialize a BigInt');40+});41+42+test('Handles "ipcInput" option during sending', async t => {43+ await t.throwsAsync(execa('empty.js', {ipcInput: 0n}), {44+ message: /The "message" argument must be one of type string/,45+ });46+});deleted:test/ipc/messages.js-58 removed
1-import test from 'ava';2-import {execa, execaSync} from '../../index.js';3-import {setFixtureDirectory} from '../helpers/fixtures-directory.js';4-import {foobarString, foobarArray} from '../helpers/input.js';5-6-setFixtureDirectory();7-8-const testResultIpc = async (t, options) => {9- const {ipc} = await execa('ipc-send-twice.js', {...options, ipc: true});10- t.deepEqual(ipc, foobarArray);11-};12-13-test('Sets result.ipc', testResultIpc, {});14-test('Sets result.ipc, fd-specific buffer', testResultIpc, {buffer: {stdout: false}});15-16-const testResultNoBuffer = async (t, options) => {17- const {ipc} = await execa('ipc-send.js', {...options, ipc: true});18- t.deepEqual(ipc, []);19-};20-21-test('Sets empty result.ipc if buffer is false', testResultNoBuffer, {buffer: false});22-test('Sets empty result.ipc if buffer is false, fd-specific buffer', testResultNoBuffer, {buffer: {ipc: false}});23-24-test('Sets empty result.ipc if ipc is false', async t => {25- const {ipc} = await execa('empty.js');26- t.deepEqual(ipc, []);27-});28-29-test('Sets empty result.ipc, sync', t => {30- const {ipc} = execaSync('empty.js');31- t.deepEqual(ipc, []);32-});33-34-const testErrorIpc = async (t, options) => {35- const {ipc} = await t.throwsAsync(execa('ipc-send-fail.js', {...options, ipc: true}));36- t.deepEqual(ipc, [foobarString]);37-};38-39-test('Sets error.ipc', testErrorIpc, {});40-test('Sets error.ipc, fd-specific buffer', testErrorIpc, {buffer: {stdout: false}});41-42-const testErrorNoBuffer = async (t, options) => {43- const {ipc} = await t.throwsAsync(execa('ipc-send-fail.js', {...options, ipc: true}));44- t.deepEqual(ipc, []);45-};46-47-test('Sets empty error.ipc if buffer is false', testErrorNoBuffer, {buffer: false});48-test('Sets empty error.ipc if buffer is false, fd-specific buffer', testErrorNoBuffer, {buffer: {ipc: false}});49-50-test('Sets empty error.ipc if ipc is false', async t => {51- const {ipc} = await t.throwsAsync(execa('fail.js'));52- t.deepEqual(ipc, []);53-});54-55-test('Sets empty error.ipc, sync', t => {56- const {ipc} = t.throws(() => execaSync('fail.js'));57- t.deepEqual(ipc, []);58-});modified:test/ipc/send.js+14 added
66 unmodified lines67 t.is(exitCode, 1);68 t.false(isTerminated);69 t.true(stderr.includes('sendMessage()\'s argument type is invalid'));70 });71+72+test('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+});79+80+test('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+});modified:test/methods/node.js-14 removed
284 unmodified lines285 286 test('Cannot use "shell: true" - execaNode()', testNoShell, execaNode);287 test('Cannot use "shell: true" - "node" option', testNoShell, runWithNodeOption);288 test('Cannot use "shell: true" - "node" option sync', testNoShell, runWithNodeOptionSync);289-290-test('The "serialization" option defaults to "advanced"', async t => {291- const subprocess = execa('node', ['ipc-echo.js'], {ipc: true});292- await subprocess.sendMessage([0n]);293- const message = await subprocess.getOneMessage();294- t.is(message[0], 0n);295- await subprocess;296-});297-298-test('The "serialization" option can be set to "json"', async t => {299- const subprocess = execa('node', ['ipc-echo.js'], {ipc: true, serialization: 'json'});300- await t.throwsAsync(subprocess.sendMessage([0n]), {message: /serialize a BigInt/});301- await t.throwsAsync(subprocess);302-});modified:test/return/message.js+4 added-8 removed
93 unmodified lines94 const {originalMessage} = await t.throwsAsync(execa('noop.js', {uid: true}));95 t.is(originalMessage, 'The "options.uid" property must be int32. Received type boolean (true)');96 });97 98-const testIpcMessage = async (t, doubles, input, returnedMessage) => {98+const testIpcMessage = async (t, doubles, ipcInput, returnedMessage) => {99 const fixtureName = doubles ? 'ipc-echo-twice-fail.js' : 'ipc-echo-fail.js';100- const subprocess = execa(fixtureName, {ipc: true});101- await subprocess.sendMessage(input);102- const {exitCode, message, ipc} = await t.throwsAsync(subprocess);100+ const {exitCode, message, ipc} = await t.throwsAsync(execa(fixtureName, {ipcInput}));101 t.is(exitCode, 1);102 t.true(message.endsWith(`\n\n${doubles ? `${returnedMessage}\n${returnedMessage}` : returnedMessage}`));105- t.deepEqual(ipc, doubles ? [input, input] : [input]);103+ t.deepEqual(ipc, doubles ? [ipcInput, ipcInput] : [ipcInput]);104 };105 106 test('error.message contains IPC messages, single string', testIpcMessage, false, foobarString, foobarString);107 test('error.message contains IPC messages, two strings', testIpcMessage, true, foobarString, foobarString);2 unmodified lines110 test('error.message contains IPC messages, multiline string', testIpcMessage, false, `${foobarString}\n${foobarString}`, `${foobarString}\n${foobarString}`);111 test('error.message contains IPC messages, control characters', testIpcMessage, false, '\0', '\\u0000');112 113 test('error.message does not contain IPC messages, buffer false', async t => {116- const subprocess = execa('ipc-echo-fail.js', {ipc: true, buffer: false});117- await subprocess.sendMessage(foobarString);118- const {exitCode, message, ipc} = await t.throwsAsync(subprocess);114+ const {exitCode, message, ipc} = await t.throwsAsync(execa('ipc-echo-fail.js', {ipcInput: foobarString, buffer: false}));115 t.is(exitCode, 1);116 t.true(message.endsWith('ipc-echo-fail.js'));117 t.deepEqual(ipc, []);118 });modified:test-d/arguments/options.test-d.ts+9 added
199 unmodified lines200 expectError(execaSync('unicorns', {serialization: 'advanced'}));201 expectError(await execa('unicorns', {serialization: 'other'}));202 expectError(execaSync('unicorns', {serialization: 'other'}));203 204+await execa('unicorns', {ipcInput: ''});205+expectError(execaSync('unicorns', {ipcInput: ''}));206+await execa('unicorns', {ipcInput: {}});207+expectError(execaSync('unicorns', {ipcInput: {}}));208+await execa('unicorns', {ipcInput: undefined});209+execaSync('unicorns', {ipcInput: undefined});210+expectError(await execa('unicorns', {ipcInput: 0n}));211+expectError(execaSync('unicorns', {ipcInput: 0n}));212+213 await execa('unicorns', {detached: true});214 expectError(execaSync('unicorns', {detached: true}));215 expectError(await execa('unicorns', {detached: 'true'}));216 expectError(execaSync('unicorns', {detached: 'true'}));5 unmodified linesmodified:test-d/ipc/get-each.test-d.ts+18 added-3 removed
1 import {expectType, expectError} from 'tsd';2-import {getEachMessage, execa, type Message} from '../../index.js';2+import {3+ getEachMessage,4+ execa,5+ type Message,6+ type Options,7+} from '../../index.js';8 9 for await (const message of getEachMessage()) {10 expectType<Message>(message);11 }10 unmodified lines22 expectType<Message<'json'>>(message);23 }24 25 expectError(subprocess.getEachMessage(''));21-expectError(await execa('test').getEachMessage());22-expectError(await execa('test', {ipc: false}).getEachMessage());26 27+execa('test', {ipcInput: ''}).getEachMessage();28+execa('test', {ipcInput: '' as Message}).getEachMessage();29+execa('test', {} as Options).getEachMessage?.();30+execa('test', {ipc: true as boolean}).getEachMessage?.();31+execa('test', {ipcInput: '' as '' | undefined}).getEachMessage?.();32+33+expectType<undefined>(execa('test').getEachMessage);34+expectType<undefined>(execa('test', {}).getEachMessage);35+expectType<undefined>(execa('test', {ipc: false}).getEachMessage);36+expectType<undefined>(execa('test', {ipcInput: undefined}).getEachMessage);37+expectType<undefined>(execa('test', {ipc: false, ipcInput: ''}).getEachMessage);38+modified:test-d/ipc/get-one.test-d.ts+18 added-3 removed
1 import {expectType, expectError} from 'tsd';2-import {getOneMessage, execa, type Message} from '../../index.js';2+import {3+ getOneMessage,4+ execa,5+ type Message,6+ type Options,7+} from '../../index.js';8 9 expectType<Promise<Message>>(getOneMessage());10 expectError(await getOneMessage(''));11 1 unmodified line13 expectType<Message<'advanced'>>(await subprocess.getOneMessage());14 expectType<Message<'json'>>(await execa('test', {ipc: true, serialization: 'json'}).getOneMessage());15 16 expectError(await subprocess.getOneMessage(''));12-expectError(await execa('test').getOneMessage());13-expectError(await execa('test', {ipc: false}).getOneMessage());17+18+await execa('test', {ipcInput: ''}).getOneMessage();19+await execa('test', {ipcInput: '' as Message}).getOneMessage();20+await execa('test', {} as Options).getOneMessage?.();21+await execa('test', {ipc: true as boolean}).getOneMessage?.();22+await execa('test', {ipcInput: '' as '' | undefined}).getOneMessage?.();23+24+expectType<undefined>(execa('test').getOneMessage);25+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);modified:test-d/ipc/send.test-d.ts+18 added-3 removed
1 import {expectType, expectError} from 'tsd';2-import {sendMessage, execa} from '../../index.js';2+import {3+ sendMessage,4+ execa,5+ type Message,6+ type Options,7+} from '../../index.js';8 9 expectType<Promise<void>>(sendMessage(''));10 11 expectError(await sendMessage());4 unmodified lines16 const subprocess = execa('test', {ipc: true});17 expectType<void>(await subprocess.sendMessage(''));18 19 expectError(await subprocess.sendMessage());15-expectError(await execa('test').sendMessage(''));16-expectError(await execa('test', {ipc: false}).sendMessage(''));20+21+await execa('test', {ipcInput: ''}).sendMessage('');22+await execa('test', {ipcInput: '' as Message}).sendMessage('');23+await execa('test', {} as Options).sendMessage?.('');24+await execa('test', {ipc: true as boolean}).sendMessage?.('');25+await execa('test', {ipcInput: '' as '' | undefined}).sendMessage?.('');26+27+expectType<undefined>(execa('test').sendMessage);28+expectType<undefined>(execa('test', {}).sendMessage);29+expectType<undefined>(execa('test', {ipc: false}).sendMessage);30+expectType<undefined>(execa('test', {ipcInput: undefined}).sendMessage);31+expectType<undefined>(execa('test', {ipc: false, ipcInput: ''}).sendMessage);modified:test-d/return/result-ipc.ts+25 added
5 unmodified lines6 type SyncResult,7 type ExecaError,8 type ExecaSyncError,9 type Message,10+ type Options,11 } from '../../index.js';12 13 const ipcResult = await execa('unicorns', {ipc: true});14 expectType<Array<Message<'advanced'>>>(ipcResult.ipc);6 unmodified lines21 22 const jsonResult = await execa('unicorns', {ipc: true, serialization: 'json'});23 expectType<Array<Message<'json'>>>(jsonResult.ipc);24 25+const inputResult = await execa('unicorns', {ipcInput: ''});26+expectType<Array<Message<'advanced'>>>(inputResult.ipc);27+28+const genericInputResult = await execa('unicorns', {ipcInput: '' as Message});29+expectType<Array<Message<'advanced'>>>(genericInputResult.ipc);30+31+const genericResult = await execa('unicorns', {} as Options);32+expectType<Message[] | []>(genericResult.ipc);33+34+const genericIpc = await execa('unicorns', {ipc: true as boolean});35+expectType<Array<Message<'advanced'>> | []>(genericIpc.ipc);36+37+const maybeInputResult = await execa('unicorns', {ipcInput: '' as '' | undefined});38+expectType<Array<Message<'advanced'>> | []>(maybeInputResult.ipc);39+40 const falseIpcResult = await execa('unicorns', {ipc: false});41 expectType<[]>(falseIpcResult.ipc);42 43 const noIpcResult = await execa('unicorns');44 expectType<[]>(noIpcResult.ipc);45 46+const emptyIpcResult = await execa('unicorns', {});47+expectType<[]>(emptyIpcResult.ipc);48+49+const undefinedInputResult = await execa('unicorns', {ipcInput: undefined});50+expectType<[]>(undefinedInputResult.ipc);51+52+const inputNoIpcResult = await execa('unicorns', {ipc: false, ipcInput: ''});53+expectType<[]>(inputNoIpcResult.ipc);54+55 const noBufferResult = await execa('unicorns', {ipc: true, buffer: false});56 expectType<[]>(noBufferResult.ipc);57 58 const noBufferFdResult = await execa('unicorns', {ipc: true, buffer: {ipc: false}});21 unmodified linesmodified:types/arguments/options.d.ts+11 added-1 removed
1 import type {SignalConstants} from 'node:os';2 import type {env} from 'node:process';3 import type {Readable} from 'node:stream';4 import type {Unless} from '../utils.js';5+import type {Message} from '../ipc.js';6 import type {StdinOptionCommon, StdoutStderrOptionCommon, StdioOptionsProperty} from '../stdio/type.js';7 import type {FdGenericOption} from './specific.js';8 import type {EncodingOption} from './encoding-option.js';9 190 unmodified lines200 201 /**202 Enables exchanging messages with the subprocess using `subprocess.sendMessage(message)`, `subprocess.getOneMessage()` and `subprocess.getEachMessage()`.203 203- @default `true` if the `node` option is enabled, `false` otherwise204+ The subprocess must be a Node.js file.205+206+ @default `true` if either the `node` option or the `ipcInput` option is set, `false` otherwise207 */208 readonly ipc?: Unless<IsSync, boolean>;209 210 /**3 unmodified lines214 */215 readonly serialization?: Unless<IsSync, 'json' | 'advanced'>;216 217 /**218+ Sends an IPC message when the subprocess starts.219+220+ The subprocess must be a Node.js file. The value's type depends on the `serialization` option.221+ */222+ readonly ipcInput?: Unless<IsSync, Message>;223+224+ /**225 If `verbose` is `'short'`, prints the command on [`stderr`](https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)): its file, arguments, duration and (if it failed) error message.226 227 If `verbose` is `'full'`, the command's [`stdout`](https://en.wikipedia.org/wiki/Standard_streams#Standard_output_(stdout)), `stderr` and IPC messages are also printed.228 154 unmodified linesmodified:types/methods/main-async.d.ts+73 added-6 removed
103 unmodified lines104 // stdout is also printed to the terminal105 console.log(stdout);106 ```107 108-@example <caption>Files</caption>108+@example <caption>Simple input</caption>109 110 ```111-// Similar to: npm run build > output.txt112-await execa({stdout: {file: './output.txt'}})`npm run build`;111+const {stdout} = await execa({input: getInputString()})`sort`;112+console.log(stdout);113 ```114 115-@example <caption>Simple input</caption>115+@example <caption>File input</caption>116 117 ```118-const {stdout} = await execa({input: getInputString()})`sort`;119-console.log(stdout);118+// Similar to: npm run build < input.txt119+await execa({stdin: {file: 'input.txt'}})`npm run build`;120 ```121 122+@example <caption>File output</caption>123+124+```125+// Similar to: npm run build > output.txt126+await execa({stdout: {file: 'output.txt'}})`npm run build`;127+```128+129 @example <caption>Split into text lines</caption>130 131 ```132 const {stdout} = await execa({lines: true})`npm run build`;46 unmodified lines179 createWriteStream('./output.txt'),180 );181 ```182 183+@example <caption>Exchange messages</caption>184+185+```186+// parent.js187+import {execaNode} from 'execa';188+189+const subprocess = execaNode`child.js`;190+console.log(await subprocess.getOneMessage()); // 'Hello from child'191+await subprocess.sendMessage('Hello from parent');192+const result = await subprocess;193+```194+195+```196+// child.js197+import {sendMessage, getOneMessage} from 'execa';198+199+await sendMessage('Hello from child');200+console.log(await getOneMessage()); // 'Hello from parent'201+```202+203+@example <caption>Any input type</caption>204+205+```206+// main.js207+import {execaNode} from 'execa';208+209+const ipcInput = [210+ {task: 'lint', ignore: /test\.js/},211+ {task: 'copy', files: new Set(['main.js', 'index.js']),212+}];213+await execaNode({ipcInput})`build.js`;214+```215+216+```217+// build.js218+import {getOneMessage} from 'execa';219+220+const ipcInput = await getOneMessage();221+```222+223+@example <caption>Any output type</caption>224+225+```226+// main.js227+import {execaNode} from 'execa';228+229+const {ipc} = await execaNode`build.js`;230+console.log(ipc[0]); // {kind: 'start', timestamp: date}231+console.log(ipc[1]); // {kind: 'stop', timestamp: date}232+```233+234+```235+// build.js236+import {sendMessage} from 'execa';237+238+await sendMessage({kind: 'start', timestamp: new Date()});239+await runBuild();240+await sendMessage({kind: 'stop', timestamp: new Date()});241+```242+243 @example <caption>Detailed error</caption>244 245 ```246 import {execa, ExecaError} from 'execa';63 unmodified linesmodified:types/return/result-ipc.d.ts+5 added-5 removed
1 import type {FdSpecificOption} from '../arguments/specific.js';2-import type {CommonOptions} from '../arguments/options.js';3-import type {Message} from '../ipc.js';2+import type {CommonOptions, Options, StricterOptions} from '../arguments/options.js';3+import type {Message, HasIpc} from '../ipc.js';4 5 // `result.ipc`6 // This is empty unless the `ipc` option is `true`.7 // Also, this is empty if the `buffer` option is `false`.3 unmodified lines11 > = IsSync extends true12 ? []13 : ResultIpcAsync<14 FdSpecificOption<OptionsType['buffer'], 'ipc'>,15- OptionsType['ipc'],15+ HasIpc<StricterOptions<OptionsType, Options>>,16 OptionsType['serialization']17 >;18 19 type ResultIpcAsync<20 BufferOption extends boolean | undefined,21- IpcOption extends boolean | undefined,21+ IpcEnabled extends boolean,22 SerializationOption extends CommonOptions['serialization'],23 > = BufferOption extends false24 ? []25- : IpcOption extends true25+ : IpcEnabled extends true26 ? Array<Message<SerializationOption>>27 : [];modified:types/subprocess/subprocess.d.ts+2 added-9 removed
1 import type {ChildProcess} from 'node:child_process';2 import type {SignalConstants} from 'node:os';3 import type {Readable, Writable, Duplex} from 'node:stream';4-import type {StdioOptionsArray} from '../stdio/type.js';4 import type {Options} from '../arguments/options.js';5 import type {Result} from '../return/result.js';6 import type {PipableSubprocess} from '../pipe.js';7 import type {1 unmodified line9 WritableOptions,10 DuplexOptions,11 SubprocessAsyncIterable,12 } from '../convert.js';14-import type {IpcMethods} from '../ipc.js';13+import type {IpcMethods, HasIpc} from '../ipc.js';14 import type {SubprocessStdioStream} from './stdout.js';15 import type {SubprocessStdioArray} from './stdio.js';16 import type {SubprocessAll} from './all.js';17 19-type HasIpc<OptionsType extends Options> = OptionsType['ipc'] extends true20- ? true21- : OptionsType['stdio'] extends StdioOptionsArray22- ? 'ipc' extends OptionsType['stdio'][number] ? true : false23- : false;24-18 type ExecaCustomSubprocess<OptionsType extends Options> = {19 /**20 Process identifier ([PID](https://en.wikipedia.org/wiki/Process_identifier)).21 74 unmodified lines96 Converts the subprocess to a duplex stream.97 */98 duplex(duplexOptions?: DuplexOptions): Duplex;99 }107-& IpcMethods<OptionsType['ipc'], OptionsType['serialization']>100+& IpcMethods<HasIpc<OptionsType>, OptionsType['serialization']>101 & PipableSubprocess;102 103 /**104 [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess) with additional methods and properties.13 unmodified linesmodified:types/ipc.d.ts+23 added-6 removed
48 unmodified lines49 export function getEachMessage(): AsyncIterableIterator<Message>;50 51 // IPC methods in the current process52 export type IpcMethods<53- IpcOption extends Options['ipc'],53+ IpcEnabled extends boolean,54 Serialization extends Options['serialization'],55-> = IpcOption extends true55+> = IpcEnabled extends true56 ? {57 /**58 Send a `message` to the subprocess.59 16 unmodified lines76 getEachMessage(): AsyncIterableIterator<Message<Serialization>>;77 }78 // Those methods only work if the `ipc` option is `true`.79 // At runtime, they are actually defined, in order to provide with a nice error message.80- // At type check time, they are typed as `never` to prevent calling them.80+ // At type check time, they are typed as `undefined` to prevent calling them.81 : {82- sendMessage: never;83- getOneMessage: never;84- getEachMessage: never;82+ sendMessage: undefined;83+ getOneMessage: undefined;84+ getEachMessage: undefined;85 };86+87+// Whether IPC is enabled, based on the `ipc` and `ipcInput` options88+export type HasIpc<OptionsType extends Options> = HasIpcOption<89+OptionsType['ipc'],90+'ipcInput' extends keyof OptionsType ? OptionsType['ipcInput'] : undefined91+>;92+93+type HasIpcOption<94+ IpcOption extends Options['ipc'],95+ IpcInputOption extends Options['ipcInput'],96+> = IpcOption extends true97+ ? true98+ : IpcOption extends false99+ ? false100+ : IpcInputOption extends undefined101+ ? false102+ : true;modified:readme.md+58 added-7 removed
60 unmodified lines61 - [Detailed errors](#detailed-error) and [verbose mode](#verbose-mode), for [debugging](docs/debugging.md).62 - [Pipe multiple subprocesses](#pipe-multiple-subprocesses) better than in shells: retrieve [intermediate results](docs/pipe.md#result), use multiple [sources](docs/pipe.md#multiple-sources-1-destination)/[destinations](docs/pipe.md#1-source-multiple-destinations), [unpipe](docs/pipe.md#unpipe).63 - [Split](#split-into-text-lines) the output into text lines, or [iterate](#iterate-over-text-lines) progressively over them.64 - Strip [unnecessary newlines](docs/lines.md#newlines).65+- Pass any [input](docs/input.md) to the subprocess: [files](#file-input), [strings](#simple-input), [`Uint8Array`s](docs/binary.md#binary-input), [iterables](docs/streams.md#iterables-as-input), [objects](docs/transform.md#object-mode) and almost any [other type](#any-input-type).66+- Return [almost any type](#any-output-type) from the subprocess, or redirect it to [files](#file-output).67 - Get [interleaved output](#interleaved-output) from `stdout` and `stderr` similar to what is printed on the terminal.68 - Retrieve the output [programmatically and print it](#programmatic--terminal-output) on the console at the same time.69 - [Transform or filter](#transformfilter-output) the input and output with [simple functions](docs/transform.md).68-- Redirect the [input](docs/input.md) and [output](docs/output.md) from/to [files](#files), [strings](#simple-input), [`Uint8Array`s](docs/binary.md#binary-input), [iterables](docs/streams.md#iterables-as-input) or [objects](docs/transform.md#object-mode).70 - Pass [Node.js streams](docs/streams.md#nodejs-streams) or [web streams](#web-streams) to subprocesses, or [convert](#convert-to-duplex-stream) subprocesses to [a stream](docs/streams.md#converting-a-subprocess-to-a-stream).71 - [Exchange messages](#exchange-messages) with the subprocess.72 - Ensure subprocesses exit even when they [intercept termination signals](docs/termination.md#forceful-termination), or when the current process [ends abruptly](docs/termination.md#current-process-exit).73 109 unmodified lines183 // stdout is also printed to the terminal184 console.log(stdout);185 ```186 186-#### Files187+#### Simple input188 189 ```js189-// Similar to: npm run build > output.txt190-await execa({stdout: {file: './output.txt'}})`npm run build`;190+const {stdout} = await execa({input: getInputString()})`sort`;191+console.log(stdout);192 ```193 193-#### Simple input194+#### File input195 196 ```js196-const {stdout} = await execa({input: getInputString()})`sort`;197-console.log(stdout);197+// Similar to: npm run build < input.txt198+await execa({stdin: {file: 'input.txt'}})`npm run build`;199 ```200 201+#### File output202+203+```js204+// Similar to: npm run build > output.txt205+await execa({stdout: {file: 'output.txt'}})`npm run build`;206+```207+208 #### Split into text lines209 210 ```js211 const {stdout} = await execa({lines: true})`npm run build`;48 unmodified lines260 createWriteStream('./output.txt'),261 );262 ```263 264+### IPC265+266 #### Exchange messages267 268 ```js269 // parent.js1 unmodified line271 272 const subprocess = execaNode`child.js`;273 console.log(await subprocess.getOneMessage()); // 'Hello from child'274 await subprocess.sendMessage('Hello from parent');275+const result = await subprocess;276 ```277 278 ```js279 // child.js2 unmodified lines282 await sendMessage('Hello from child');283 console.log(await getOneMessage()); // 'Hello from parent'284 ```285 286+#### Any input type287+288+```js289+// main.js290+import {execaNode} from 'execa';291+292+const ipcInput = [293+ {task: 'lint', ignore: /test\.js/},294+ {task: 'copy', files: new Set(['main.js', 'index.js']),295+}];296+await execaNode({ipcInput})`build.js`;297+```298+299+```js300+// build.js301+import {getOneMessage} from 'execa';302+303+const ipcInput = await getOneMessage();304+```305+306+#### Any output type307+308+```js309+// main.js310+import {execaNode} from 'execa';311+312+const {ipc} = await execaNode`build.js`;313+console.log(ipc[0]); // {kind: 'start', timestamp: date}314+console.log(ipc[1]); // {kind: 'stop', timestamp: date}315+```316+317+```js318+// build.js319+import {sendMessage} from 'execa';320+321+await sendMessage({kind: 'start', timestamp: new Date()});322+await runBuild();323+await sendMessage({kind: 'stop', timestamp: new Date()});324+```325+326 ### Debugging327 328 #### Detailed error329 62 unmodified lines