Skip to content
Myr

Allow passing generators to the `std*` options (#693)

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

authored by ehmicky · committed by GitHub · parent 1825aea · Browse files · 15 files+722 added−31 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+722 added−31 removed

  • tests:+420 added−1 removed
  • other:+302 added−30 removed

15 files+722 added−31 removed

added:docs/transform.md+57 added
modified:lib/stdio/async.js+14 added-2 removed
modified:lib/stdio/direction.js+1 added
added:lib/stdio/generator.js+109 added
1import {Duplex, Readable, PassThrough, getDefaultHighWaterMark} from 'node:stream';23/*4Generators can be used to transform/filter standard streams.56Generators have a simple syntax, yet allows all of the following:7- Sharing state between chunks, by using logic before the `for` loop8- Flushing logic, by using logic after the `for` loop9- Asynchronous logic10- Emitting multiple chunks from a single source chunk, even if spaced in time, by using multiple `yield`11- Filtering, by using no `yield`1213Therefore, there is no need to allow Node.js or web transform streams.1415The `highWaterMark` is kept as the default value, since this is what `childProcess.std*` uses.1617We ensure `objectMode` is `false` for better buffering.1819Chunks are currently processed serially. We could add a `concurrency` option to parallelize in the future.2021We return a `Duplex`, created by `Duplex.from()` made of a writable stream and a readable stream, piped to each other.22- The writable stream is a simple `PassThrough`, so it only forwards data to the readable part.23- The `PassThrough` is read as an iterable using `passThrough.iterator()`.24- This iterable is transformed to another iterable, by applying the encoding generators.25 Those convert the chunk type from `Buffer` to `string | Uint8Array` depending on the encoding option.26- This new iterable is transformed again to another one, this time by applying the user-supplied generator.27- Finally, `Readable.from()` is used to convert this final iterable to a `Readable` stream.28*/29export const generatorToTransformStream = ({value}, {encoding}) => {30 const objectMode = false;31 const highWaterMark = getDefaultHighWaterMark(objectMode);32 const passThrough = new PassThrough({objectMode, highWaterMark, destroy: destroyPassThrough});33 const iterable = passThrough.iterator();34 const encodedIterable = applyEncoding(iterable, encoding);35 const mappedIterable = value(encodedIterable);36 const readableStream = Readable.from(mappedIterable, {objectMode, highWaterMark});37 const duplexStream = Duplex.from({writable: passThrough, readable: readableStream});38 return {value: duplexStream};39};4041/*42When an error is thrown in a generator, the PassThrough is aborted.4344This creates a race condition for which error is propagated, due to the Duplex throwing twice:45- The writable side is aborted (PassThrough)46- The readable side propagate the generator's error4748In order for the later to win that race, we need to wait one microtask.49- However we wait one macrotask instead to be on the safe side50- See https://github.com/sindresorhus/execa/pull/693#discussion_r145380945051*/52const destroyPassThrough = (error, done) => {53 setTimeout(() => {54 done(error);55 }, 0);56};5758// When using generators, add an internal generator that converts chunks from `Buffer` to `string` or `Uint8Array`.59// This allows generator functions to operate with those types instead.60const applyEncoding = (iterable, encoding) => encoding === 'buffer'61 ? encodingStartBufferGenerator(iterable)62 : encodingStartStringGenerator(iterable);6364/*65Chunks might be Buffer, Uint8Array or strings since:66- `childProcess.stdout|stderr` emits Buffers67- `childProcess.stdin.write()` accepts Buffer, Uint8Array or string68- Previous generators might return Uint8Array or string6970However, those are converted to Buffer:71- on writes: `Duplex.writable` `decodeStrings: true` default option72- on reads: `Duplex.readable` `readableEncoding: null` default option73*/74const encodingStartStringGenerator = async function * (chunks) {75 const textDecoder = new TextDecoder();7677 for await (const chunk of chunks) {78 yield textDecoder.decode(chunk, {stream: true});79 }8081 const lastChunk = textDecoder.decode();82 if (lastChunk !== '') {83 yield lastChunk;84 }85};8687const encodingStartBufferGenerator = async function * (chunks) {88 for await (const chunk of chunks) {89 yield new Uint8Array(chunk);90 }91};9293// `childProcess.stdin|stdout|stderr|stdio` is directly mutated.94export const pipeGenerator = (spawned, {value, direction, index}) => {95 if (direction === 'output') {96 spawned.stdio[index].pipe(value);97 } else {98 value.pipe(spawned.stdio[index]);99 }100101 const streamProperty = PROCESS_STREAM_PROPERTIES[index];102 if (streamProperty !== undefined) {103 spawned[streamProperty] = value;104 }105106 spawned.stdio[index] = value;107};108109const PROCESS_STREAM_PROPERTIES = ['stdin', 'stdout', 'stderr'];
modified:lib/stdio/handle.js+4 added-4 removed
9 unmodified lines
10 const [stdinStreams, ...otherStreamsGroups] = stdio.map((stdioOption, index) => getStdioStreams(stdioOption, index));11 const stdioStreamsGroups = [[...stdinStreams, ...handleInputOptions(options)], ...otherStreamsGroups]12 .map(stdioStreams => validateStreams(stdioStreams))13 .map(stdioStreams => addStreamDirection(stdioStreams))14 .map(stdioStreams => addStreamsProperties(stdioStreams, addProperties));14 .map(stdioStreams => addStreamsProperties(stdioStreams, addProperties, options));15 options.stdio = transformStdio(stdioStreamsGroups);16 return stdioStreamsGroups;17};18
31 unmodified lines
50// However, we do allow it if the array has a single item.51const INVALID_STDIO_ARRAY_OPTIONS = ['ignore', 'ipc'];5253const getStdioStream = ({stdioOption, optionName, index, isStdioArray}) => {54 const type = getStdioOptionType(stdioOption);54 const type = getStdioOptionType(stdioOption, optionName);55 const stdioStream = {type, value: stdioOption, optionName, index};56 return handleNativeStream(stdioStream, isStdioArray);57};58
18 unmodified lines
7778// Some `stdio` values require Execa to create streams.79// For example, file paths create file read/write streams.80// Those transformations are specified in `addProperties`, which is both direction-specific and type-specific.81const addStreamsProperties = (stdioStreams, addProperties) => stdioStreams.map(stdioStream => ({81const addStreamsProperties = (stdioStreams, addProperties, options) => stdioStreams.map(stdioStream => ({82 ...stdioStream,83 ...addProperties[stdioStream.direction][stdioStream.type]?.(stdioStream),83 ...addProperties[stdioStream.direction][stdioStream.type]?.(stdioStream, options),84}));8586// When the `std*: Iterable | WebStream | URL | filePath`, `input` or `inputFile` option is used, we pipe to `spawned.std*`.87// When the `std*: Array` option is used, we emulate some of the native values ('inherit', Node.js stream and file descriptor integer). To do so, we also need to pipe to `spawned.std*`.
11 unmodified lines
modified:lib/stdio/sync.js+2 added
23 unmodified lines
24};2526const addPropertiesSync = {27 input: {28 generator: forbiddenIfSync,29 fileUrl: ({value}) => ({value: bufferToUint8Array(readFileSync(value)), type: 'uint8Array'}),30 filePath: ({value}) => ({value: bufferToUint8Array(readFileSync(value.file)), type: 'uint8Array'}),31 webStream: forbiddenIfSync,32 nodeStream: forbiddenIfSync,33 iterable: forbiddenIfSync,34 native: forbiddenIfStreamSync,35 },36 output: {37 generator: forbiddenIfSync,38 filePath: ({value}) => ({value: value.file}),39 webStream: forbiddenIfSync,40 nodeStream: forbiddenIfSync,41 iterable: forbiddenIfSync,
40 unmodified lines
modified:lib/stdio/type.js+13 added-1 removed
1import {isStream as isNodeStream} from 'is-stream';2import {isUint8Array} from './utils.js';34// The `stdin`/`stdout`/`stderr` option can be of many types. This detects it.5export const getStdioOptionType = stdioOption => {5export const getStdioOptionType = (stdioOption, optionName) => {6 if (isAsyncGenerator(stdioOption)) {7 return 'generator';8 }910 if (isSyncGenerator(stdioOption)) {11 throw new TypeError(`The \`${optionName}\` option must use an asynchronous generator, not a synchronous one.`);12 }1314 if (isUrl(stdioOption)) {15 return 'fileUrl';16 }17
19 unmodified lines
3738 return 'native';39};4041const isAsyncGenerator = stdioOption => Object.prototype.toString.call(stdioOption) === '[object AsyncGeneratorFunction]';42const isSyncGenerator = stdioOption => Object.prototype.toString.call(stdioOption) === '[object GeneratorFunction]';4344export const isUrl = stdioOption => Object.prototype.toString.call(stdioOption) === '[object URL]';45export const isRegularUrl = stdioOption => isUrl(stdioOption) && stdioOption.protocol !== 'file:';4647const isFilePathObject = stdioOption => typeof stdioOption === 'object'
15 unmodified lines
63 && (typeof stdioOption[Symbol.asyncIterator] === 'function' || typeof stdioOption[Symbol.iterator] === 'function');6465// Convert types to human-friendly strings for error messages66export const TYPE_TO_MESSAGE = {67 generator: 'a generator',68 fileUrl: 'a file URL',69 filePath: 'a file path string',70 webStream: 'a web stream',71 nodeStream: 'a Node.js stream',
5 unmodified lines
added:test/fixtures/all-fail.js+6 added
added:test/fixtures/all.js+3 added
added:test/fixtures/nested-inherit.js+10 added
1#!/usr/bin/env node2import {execa} from '../../index.js';34const uppercaseGenerator = async function * (chunks) {5 for await (const chunk of chunks) {6 yield chunk.toUpperCase();7 }8};910await execa('noop-fd.js', ['1'], {stdout: ['inherit', uppercaseGenerator]});
modified:test/fixtures/noop-fail.js+1 added-1 removed
1#!/usr/bin/env node2import process from 'node:process';3import {writeSync} from 'node:fs';45writeSync(Number(process.argv[2]), 'foobar');5writeSync(Number(process.argv[2]), process.argv[3] || 'foobar');6process.exit(2);
added:test/stdio/generator.js+400 added
1import {Buffer} from 'node:buffer';2import {readFile, writeFile, rm} from 'node:fs/promises';3import {getDefaultHighWaterMark, PassThrough} from 'node:stream';4import {setTimeout} from 'node:timers/promises';5import test from 'ava';6import getStream from 'get-stream';7import tempfile from 'tempfile';8import {execa, execaSync} from '../../index.js';9import {setFixtureDir} from '../helpers/fixtures-dir.js';10import {getStdio} from '../helpers/stdio.js';1112setFixtureDir();1314const foobarString = 'foobar';15const foobarUppercase = foobarString.toUpperCase();16const foobarBuffer = Buffer.from(foobarString);17const foobarUint8Array = new TextEncoder().encode(foobarString);1819const uppercaseGenerator = async function * (chunks) {20 for await (const chunk of chunks) {21 yield chunk.toUpperCase();22 }23};2425const testGeneratorInput = async (t, index) => {26 const {stdout} = await execa('stdin-fd.js', [`${index}`], getStdio(index, [foobarUint8Array, uppercaseGenerator]));27 t.is(stdout, foobarUppercase);28};2930test('Can use generators with result.stdin', testGeneratorInput, 0);31test('Can use generators with result.stdio[*] as input', testGeneratorInput, 3);3233const testGeneratorInputPipe = async (t, index, useShortcutProperty, encoding) => {34 const childProcess = execa('stdin-fd.js', [`${index}`], getStdio(index, uppercaseGenerator));35 const stream = useShortcutProperty ? childProcess.stdin : childProcess.stdio[index];36 stream.end(encoding === 'buffer' ? foobarBuffer : foobarBuffer.toString(encoding), encoding);37 const {stdout} = await childProcess;38 t.is(stdout, foobarUppercase);39};4041test('Can use generators with childProcess.stdio[0] and default encoding', testGeneratorInputPipe, 0, false, 'utf8');42test('Can use generators with childProcess.stdin and default encoding', testGeneratorInputPipe, 0, true, 'utf8');43test('Can use generators with childProcess.stdio[0] and encoding "buffer"', testGeneratorInputPipe, 0, false, 'buffer');44test('Can use generators with childProcess.stdin and encoding "buffer"', testGeneratorInputPipe, 0, true, 'buffer');45test('Can use generators with childProcess.stdio[0] and encoding "hex"', testGeneratorInputPipe, 0, false, 'hex');46test('Can use generators with childProcess.stdin and encoding "hex"', testGeneratorInputPipe, 0, true, 'hex');4748test('Can use generators with childProcess.stdio[*] as input', async t => {49 const childProcess = execa('stdin-fd.js', ['3'], getStdio(3, [new Uint8Array(), uppercaseGenerator]));50 childProcess.stdio[3].write(foobarUint8Array);51 const {stdout} = await childProcess;52 t.is(stdout, foobarUppercase);53});5455const testGeneratorOutput = async (t, index, reject, useShortcutProperty) => {56 const fixtureName = reject ? 'noop-fd.js' : 'noop-fail.js';57 const {stdout, stderr, stdio} = await execa(fixtureName, [`${index}`, foobarString], {...getStdio(index, uppercaseGenerator), reject});58 const result = useShortcutProperty ? [stdout, stderr][index - 1] : stdio[index];59 t.is(result, foobarUppercase);60};6162test('Can use generators with result.stdio[1]', testGeneratorOutput, 1, true, false);63test('Can use generators with result.stdout', testGeneratorOutput, 1, true, true);64test('Can use generators with result.stdio[2]', testGeneratorOutput, 2, true, false);65test('Can use generators with result.stderr', testGeneratorOutput, 2, true, true);66test('Can use generators with result.stdio[*] as output', testGeneratorOutput, 3, true, false);67test('Can use generators with error.stdio[1]', testGeneratorOutput, 1, false, false);68test('Can use generators with error.stdout', testGeneratorOutput, 1, false, true);69test('Can use generators with error.stdio[2]', testGeneratorOutput, 2, false, false);70test('Can use generators with error.stderr', testGeneratorOutput, 2, false, true);71test('Can use generators with error.stdio[*] as output', testGeneratorOutput, 3, false, false);7273const testGeneratorOutputPipe = async (t, index, useShortcutProperty) => {74 const childProcess = execa('noop-fd.js', [`${index}`, foobarString], {...getStdio(index, uppercaseGenerator), buffer: false});75 const stream = useShortcutProperty ? [childProcess.stdout, childProcess.stderr][index - 1] : childProcess.stdio[index];76 const [result] = await Promise.all([getStream(stream), childProcess]);77 t.is(result, foobarUppercase);78};7980test('Can use generators with childProcess.stdio[1]', testGeneratorOutputPipe, 1, false);81test('Can use generators with childProcess.stdout', testGeneratorOutputPipe, 1, true);82test('Can use generators with childProcess.stdio[2]', testGeneratorOutputPipe, 2, false);83test('Can use generators with childProcess.stderr', testGeneratorOutputPipe, 2, true);84test('Can use generators with childProcess.stdio[*] as output', testGeneratorOutputPipe, 3, false);8586const testGeneratorAll = async (t, reject) => {87 const fixtureName = reject ? 'all.js' : 'all-fail.js';88 const {all} = await execa(fixtureName, {all: true, reject, stdout: uppercaseGenerator, stderr: uppercaseGenerator});89 t.is(all, 'STDOUT\nSTDERR');90};9192test('Can use generators with result.all', testGeneratorAll, true);93test('Can use generators with error.all', testGeneratorAll, false);9495test('Can use generators with input option', async t => {96 const {stdout} = await execa('stdin-fd.js', ['0'], {stdin: uppercaseGenerator, input: foobarUint8Array});97 t.is(stdout, foobarUppercase);98});99100const syncGenerator = function * () {};101102const testSyncGenerator = (t, index) => {103 t.throws(() => {104 execa('empty.js', getStdio(index, syncGenerator));105 }, {message: /asynchronous generator/});106};107108test('Cannot use sync generators with stdin', testSyncGenerator, 0);109test('Cannot use sync generators with stdout', testSyncGenerator, 1);110test('Cannot use sync generators with stderr', testSyncGenerator, 2);111test('Cannot use sync generators with stdio[*]', testSyncGenerator, 3);112113const testSyncMethods = (t, index) => {114 t.throws(() => {115 execaSync('empty.js', getStdio(index, uppercaseGenerator));116 }, {message: /cannot be a generator/});117};118119test('Cannot use generators with sync methods and stdin', testSyncMethods, 0);120test('Cannot use generators with sync methods and stdout', testSyncMethods, 1);121test('Cannot use generators with sync methods and stderr', testSyncMethods, 2);122test('Cannot use generators with sync methods and stdio[*]', testSyncMethods, 3);123124const repeatHighWaterMark = 10;125126const writerGenerator = async function * (chunks) {127 // eslint-disable-next-line no-unused-vars128 for await (const chunk of chunks) {129 for (let index = 0; index < getDefaultHighWaterMark() * repeatHighWaterMark; index += 1) {130 yield '.';131 }132 }133};134135const passThroughGenerator = async function * (chunks) {136 for await (const chunk of chunks) {137 yield `${chunk.length}`;138 }139};140141test('Stream respects highWaterMark', async t => {142 const index = 1;143 const {stdout} = await execa('noop-fd.js', [`${index}`], getStdio(index, [writerGenerator, passThroughGenerator]));144 t.is(stdout, `${getDefaultHighWaterMark()}`.repeat(repeatHighWaterMark));145});146147const typeofGenerator = async function * (chunks) {148 for await (const chunk of chunks) {149 yield Object.prototype.toString.call(chunk);150 }151};152153const testGeneratorFirstEncoding = async (t, input, encoding) => {154 const childProcess = execa('stdin.js', {stdin: typeofGenerator, encoding});155 childProcess.stdin.end(input);156 const {stdout} = await childProcess;157 const output = Buffer.from(stdout, encoding).toString();158 t.is(output, encoding === 'buffer' ? '[object Uint8Array]' : '[object String]');159};160161test('First generator argument is string with default encoding, with string writes', testGeneratorFirstEncoding, foobarString, 'utf8');162test('First generator argument is string with default encoding, with Buffer writes', testGeneratorFirstEncoding, foobarBuffer, 'utf8');163test('First generator argument is string with default encoding, with Uint8Array writes', testGeneratorFirstEncoding, foobarUint8Array, 'utf8');164test('First generator argument is Uint8Array with encoding "buffer", with string writes', testGeneratorFirstEncoding, foobarString, 'buffer');165test('First generator argument is Uint8Array with encoding "buffer", with Buffer writes', testGeneratorFirstEncoding, foobarBuffer, 'buffer');166test('First generator argument is Uint8Array with encoding "buffer", with Uint8Array writes', testGeneratorFirstEncoding, foobarUint8Array, 'buffer');167test('First generator argument is Uint8Array with encoding "hex", with string writes', testGeneratorFirstEncoding, foobarString, 'hex');168test('First generator argument is Uint8Array with encoding "hex", with Buffer writes', testGeneratorFirstEncoding, foobarBuffer, 'hex');169test('First generator argument is Uint8Array with encoding "hex", with Uint8Array writes', testGeneratorFirstEncoding, foobarUint8Array, 'hex');170171const outputGenerator = async function * (input, chunks) {172 // eslint-disable-next-line no-unused-vars173 for await (const chunk of chunks) {174 yield input;175 }176};177178const testGeneratorNextEncoding = async (t, input, encoding) => {179 const {stdout} = await execa('noop.js', ['other'], {stdout: [outputGenerator.bind(undefined, input), typeofGenerator], encoding});180 const output = Buffer.from(stdout, encoding).toString();181 t.is(output, encoding === 'buffer' ? '[object Uint8Array]' : '[object String]');182};183184test('Next generator argument is string with default encoding, with string writes', testGeneratorNextEncoding, foobarString, 'utf8');185test('Next generator argument is string with default encoding, with Buffer writes', testGeneratorNextEncoding, foobarBuffer, 'utf8');186test('Next generator argument is string with default encoding, with Uint8Array writes', testGeneratorNextEncoding, foobarUint8Array, 'utf8');187test('Next generator argument is Uint8Array with encoding "buffer", with string writes', testGeneratorNextEncoding, foobarString, 'buffer');188test('Next generator argument is Uint8Array with encoding "buffer", with Buffer writes', testGeneratorNextEncoding, foobarBuffer, 'buffer');189test('Next generator argument is Uint8Array with encoding "buffer", with Uint8Array writes', testGeneratorNextEncoding, foobarUint8Array, 'buffer');190test('Next generator argument is Uint8Array with encoding "hex", with string writes', testGeneratorNextEncoding, foobarString, 'hex');191test('Next generator argument is Uint8Array with encoding "hex", with Buffer writes', testGeneratorNextEncoding, foobarBuffer, 'hex');192test('Next generator argument is Uint8Array with encoding "hex", with Uint8Array writes', testGeneratorNextEncoding, foobarUint8Array, 'hex');193194const testGeneratorReturnType = async (t, input, encoding) => {195 const {stdout} = await execa('noop.js', ['other'], {stdout: outputGenerator.bind(undefined, input), encoding});196 const output = Buffer.from(stdout, encoding).toString();197 t.is(output, foobarString);198};199200test('Generator can return string with default encoding', testGeneratorReturnType, foobarString, 'utf8');201test('Generator can return Uint8Array with default encoding', testGeneratorReturnType, foobarUint8Array, 'utf8');202test('Generator can return string with encoding "buffer"', testGeneratorReturnType, foobarString, 'buffer');203test('Generator can return Uint8Array with encoding "buffer"', testGeneratorReturnType, foobarUint8Array, 'buffer');204test('Generator can return string with encoding "hex"', testGeneratorReturnType, foobarString, 'hex');205test('Generator can return Uint8Array with encoding "hex"', testGeneratorReturnType, foobarUint8Array, 'hex');206207const multibyteChar = '\u{1F984}';208const multibyteString = `${multibyteChar}${multibyteChar}`;209const multibyteUint8Array = new TextEncoder().encode(multibyteString);210const breakingLength = multibyteUint8Array.length * 0.75;211const brokenSymbol = '\uFFFD';212213const noopGenerator = async function * (chunks) {214 for await (const chunk of chunks) {215 yield chunk;216 }217};218219test('Generator handles multibyte characters with Uint8Array', async t => {220 const childProcess = execa('stdin.js', {stdin: noopGenerator});221 childProcess.stdin.write(multibyteUint8Array.slice(0, breakingLength));222 await setTimeout(0);223 childProcess.stdin.end(multibyteUint8Array.slice(breakingLength));224 const {stdout} = await childProcess;225 t.is(stdout, multibyteString);226});227228test('Generator handles partial multibyte characters with Uint8Array', async t => {229 const {stdout} = await execa('stdin.js', {stdin: [multibyteUint8Array.slice(0, breakingLength), noopGenerator]});230 t.is(stdout, `${multibyteChar}${brokenSymbol}`);231});232233// eslint-disable-next-line require-yield234const noYieldGenerator = async function * (chunks) {235 // eslint-disable-next-line no-empty, no-unused-vars236 for await (const chunk of chunks) {}237};238239test('Generator can filter by not calling yield', async t => {240 const {stdout} = await execa('noop.js', {stdout: noYieldGenerator});241 t.is(stdout, '');242});243244const prefix = '> ';245const suffix = ' <';246247const multipleYieldGenerator = async function * (chunks) {248 for await (const chunk of chunks) {249 yield prefix;250 await setTimeout(0);251 yield chunk;252 await setTimeout(0);253 yield suffix;254 }255};256257test('Generator can yield multiple times at different moments', async t => {258 const {stdout} = await execa('noop-fd.js', ['1', foobarString], {stdout: multipleYieldGenerator});259 t.is(stdout, `${prefix}${foobarString}${suffix}`);260});261262const testInputFile = async (t, getOptions, reversed) => {263 const filePath = tempfile();264 await writeFile(filePath, foobarString);265 const {stdin, ...options} = getOptions(filePath);266 const reversedStdin = reversed ? stdin.reverse() : stdin;267 const {stdout} = await execa('stdin-fd.js', ['0'], {...options, stdin: reversedStdin});268 t.is(stdout, foobarUppercase);269 await rm(filePath);270};271272test('Can use generators with a file as input', testInputFile, filePath => ({stdin: [{file: filePath}, uppercaseGenerator]}), false);273test('Can use generators with a file as input, reversed', testInputFile, filePath => ({stdin: [{file: filePath}, uppercaseGenerator]}), true);274test('Can use generators with inputFile option', testInputFile, filePath => ({inputFile: filePath, stdin: uppercaseGenerator}), false);275276const testOutputFile = async (t, reversed) => {277 const filePath = tempfile();278 const stdoutOption = [uppercaseGenerator, {file: filePath}];279 const reversedStdoutOption = reversed ? stdoutOption.reverse() : stdoutOption;280 const {stdout} = await execa('noop-fd.js', ['1'], {stdout: reversedStdoutOption});281 t.is(stdout, foobarUppercase);282 t.is(await readFile(filePath, 'utf8'), foobarUppercase);283 await rm(filePath);284};285286test('Can use generators with a file as output', testOutputFile, false);287test('Can use generators with a file as output, reversed', testOutputFile, true);288289test('Can use generators to a Writable stream', async t => {290 const passThrough = new PassThrough();291 const [{stdout}, streamOutput] = await Promise.all([292 execa('noop-fd.js', ['1', foobarString], {stdout: [uppercaseGenerator, passThrough]}),293 getStream(passThrough),294 ]);295 t.is(stdout, foobarUppercase);296 t.is(streamOutput, foobarUppercase);297});298299test('Can use generators from a Readable stream', async t => {300 const passThrough = new PassThrough();301 const childProcess = execa('stdin-fd.js', ['0'], {stdin: [passThrough, uppercaseGenerator]});302 passThrough.end(foobarString);303 const {stdout} = await childProcess;304 t.is(stdout, foobarUppercase);305});306307test('Can use generators with "inherit"', async t => {308 const {stdout} = await execa('nested-inherit.js');309 t.is(stdout, foobarUppercase);310});311312const casedSuffix = 'k';313314const appendGenerator = async function * (chunks) {315 for await (const chunk of chunks) {316 yield `${chunk}${casedSuffix}`;317 }318};319320const testAppendInput = async (t, reversed) => {321 const stdin = [foobarUint8Array, uppercaseGenerator, appendGenerator];322 const reversedStdin = reversed ? stdin.reverse() : stdin;323 const {stdout} = await execa('stdin-fd.js', ['0'], {stdin: reversedStdin});324 const reversedSuffix = reversed ? casedSuffix.toUpperCase() : casedSuffix;325 t.is(stdout, `${foobarUppercase}${reversedSuffix}`);326};327328test('Can use multiple generators as input', testAppendInput, false);329test('Can use multiple generators as input, reversed', testAppendInput, true);330331const testAppendOutput = async (t, reversed) => {332 const stdoutOption = [uppercaseGenerator, appendGenerator];333 const reversedStdoutOption = reversed ? stdoutOption.reverse() : stdoutOption;334 const {stdout} = await execa('noop-fd.js', ['1', foobarString], {stdout: reversedStdoutOption});335 const reversedSuffix = reversed ? casedSuffix.toUpperCase() : casedSuffix;336 t.is(stdout, `${foobarUppercase}${reversedSuffix}`);337};338339test('Can use multiple generators as output', testAppendOutput, false);340test('Can use multiple generators as output, reversed', testAppendOutput, true);341342const maxBuffer = 10;343344test('Generators take "maxBuffer" into account', async t => {345 const bigString = '.'.repeat(maxBuffer);346 const {stdout} = await execa('noop.js', {maxBuffer, stdout: outputGenerator.bind(undefined, bigString)});347 t.is(stdout, bigString);348349 await t.throwsAsync(execa('noop.js', {maxBuffer, stdout: outputGenerator.bind(undefined, `${bigString}.`)}));350});351352const timeoutGenerator = async function * (timeout, chunks) {353 for await (const chunk of chunks) {354 await setTimeout(timeout);355 yield chunk;356 }357};358359test('Generators are awaited on success', async t => {360 const {stdout} = await execa('noop-fd.js', ['1', foobarString], {maxBuffer, stdout: timeoutGenerator.bind(undefined, 1e3)});361 t.is(stdout, foobarString);362});363364// eslint-disable-next-line require-yield365const throwingGenerator = async function * (chunks) {366 // eslint-disable-next-line no-unreachable-loop367 for await (const chunk of chunks) {368 throw new Error(`Generator error ${chunk}`);369 }370};371372test('Generators errors make process fail', async t => {373 await t.throwsAsync(374 execa('noop-fd.js', ['1', foobarString], {stdout: throwingGenerator}),375 {message: /Generator error foobar/},376 );377});378379// eslint-disable-next-line require-yield380const errorHandlerGenerator = async function * (state, chunks) {381 try {382 // eslint-disable-next-line no-unused-vars383 for await (const chunk of chunks) {384 await setTimeout(1e8);385 }386 } catch (error) {387 state.error = error;388 }389};390391test.serial('Process streams failures make generators throw', async t => {392 const state = {};393 const childProcess = execa('noop-fail.js', ['1'], {stdout: errorHandlerGenerator.bind(undefined, state)});394 const error = new Error('test');395 childProcess.stdout.emit('error', error);396 const thrownError = await t.throwsAsync(childProcess);397 t.is(error, thrownError);398 await setTimeout(0);399 t.is(state.error.code, 'ABORT_ERR');400});
modified:index.d.ts+17 added-8 removed
16 unmodified lines
17 | 'overlapped'18 | 'ignore'19 | 'inherit';2021type CommonStdioOption =21type CommonStdioOption<IsSync extends boolean = boolean> =22 | BaseStdioOption23 | 'ipc'24 | number25 | undefined26 | URL27 | {file: string};27 | {file: string}28 // TODO: Use either `Iterable<string>` or `Iterable<Uint8Array>` based on whether `encoding: 'buffer'` is used.29 // See https://github.com/sindresorhus/execa/issues/69430 | IfAsync<IsSync, ((chunks: Iterable<string | Uint8Array>) => AsyncGenerator<string | Uint8Array, void, void>)>;3132type InputStdioOption<IsSync extends boolean = boolean> =33 | Uint8Array34 | IfAsync<IsSync,
6 unmodified lines
41| Writable42| WritableStream>;4344export type StdinOption<IsSync extends boolean = boolean> =42 CommonStdioOption | InputStdioOption<IsSync>43 | Array<CommonStdioOption | InputStdioOption<IsSync>>;45 CommonStdioOption<IsSync> | InputStdioOption<IsSync>46 | Array<CommonStdioOption<IsSync> | InputStdioOption<IsSync>>;47export type StdoutStderrOption<IsSync extends boolean = boolean> =45 CommonStdioOption | OutputStdioOption<IsSync>46 | Array<CommonStdioOption | OutputStdioOption<IsSync>>;48 CommonStdioOption<IsSync> | OutputStdioOption<IsSync>49 | Array<CommonStdioOption<IsSync> | OutputStdioOption<IsSync>>;50export type StdioOption<IsSync extends boolean = boolean> =48 CommonStdioOption | InputStdioOption | OutputStdioOption<IsSync>49 | Array<CommonStdioOption | InputStdioOption | OutputStdioOption<IsSync>>;51 CommonStdioOption<IsSync> | InputStdioOption | OutputStdioOption<IsSync>52 | Array<CommonStdioOption<IsSync> | InputStdioOption | OutputStdioOption<IsSync>>;5354type StdioOptionsArray<IsSync extends boolean = boolean> = readonly [55 StdinOption<IsSync>,56 StdoutStderrOption<IsSync>,
186 unmodified lines
243 - an `Uint8Array`.244245 This can be an [array of values](https://github.com/sindresorhus/execa#redirect-stdinstdoutstderr-to-multiple-destinations) such as `['inherit', 'pipe']` or `[filePath, 'pipe']`.246247 This can also be an async generator function to transform the input. [Learn more.](https://github.com/sindresorhus/execa/tree/main/docs/transform.md)248249 @default `inherit` with `$`, `pipe` otherwise250 */251 readonly stdin?: StdinOption<IsSync>;252
11 unmodified lines
264 - a web [`WritableStream`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream).265266 This can be an [array of values](https://github.com/sindresorhus/execa#redirect-stdinstdoutstderr-to-multiple-destinations) such as `['inherit', 'pipe']` or `[filePath, 'pipe']`.267268 This can also be an async generator function to transform the output. [Learn more.](https://github.com/sindresorhus/execa/tree/main/docs/transform.md)269270 @default 'pipe'271 */272 readonly stdout?: StdoutStderrOption<IsSync>;273
11 unmodified lines
285 - a web [`WritableStream`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream).286287 This can be an [array of values](https://github.com/sindresorhus/execa#redirect-stdinstdoutstderr-to-multiple-destinations) such as `['inherit', 'pipe']` or `[filePath, 'pipe']`.288289 This can also be an async generator function to transform the output. [Learn more.](https://github.com/sindresorhus/execa/tree/main/docs/transform.md)290291 @default 'pipe'292 */293 readonly stderr?: StdoutStderrOption<IsSync>;294
928 unmodified lines
modified:index.test-d.ts+75 added-11 removed
549 unmodified lines
550expectType<string | undefined>(noRejectsSyncResult.message);551expectType<string | undefined>(noRejectsSyncResult.shortMessage);552expectType<string | undefined>(noRejectsSyncResult.originalMessage);553554const stringGenerator = function * () {554const emptyStringGenerator = function * () {555 yield '';556};557558const binaryGenerator = function * () {
9 unmodified lines
568};569570const fileUrl = new URL('file:///test');571572const stringOrUint8ArrayGenerator = async function * (chunks: Iterable<string | Uint8Array>) {573 for await (const chunk of chunks) {574 yield chunk;575 }576};577578const booleanGenerator = async function * (chunks: Iterable<boolean>) {579 for await (const chunk of chunks) {580 yield chunk;581 }582};583584const arrayGenerator = async function * (chunks: string[]) {585 for await (const chunk of chunks) {586 yield chunk;587 }588};589590const invalidReturnGenerator = async function * (chunks: Iterable<string>) {591 for await (const chunk of chunks) {592 yield chunk;593 }594595 return false;596};597598const syncGenerator = function * (chunks: Iterable<string>) {599 for (const chunk of chunks) {600 yield chunk;601 }602603 return false;604};605606expectAssignable<Options>({cleanup: false});607expectNotAssignable<SyncOptions>({cleanup: false});608expectAssignable<SyncOptions>({preferLocal: false});609
65 unmodified lines
675expectError(execa('unicorns', {stdin: [new WritableStream()]}));676expectError(execaSync('unicorns', {stdin: [new WritableStream()]}));677execa('unicorns', {stdin: new Uint8Array()});678execaSync('unicorns', {stdin: new Uint8Array()});645execa('unicorns', {stdin: stringGenerator()});646expectError(execaSync('unicorns', {stdin: stringGenerator()}));647execa('unicorns', {stdin: [stringGenerator()]});648expectError(execaSync('unicorns', {stdin: [stringGenerator()]}));679execa('unicorns', {stdin: emptyStringGenerator()});680expectError(execaSync('unicorns', {stdin: emptyStringGenerator()}));681execa('unicorns', {stdin: [emptyStringGenerator()]});682expectError(execaSync('unicorns', {stdin: [emptyStringGenerator()]}));683execa('unicorns', {stdin: binaryGenerator()});684expectError(execaSync('unicorns', {stdin: binaryGenerator()}));685execa('unicorns', {stdin: [binaryGenerator()]});686expectError(execaSync('unicorns', {stdin: [binaryGenerator()]}));
16 unmodified lines
703execa('unicorns', {stdin: 1});704execaSync('unicorns', {stdin: 1});705execa('unicorns', {stdin: [1]});706execaSync('unicorns', {stdin: [1]});707execa('unicorns', {stdin: stringOrUint8ArrayGenerator});708expectError(execaSync('unicorns', {stdin: stringOrUint8ArrayGenerator}));709execa('unicorns', {stdin: [stringOrUint8ArrayGenerator]});710expectError(execaSync('unicorns', {stdin: [stringOrUint8ArrayGenerator]}));711expectError(execa('unicorns', {stdin: booleanGenerator}));712expectError(execa('unicorns', {stdin: arrayGenerator}));713expectError(execa('unicorns', {stdin: invalidReturnGenerator}));714expectError(execa('unicorns', {stdin: syncGenerator}));715execa('unicorns', {stdin: undefined});716execaSync('unicorns', {stdin: undefined});717execa('unicorns', {stdin: [undefined]});718execaSync('unicorns', {stdin: [undefined]});
50 unmodified lines
769execa('unicorns', {stdout: 1});770execaSync('unicorns', {stdout: 1});771execa('unicorns', {stdout: [1]});772execaSync('unicorns', {stdout: [1]});773execa('unicorns', {stdout: stringOrUint8ArrayGenerator});774expectError(execaSync('unicorns', {stdout: stringOrUint8ArrayGenerator}));775execa('unicorns', {stdout: [stringOrUint8ArrayGenerator]});776expectError(execaSync('unicorns', {stdout: [stringOrUint8ArrayGenerator]}));777expectError(execa('unicorns', {stdout: booleanGenerator}));778expectError(execa('unicorns', {stdout: arrayGenerator}));779expectError(execa('unicorns', {stdout: invalidReturnGenerator}));780expectError(execa('unicorns', {stdout: syncGenerator}));781execa('unicorns', {stdout: undefined});782execaSync('unicorns', {stdout: undefined});783execa('unicorns', {stdout: [undefined]});784execaSync('unicorns', {stdout: [undefined]});
50 unmodified lines
835execa('unicorns', {stderr: 1});836execaSync('unicorns', {stderr: 1});837execa('unicorns', {stderr: [1]});838execaSync('unicorns', {stderr: [1]});839execa('unicorns', {stderr: stringOrUint8ArrayGenerator});840expectError(execaSync('unicorns', {stderr: stringOrUint8ArrayGenerator}));841execa('unicorns', {stderr: [stringOrUint8ArrayGenerator]});842expectError(execaSync('unicorns', {stderr: [stringOrUint8ArrayGenerator]}));843expectError(execa('unicorns', {stderr: booleanGenerator}));844expectError(execa('unicorns', {stderr: arrayGenerator}));845expectError(execa('unicorns', {stderr: invalidReturnGenerator}));846expectError(execa('unicorns', {stderr: syncGenerator}));847execa('unicorns', {stderr: undefined});848execaSync('unicorns', {stderr: undefined});849execa('unicorns', {stderr: [undefined]});850execaSync('unicorns', {stderr: [undefined]});
28 unmodified lines
879expectError(execa('unicorns', {stdio: 'ipc'}));880expectError(execaSync('unicorns', {stdio: 'ipc'}));881expectError(execa('unicorns', {stdio: 1}));882expectError(execaSync('unicorns', {stdio: 1}));883expectError(execa('unicorns', {stdio: stringOrUint8ArrayGenerator}));884expectError(execaSync('unicorns', {stdio: stringOrUint8ArrayGenerator}));885expectError(execa('unicorns', {stdio: fileUrl}));886expectError(execaSync('unicorns', {stdio: fileUrl}));887expectError(execa('unicorns', {stdio: {file: './test'}}));888expectError(execaSync('unicorns', {stdio: {file: './test'}}));
4 unmodified lines
893expectError(execa('unicorns', {stdio: new WritableStream()}));894expectError(execaSync('unicorns', {stdio: new WritableStream()}));895expectError(execa('unicorns', {stdio: new ReadableStream()}));896expectError(execaSync('unicorns', {stdio: new ReadableStream()}));837expectError(execa('unicorns', {stdio: stringGenerator()}));838expectError(execaSync('unicorns', {stdio: stringGenerator()}));897expectError(execa('unicorns', {stdio: emptyStringGenerator()}));898expectError(execaSync('unicorns', {stdio: emptyStringGenerator()}));899expectError(execa('unicorns', {stdio: asyncStringGenerator()}));900expectError(execaSync('unicorns', {stdio: asyncStringGenerator()}));901expectError(execa('unicorns', {stdio: ['pipe', 'pipe']}));902expectError(execaSync('unicorns', {stdio: ['pipe', 'pipe']}));
29 unmodified lines
932 'ignore',933 'inherit',934 process.stdin,935 1,936 stringOrUint8ArrayGenerator,937 undefined,938 fileUrl,939 {file: './test'},940 new Writable(),941 new Readable(),942 new WritableStream(),943 new ReadableStream(),944 new Uint8Array(),884 stringGenerator(),945 emptyStringGenerator(),946 asyncStringGenerator(),947 ],948});949execaSync('unicorns', {
10 unmodified lines
960 {file: './test'},961 new Uint8Array(),962 ],963});964expectError(execaSync('unicorns', {stdio: [stringOrUint8ArrayGenerator]}));965expectError(execaSync('unicorns', {stdio: [new Writable()]}));966expectError(execaSync('unicorns', {stdio: [new Readable()]}));967expectError(execaSync('unicorns', {stdio: [new WritableStream()]}));968expectError(execaSync('unicorns', {stdio: [new ReadableStream()]}));907expectError(execaSync('unicorns', {stdio: [stringGenerator()]}));969expectError(execaSync('unicorns', {stdio: [emptyStringGenerator()]}));970expectError(execaSync('unicorns', {stdio: [asyncStringGenerator()]}));971execa('unicorns', {972 stdio: [973 ['pipe'],
3 unmodified lines
977 ['ignore'],978 ['inherit'],979 [process.stdin],980 [1],981 [stringOrUint8ArrayGenerator],982 [undefined],983 [fileUrl],984 [{file: './test'}],985 [new Writable()],986 [new Readable()],987 [new WritableStream()],988 [new ReadableStream()],989 [new Uint8Array()],927 [stringGenerator()],990 [emptyStringGenerator()],991 [asyncStringGenerator()],992 ],993});994execaSync('unicorns', {
11 unmodified lines
1006 [{file: './test'}],1007 [new Uint8Array()],1008 ],1009});1010expectError(execaSync('unicorns', {stdio: [[stringOrUint8ArrayGenerator]]}));1011expectError(execaSync('unicorns', {stdio: [[new Writable()]]}));1012expectError(execaSync('unicorns', {stdio: [[new Readable()]]}));1013expectError(execaSync('unicorns', {stdio: [[new WritableStream()]]}));1014expectError(execaSync('unicorns', {stdio: [[new ReadableStream()]]}));951expectError(execaSync('unicorns', {stdio: [[stringGenerator()]]}));1015expectError(execaSync('unicorns', {stdio: [[emptyStringGenerator()]]}));1016expectError(execaSync('unicorns', {stdio: [[asyncStringGenerator()]]}));1017execa('unicorns', {serialization: 'advanced'});1018expectError(execaSync('unicorns', {serialization: 'advanced'}));1019execa('unicorns', {detached: true});
138 unmodified lines
modified:readme.md+10 added-4 removed
580 unmodified lines
581See also the [`input`](#input) and [`stdin`](#stdin) options.582583#### stdin584585Type: `string | number | stream.Readable | ReadableStream | URL | Uint8Array | Iterable<string | Uint8Array> | AsyncIterable<string | Uint8Array>` (or a tuple of those types)\585Type: `string | number | stream.Readable | ReadableStream | URL | Uint8Array | Iterable<string | Uint8Array> | AsyncIterable<string | Uint8Array> | AsyncGeneratorFunction<string | Uint8Array>` (or a tuple of those types)\586Default: `inherit` with [`$`](#command), `pipe` otherwise587588[How to setup](https://nodejs.org/api/child_process.html#child_process_options_stdio) the child process' standard input. This can be:589- `'pipe'`: Sets [`childProcess.stdin`](https://nodejs.org/api/child_process.html#subprocessstdin) stream.
10 unmodified lines
600- an `Uint8Array`.601602This can be an [array of values](#redirect-stdinstdoutstderr-to-multiple-destinations) such as `['inherit', 'pipe']` or `[filePath, 'pipe']`.603604This can also be an async generator function to transform the input. [Learn more.](docs/transform.md)605606#### stdout607606Type: `string | number | stream.Writable | WritableStream | URL` (or a tuple of those types)\608Type: `string | number | stream.Writable | WritableStream | URL | AsyncGeneratorFunction<string | Uint8Array>` (or a tuple of those types)\609Default: `pipe`610611[How to setup](https://nodejs.org/api/child_process.html#child_process_options_stdio) the child process' standard output. This can be:612- `'pipe'`: Sets [`childProcessResult.stdout`](#stdout) (as a string or `Uint8Array`) and [`childProcess.stdout`](https://nodejs.org/api/child_process.html#subprocessstdout) (as a stream).
8 unmodified lines
621- a web [`WritableStream`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream).622623This can be an [array of values](#redirect-stdinstdoutstderr-to-multiple-destinations) such as `['inherit', 'pipe']` or `[filePath, 'pipe']`.624625This can also be an async generator function to transform the output. [Learn more.](docs/transform.md)626627#### stderr628625Type: `string | number | stream.Writable | WritableStream | URL` (or a tuple of those types)`\629Type: `string | number | stream.Writable | WritableStream | URL | AsyncGeneratorFunction<string | Uint8Array>` (or a tuple of those types)`\630Default: `pipe`631632[How to setup](https://nodejs.org/api/child_process.html#child_process_options_stdio) the child process' standard error. This can be:633- `'pipe'`: Sets [`childProcessResult.stderr`](#stderr) (as a string or `Uint8Array`) and [`childProcess.stderr`](https://nodejs.org/api/child_process.html#subprocessstderr) (as a stream).
8 unmodified lines
642- a web [`WritableStream`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream).643644This can be an [array of values](#redirect-stdinstdoutstderr-to-multiple-destinations) such as `['inherit', 'pipe']` or `[filePath, 'pipe']`.645646This can also be an async generator function to transform the output. [Learn more.](docs/transform.md)647648#### stdio649644Type: `string | Array<string | number | stream.Readable | stream.Writable | ReadableStream | WritableStream | URL | Uint8Array | Iterable<string | Uint8Array> | AsyncIterable<string | Uint8Array>>` (or a tuple of those types)\650Type: `string | Array<string | number | stream.Readable | stream.Writable | ReadableStream | WritableStream | URL | Uint8Array | Iterable<string | Uint8Array> | AsyncIterable<string | Uint8Array> | AsyncGeneratorFunction<string | Uint8Array>>` (or a tuple of those types)\651Default: `pipe`652653Like the [`stdin`](#stdin), [`stdout`](#stdout-1) and [`stderr`](#stderr-1) options but for all file descriptors at once. For example, `{stdio: ['ignore', 'pipe', 'pipe']}` is the same as `{stdin: 'ignore', stdout: 'pipe', stderr: 'pipe'}`.654
289 unmodified lines