Allow `stdin` to be a sync/async iterable (#604)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent 2f89219 · Browse files · 7 files·+175 added−15 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+175 added−15 removed
- tests:+70 added−0 removed
- other:+105 added−15 removed
Provenance
- Commit
ec380db- Tree
db2b71b- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
2f89219
7 files changed+175 added−15 removed
modified:lib/stdio.js+36 added
12345678910111213141516171819202122232425262728293031323334353637383940414243 unmodified linesimport {Readable} from 'node:stream';import {isStream} from 'is-stream';
const aliases = ['stdin', 'stdout', 'stderr'];
const isIterableStdin = stdinOption => typeof stdinOption === 'object' && stdinOption !== null && !isStream(stdinOption) && (typeof stdinOption[Symbol.asyncIterator] === 'function' || typeof stdinOption[Symbol.iterator] === 'function');
const transformStdioItem = (stdioItem, index) => { if (index === 0 && isIterableStdin(stdioItem)) { return 'pipe'; }
return stdioItem;};
const transformStdio = stdio => Array.isArray(stdio) ? stdio.map((stdioItem, index) => transformStdioItem(stdioItem, index)) : stdio;
const getStdioStreams = stdio => { if (!Array.isArray(stdio) || !isIterableStdin(stdio[0])) { return {}; }
const stdinIterableStream = Readable.from(stdio[0]); return {stdinIterableStream};};
export const handleStdioOption = options => { const stdio = normalizeStdio(options); const stdioStreams = getStdioStreams(stdio); options.stdio = transformStdio(stdio); return stdioStreams;};
const hasAlias = options => aliases.some(alias => options[alias] !== undefined);
export const normalizeStdio = options => { if (!options) {43 unmodified linesmodified:lib/stream.js+35 added-5 removed
1234567789101112131415161718192021222324142526272829303132332 unmodified lines36373839254041424344454647484955 unmodified lines10510610710810911011111211311411511611711890119120121122123124125961261271281291306 unmodified linesimport {once} from 'node:events';import {createReadStream, readFileSync} from 'node:fs';import {setTimeout} from 'node:timers/promises';import {isStream} from 'is-stream';import getStream, {getStreamAsBuffer} from 'get-stream';import mergeStreams from '@sindresorhus/merge-streams';
export const validateInputOptions = ({input, inputFile}) => {export const validateInputOptions = ({input, inputFile}, {stdinIterableStream}) => { if (input !== undefined && inputFile !== undefined) { throw new TypeError('The `input` and `inputFile` options cannot be both set.'); }
if (stdinIterableStream !== undefined) { if (input !== undefined) { throw new TypeError('The `stdin` option cannot be an iterable when the `input` option is set.'); }
if (inputFile !== undefined) { throw new TypeError('The `stdin` option cannot be an iterable when the `inputFile` option is set.'); } }};
// `input` and `inputFile` option in sync modeexport const handleInputSync = ({input, inputFile}) => {export const handleInputSync = ({input, inputFile}, {stdinIterableStream}) => { if (stdinIterableStream !== undefined) { throw new TypeError('The `stdin` option cannot be an iterable in sync mode'); }
const inputOption = typeof inputFile === 'string' ? readFileSync(inputFile) : input;
if (isStream(inputOption)) { throw new TypeError('The `input` option cannot be a stream in sync mode');2 unmodified lines return inputOption;};
// `input` and `inputFile` option in async modeexport const handleInput = (spawned, {input, inputFile}) => {export const handleInput = (spawned, {input, inputFile}, {stdinIterableStream}) => { if (stdinIterableStream !== undefined) { stdinIterableStream.pipe(spawned.stdin); return; }
const inputOption = typeof inputFile === 'string' ? createReadStream(inputFile) : input;
if (inputOption === undefined) { return;55 unmodified lines const buffer = await getStreamAsBuffer(stream, {maxBuffer}); return buffer.toString(encoding);};
// Handle any errors thrown by the iterable passed to the `stdin` option, if any.// We do not consume nor wait on that stream though, since it could potentially be infinite (like `process.stdin` in an interactive TTY).const throwOnStreamsError = streams => streams.filter(Boolean).map(stream => throwOnStreamError(stream));
const throwOnStreamError = async stream => { const [error] = await once(stream, 'error'); throw error;};
// Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all)export const getSpawnedResult = async (spawned, {encoding, buffer, maxBuffer}, processDone) => {export const getSpawnedResult = async (spawned, {encoding, buffer, maxBuffer}, {stdinIterableStream}, processDone) => { const stdoutPromise = getStreamPromise(spawned.stdout, {encoding, buffer, maxBuffer}); const stderrPromise = getStreamPromise(spawned.stderr, {encoding, buffer, maxBuffer}); const allPromise = getStreamPromise(spawned.all, {encoding, buffer, maxBuffer: maxBuffer * 2}); const processDoneOrStreamsError = Promise.race([processDone, ...throwOnStreamsError([stdinIterableStream])]);
try { return await Promise.all([processDone, stdoutPromise, stderrPromise, allPromise]); return await Promise.all([processDoneOrStreamsError, stdoutPromise, stderrPromise, allPromise]); } catch (error) { spawned.kill(); return Promise.all([ {error, signal: error.signal, timedOut: error.timedOut},6 unmodified linesmodified:test/stream.js+70 added
95 unmodified lines96 t.is(stderr, undefined);97 t.is(all, undefined);98 });99 100+test('stdin option can be a sync iterable of strings', async t => {101+ const {stdout} = await execa('stdin.js', {stdin: ['foo', 'bar']});102+ t.is(stdout, 'foobar');103+});104+105+const textEncoder = new TextEncoder();106+const binaryFoo = textEncoder.encode('foo');107+const binaryBar = textEncoder.encode('bar');108+109+test('stdin option can be a sync iterable of Uint8Arrays', async t => {110+ const {stdout} = await execa('stdin.js', {stdin: [binaryFoo, binaryBar]});111+ t.is(stdout, 'foobar');112+});113+114+const stringGenerator = function * () {115+ yield * ['foo', 'bar'];116+};117+118+const binaryGenerator = function * () {119+ yield * [binaryFoo, binaryBar];120+};121+122+const throwingGenerator = function * () {123+ yield 'foo';124+ throw new Error('generator error');125+};126+127+test('stdin option can be an async iterable of strings', async t => {128+ const {stdout} = await execa('stdin.js', {stdin: stringGenerator()});129+ t.is(stdout, 'foobar');130+});131+132+test('stdin option can be an async iterable of Uint8Arrays', async t => {133+ const {stdout} = await execa('stdin.js', {stdin: binaryGenerator()});134+ t.is(stdout, 'foobar');135+});136+137+test('stdin option cannot be a sync iterable with execa.sync()', t => {138+ t.throws(() => {139+ execaSync('stdin.js', {stdin: ['foo', 'bar']});140+ }, {message: /an iterable in sync mode/});141+});142+143+test('stdin option cannot be an async iterable with execa.sync()', t => {144+ t.throws(() => {145+ execaSync('stdin.js', {stdin: stringGenerator()});146+ }, {message: /an iterable in sync mode/});147+});148+149+test('stdin option cannot be an iterable when "input" is used', t => {150+ t.throws(() => {151+ execa('stdin.js', {stdin: ['foo', 'bar'], input: 'foobar'});152+ }, {message: /when the `input` option/});153+});154+155+test('stdin option cannot be an iterable when "inputFile" is used', t => {156+ t.throws(() => {157+ execa('stdin.js', {stdin: ['foo', 'bar'], inputFile: 'dummy.txt'});158+ }, {message: /when the `inputFile` option/});159+});160+161+test('stdin option cannot be a generic iterable string', async t => {162+ await t.throwsAsync(() => execa('stdin.js', {stdin: 'foobar'}), {code: 'ERR_INVALID_SYNC_FORK_INPUT'});163+});164+165+test('stdin option handles errors in iterables', async t => {166+ const {originalMessage} = await t.throwsAsync(() => execa('stdin.js', {stdin: throwingGenerator()}));167+ t.is(originalMessage, 'generator error');168+});169+170 test('input option can be a String', async t => {171 const {stdout} = await execa('stdin.js', {input: 'foobar'});172 t.is(stdout, 'foobar');173 });203 unmodified linesmodified:index.d.ts+5 added-1 removed
10 unmodified lines11 | Stream12 | number13 | undefined;14 15+export type StdinOption = StdioOption | Iterable<string | Uint8Array> | AsyncIterable<string | Uint8Array>;16+17 type EncodingOption =18 | 'utf8'19 // eslint-disable-next-line unicorn/text-encoding-identifier-case20 | 'utf-8'66 unmodified lines87 88 /**89 Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).90 91+ It can also be an [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) or an [`AsyncIterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols), providing neither [`execaSync()`](#execasyncfile-arguments-options), the [`input` option](#input) nor the [`inputFile` option](#inputfile) is used.92+93 @default `inherit` with `$`, `pipe` otherwise94 */91- readonly stdin?: StdioOption;95+ readonly stdin?: StdinOption;96 97 /**98 Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).99 900 unmodified linesmodified:index.js+8 added-8 removed
5 unmodified lines6 import stripFinalNewline from 'strip-final-newline';7 import {npmRunPathEnv} from 'npm-run-path';8 import onetime from 'onetime';9 import {makeError} from './lib/error.js';10-import {normalizeStdio, normalizeStdioNode} from './lib/stdio.js';10+import {handleStdioOption, normalizeStdioNode} from './lib/stdio.js';11 import {spawnedKill, spawnedCancel, setupTimeout, validateTimeout, setExitHandler} from './lib/kill.js';12 import {addPipeMethods} from './lib/pipe.js';13 import {validateInputOptions, handleInput, getSpawnedResult, makeAllStream, handleInputSync} from './lib/stream.js';14 import {mergePromise, getSpawnedPromise} from './lib/promise.js';36 unmodified lines51 };52 53 options.env = getEnv(options);54 55- options.stdio = normalizeStdio(options);55+ const stdioStreams = handleStdioOption(options);56 57 if (process.platform === 'win32' && path.basename(file, '.exe') === 'cmd') {58 // #11659 args.unshift('/q');60 }61 62- return {file, args, options, parsed};62+ return {file, args, options, parsed, stdioStreams};63 };64 65 const handleOutput = (options, value, error) => {66 if (typeof value !== 'string' && !Buffer.isBuffer(value)) {14 unmodified lines81 const escapedCommand = getEscapedCommand(file, args);82 logCommand(escapedCommand, parsed.options);83 84 validateTimeout(parsed.options);85- validateInputOptions(parsed.options);85+ validateInputOptions(parsed.options, parsed.stdioStreams);86 87 let spawned;88 try {89 spawned = childProcess.spawn(parsed.file, parsed.args, parsed.options);25 unmodified lines115 spawned.kill = spawnedKill.bind(null, spawned.kill.bind(spawned));116 spawned.cancel = spawnedCancel.bind(null, spawned, context);117 118 const handlePromise = async () => {119- const [{error, exitCode, signal, timedOut}, stdoutResult, stderrResult, allResult] = await getSpawnedResult(spawned, parsed.options, processDone);119+ const [{error, exitCode, signal, timedOut}, stdoutResult, stderrResult, allResult] = await getSpawnedResult(spawned, parsed.options, parsed.stdioStreams, processDone);120 const stdout = handleOutput(parsed.options, stdoutResult);121 const stderr = handleOutput(parsed.options, stderrResult);122 const all = handleOutput(parsed.options, allResult);123 35 unmodified lines159 };160 161 const handlePromiseOnce = onetime(handlePromise);162 163- handleInput(spawned, parsed.options);163+ handleInput(spawned, parsed.options, parsed.stdioStreams);164 165 spawned.all = makeAllStream(spawned, parsed.options);166 167 addPipeMethods(spawned);6 unmodified lines174 const command = joinCommand(file, args);175 const escapedCommand = getEscapedCommand(file, args);176 logCommand(escapedCommand, parsed.options);177 178- validateInputOptions(parsed.options);179- const inputOption = handleInputSync(parsed.options);178+ validateInputOptions(parsed.options, parsed.stdioStreams);179+ const inputOption = handleInputSync(parsed.options, parsed.stdioStreams);180 181 let result;182 try {183 result = childProcess.spawnSync(parsed.file, parsed.args, {...parsed.options, input: inputOption});130 unmodified linesmodified:index.test-d.ts+18 added
126 unmodified lines127 expectType<string>(execaError.shortMessage);128 expectType<string | undefined>(execaError.originalMessage);129 }130 131+const stringGenerator = function * () {132+ yield '';133+};134+135+const binaryGenerator = function * () {136+ yield new Uint8Array(0);137+};138+139+const numberGenerator = function * () {140+ yield 0;141+};142+143 /* eslint-disable @typescript-eslint/no-floating-promises */144 execa('unicorns', {cleanup: false});145 execa('unicorns', {preferLocal: false});146 execa('unicorns', {localDir: '.'});10 unmodified lines157 execa('unicorns', {stdin: 'ipc'});158 execa('unicorns', {stdin: 'ignore'});159 execa('unicorns', {stdin: 'inherit'});160 execa('unicorns', {stdin: process.stdin});161+execa('unicorns', {stdin: ['']});162+execa('unicorns', {stdin: [new Uint8Array(0)]});163+execa('unicorns', {stdin: stringGenerator()});164+execa('unicorns', {stdin: binaryGenerator()});165+expectError(execa('unicorns', {stdin: [0]}));166+expectError(execa('unicorns', {stdin: numberGenerator()}));167 execa('unicorns', {stdin: 1});168 execa('unicorns', {stdin: undefined});169 execa('unicorns', {stdout: 'pipe'});170 execa('unicorns', {stdout: 'overlapped'});195 unmodified linesmodified:readme.md+3 added-1 removed
557 unmodified lines558 If the input is not a file, use the [`input` option](#input) instead.559 560 #### stdin561 562-Type: `string | number | Stream | undefined`\562+Type: `string | number | Stream | undefined | Iterable<string | Uint8Array> | AsyncIterable<string | Uint8Array>`\563 Default: `inherit` with [`$`](#command), `pipe` otherwise564 565 Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).566 567+It can also be an [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) or an [`AsyncIterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols), providing neither [`execaSync()`](#execasyncfile-arguments-options), the [`input` option](#input) nor the [`inputFile` option](#inputfile) is used.568+569 #### stdout570 571 Type: `string | number | Stream | undefined`\572 Default: `pipe`241 unmodified lines