Make subprocess async iterable (#923)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent 56ee48e · Browse files · 19 files·+629 added−78 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
19 files+629 added−78 removed
- tests:+409 added−51 removed
- other:+220 added−27 removed
Provenance
- Commit
2e8e8c9- Tree
5f42104- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
56ee48e
19 files changed+629 added−78 removed
modified:docs/scripts.md+27 added
459 unmodified lines460 // Execa461 await $({inputFile: 'file.txt'})`cat`462 ```463 464+### Iterate over output lines465+466+```sh467+# Bash468+while read469+do470+ if [[ "$REPLY" == *ERROR* ]]471+ then472+ echo "$REPLY"473+ fi474+done < <(npm run build)475+```476+477+```js478+// zx does not allow proper iteration.479+// For example, the iteration does not handle subprocess errors.480+```481+482+```js483+// Execa484+for await (const line of $`npm run build`) {485+ if (line.includes('ERROR')) {486+ console.log(line);487+ }488+}489+```490+491 ### Errors492 493 ```sh494 # Bash communicates errors only through the exit code and stderr337 unmodified linesmodified:docs/transform.md+14 added-1 removed
10 unmodified lines11121314151516171819165 unmodified linesExpand all18518618718818919019119219319419519619719819920020110 unmodified lines const prefix = line.includes('error') ? 'ERROR' : 'INFO'; yield `${prefix}: ${line}`;};
const {stdout} = await execa('echo', ['hello'], {stdout: transform});const {stdout} = await execa('./run.js', {stdout: transform});console.log(stdout); // HELLO```
## Encoding165 unmodified linesExpand all
```jsawait execa('echo', ['hello'], {stdout: [transform, otherTransform]});```
## Async iteration
In some cases, [iterating](../readme.md#iterablereadableoptions) over the subprocess can be an alternative to transforms.
```jsimport {execa} from 'execa';
for await (const line of execa('./run.js')) { const prefix = line.includes('error') ? 'ERROR' : 'INFO'; console.log(`${prefix}: ${line}`);}```modified:lib/convert/add.js+4 added-1 removed
1 import {initializeConcurrentStreams} from './concurrent.js';2 import {createReadable} from './readable.js';3 import {createWritable} from './writable.js';4 import {createDuplex} from './duplex.js';5+import {createIterable} from './iterable.js';6 6-export const addConvertedStreams = subprocess => {7+export const addConvertedStreams = (subprocess, options) => {8 const concurrentStreams = initializeConcurrentStreams();9 subprocess.readable = createReadable.bind(undefined, {subprocess, concurrentStreams});10 subprocess.writable = createWritable.bind(undefined, {subprocess, concurrentStreams});11 subprocess.duplex = createDuplex.bind(undefined, {subprocess, concurrentStreams});12+ subprocess.iterable = createIterable.bind(undefined, subprocess, options);13+ subprocess[Symbol.asyncIterator] = createIterable.bind(undefined, subprocess, options, {});14 };added:lib/convert/iterable.js+24 added
1+import {getReadable} from '../pipe/validate.js';2+import {iterateOnStdout} from './loop.js';3+4+export const createIterable = (subprocess, {encoding}, {5+ from,6+ binary = encoding === 'buffer',7+ preserveNewlines = false,8+} = {}) => {9+ const subprocessStdout = getReadable(subprocess, from);10+ const onStdoutData = iterateOnStdout({subprocessStdout, subprocess, binary, preserveNewlines, isStream: false});11+ return iterateOnStdoutData(onStdoutData, subprocessStdout, subprocess);12+};13+14+const iterateOnStdoutData = async function * (onStdoutData, subprocessStdout, subprocess) {15+ try {16+ yield * onStdoutData;17+ } finally {18+ if (subprocessStdout.readable) {19+ subprocessStdout.destroy();20+ }21+22+ await subprocess;23+ }24+};modified:lib/convert/loop.js+16 added-10 removed
1 import {on} from 'node:events';2 import {getEncodingTransformGenerator} from '../stdio/encoding-transform.js';3 import {getSplitLinesGenerator} from '../stdio/split.js';4 5-export const iterateOnStdout = ({subprocessStdout, subprocess, binary, preserveNewlines}) => {5+export const iterateOnStdout = ({subprocessStdout, subprocess, binary, preserveNewlines, isStream}) => {6 const controller = new AbortController();7 stopReadingOnExit(subprocess, controller);8 const onStdoutChunk = on(subprocessStdout, 'data', {9 signal: controller.signal,2 unmodified lines12 // See https://github.com/nodejs/node/pull/52080#discussion_r152522786113 // @todo Remove after removing support for Node 2114 highWatermark: HIGH_WATER_MARK,15 });16- const onStdoutData = iterateOnData({subprocessStdout, onStdoutChunk, controller, binary, preserveNewlines});16+ const onStdoutData = iterateOnData({subprocessStdout, onStdoutChunk, controller, binary, preserveNewlines, isStream});17 return onStdoutData;18 };19 20 const stopReadingOnExit = async (subprocess, controller) => {12 unmodified lines33 // Therefore, we use the value of `getDefaultHighWaterMark(true)`.34 // Note: this option does not exist on Node 18, but this is ok since the logic works without it. It just consumes more memory.35 const HIGH_WATER_MARK = DEFAULT_OBJECT_HIGH_WATER_MARK;36 37-const iterateOnData = async function * ({subprocessStdout, onStdoutChunk, controller, binary, preserveNewlines}) {37+const iterateOnData = async function * ({subprocessStdout, onStdoutChunk, controller, binary, preserveNewlines, isStream}) {38 const {39 encodeChunk = identityGenerator,40 encodeChunkFinal = noopGenerator,41 splitLines = identityGenerator,42 splitLinesFinal = noopGenerator,43- } = getTransforms({subprocessStdout, binary, preserveNewlines});43+ } = getTransforms({subprocessStdout, binary, preserveNewlines, isStream});44 45 try {46 for await (const [chunk] of onStdoutChunk) {47 yield * handleChunk(encodeChunk, splitLines, chunk);6 unmodified lines54 yield * handleFinalChunks(encodeChunkFinal, splitLines, splitLinesFinal);55 }56 };57 58-const getTransforms = ({subprocessStdout, binary, preserveNewlines}) => {58+const getTransforms = ({subprocessStdout, binary, preserveNewlines, isStream}) => {59 if (subprocessStdout.readableObjectMode) {60 return {};61 }62 2 unmodified lines65 if (!binary) {66 return getTextTransforms(binary, preserveNewlines, writableObjectMode);67 }68 69- return {};69+ return isStream ? {} : getBinaryTransforms(writableObjectMode);70 };71 72 const getTextTransforms = (binary, preserveNewlines, writableObjectMode) => {73 const encoding = 'utf8';1 unmodified line75 const {transform: splitLines, final: splitLinesFinal} = getSplitLinesGenerator({encoding, binary, preserveNewlines, writableObjectMode, state: {}});76 return {encodeChunk, encodeChunkFinal, splitLines, splitLinesFinal};77 };78 79+const getBinaryTransforms = writableObjectMode => {80+ const encoding = 'buffer';81+ const {transform: encodeChunk} = getEncodingTransformGenerator(encoding, writableObjectMode, false);82+ return {encodeChunk};83+};84+85 const identityGenerator = function * (chunk) {86 yield chunk;87 };88 89 const noopGenerator = function * () {};90 91 const handleChunk = function * (encodeChunk, splitLines, chunk) {86- for (const chunkString of encodeChunk(chunk)) {87- yield * splitLines(chunkString);92+ for (const encodedChunk of encodeChunk(chunk)) {93+ yield * splitLines(encodedChunk);94 }95 };96 97 const handleFinalChunks = function * (encodeChunkFinal, splitLines, splitLinesFinal) {92- for (const chunkString of encodeChunkFinal()) {93- yield * splitLines(chunkString);98+ for (const encodedChunk of encodeChunkFinal()) {99+ yield * splitLines(encodedChunk);100 }101 102 yield * splitLinesFinal();103 };modified:lib/convert/readable.js+1 added-1 removed
38 unmodified lines39 : {readableEncoding, readableObjectMode: true, readableHighWaterMark: DEFAULT_OBJECT_HIGH_WATER_MARK};40 41 export const getReadableMethods = ({subprocessStdout, subprocess, binary, preserveNewlines}) => {42 const onStdoutDataDone = createDeferred();43- const onStdoutData = iterateOnStdout({subprocessStdout, subprocess, binary, preserveNewlines});43+ const onStdoutData = iterateOnStdout({subprocessStdout, subprocess, binary, preserveNewlines, isStream: true});44 45 return {46 read() {47 onRead(this, onStdoutData, onStdoutDataDone);46 unmodified linesmodified:lib/async.js+1 added-1 removed
63 unmodified lines64 cleanupOnExit(subprocess, options, controller);65 66 subprocess.kill = subprocessKill.bind(undefined, {kill: subprocess.kill.bind(subprocess), subprocess, options, controller});67 subprocess.all = makeAllStream(subprocess, options);68- addConvertedStreams(subprocess);68+ addConvertedStreams(subprocess, options);69 70 const promise = handlePromise({subprocess, options, startTime, verboseInfo, stdioStreamsGroups, originalStreams, command, escapedCommand, controller});71 return {subprocess, promise};72 };34 unmodified linesadded:test/convert/iterable.js+154 added
1+import test from 'ava';2+import {execa} from '../../index.js';3+import {setFixtureDir} from '../helpers/fixtures-dir.js';4+import {foobarString} from '../helpers/input.js';5+import {fullStdio, assertEpipe} from '../helpers/stdio.js';6+import {7+ arrayFromAsync,8+ assertWritableAborted,9+ assertReadableAborted,10+ assertProcessNormalExit,11+} from '../helpers/convert.js';12+import {simpleFull, noNewlinesChunks} from '../helpers/lines.js';13+14+setFixtureDir();15+16+const partialArrayFromAsync = async (asyncIterable, lines = []) => {17+ // eslint-disable-next-line no-unreachable-loop18+ for await (const line of asyncIterable) {19+ lines.push(line);20+ break;21+ }22+23+ return lines;24+};25+26+const errorArrayFromAsync = async (t, cause, asyncIterable, lines = []) => {27+ const {value} = await asyncIterable.next();28+ lines.push(value);29+ await asyncIterable.throw(cause);30+};31+32+const throwsAsync = async (t, asyncIterable, arrayFromAsyncMethod) => {33+ const lines = [];34+ const error = await t.throwsAsync(arrayFromAsyncMethod(asyncIterable, lines));35+ return {error, lines};36+};37+38+const assertStdoutAbort = (t, subprocess, error, cause) => {39+ assertProcessNormalExit(t, error, 1);40+ assertEpipe(t, error.stderr);41+ assertWritableAborted(t, subprocess.stdin);42+ t.true(subprocess.stderr.readableEnded);43+44+ if (cause === undefined) {45+ assertReadableAborted(t, subprocess.stdout);46+ } else {47+ t.is(subprocess.stdout.errored, cause);48+ }49+};50+51+const testSuccess = async (t, fdNumber, from, options = {}) => {52+ const lines = await arrayFromAsync(execa('noop-fd.js', [`${fdNumber}`, simpleFull], options).iterable({from}));53+ t.deepEqual(lines, noNewlinesChunks);54+};55+56+test('Uses stdout by default', testSuccess, 1, undefined);57+test('Can iterate successfully on stdout', testSuccess, 1, 'stdout');58+test('Can iterate successfully on stderr', testSuccess, 2, 'stderr');59+test('Can iterate successfully on stdio[*]', testSuccess, 3, 'fd3', fullStdio);60+61+test('Can iterate successfully on all', async t => {62+ const lines = await arrayFromAsync(execa('noop-both.js', [simpleFull], {all: true}).iterable({from: 'all'}));63+ t.deepEqual(lines, [...noNewlinesChunks, ...noNewlinesChunks]);64+});65+66+test('Can iterate using Symbol.asyncIterator', async t => {67+ const lines = await arrayFromAsync(execa('noop-fd.js', ['1', simpleFull]));68+ t.deepEqual(lines, noNewlinesChunks);69+});70+71+const assertMultipleCalls = async (t, iterable, iterableTwo) => {72+ t.not(iterable, iterableTwo);73+ const lines = await arrayFromAsync(iterable);74+ const linesTwo = await arrayFromAsync(iterableTwo);75+ t.deepEqual(lines, linesTwo);76+ t.deepEqual(lines, noNewlinesChunks);77+};78+79+test('Can be called multiple times', async t => {80+ const subprocess = execa('noop-fd.js', ['1', simpleFull]);81+ const iterable = subprocess.iterable();82+ const iterableTwo = subprocess.iterable();83+ await assertMultipleCalls(t, iterable, iterableTwo);84+});85+86+test('Can be called on different file descriptors', async t => {87+ const subprocess = execa('noop-both.js', [simpleFull]);88+ const iterable = subprocess.iterable();89+ const iterableTwo = subprocess.iterable({from: 'stderr'});90+ await assertMultipleCalls(t, iterable, iterableTwo);91+});92+93+test('Wait for the subprocess exit', async t => {94+ const subprocess = execa('noop-delay.js', ['1', simpleFull]);95+ const linesPromise = arrayFromAsync(subprocess);96+ t.is(await Promise.race([linesPromise, subprocess]), await subprocess);97+ t.deepEqual(await linesPromise, noNewlinesChunks);98+});99+100+test('Wait for the subprocess exit on iterator.return()', async t => {101+ const subprocess = execa('noop-delay.js', ['1', simpleFull]);102+ const linesPromise = partialArrayFromAsync(subprocess);103+ t.is(await Promise.race([linesPromise, subprocess]), await subprocess);104+ t.deepEqual(await linesPromise, [noNewlinesChunks[0]]);105+});106+107+test('Wait for the subprocess exit on iterator.throw()', async t => {108+ const subprocess = execa('noop-delay.js', ['1', simpleFull]);109+ const cause = new Error(foobarString);110+ const lines = [];111+ const linesPromise = t.throwsAsync(errorArrayFromAsync(t, cause, subprocess.iterable(), lines));112+ t.is(await Promise.race([linesPromise, subprocess]), await subprocess);113+ t.deepEqual(lines, [noNewlinesChunks[0]]);114+});115+116+test('Abort stdout on iterator.return()', async t => {117+ const subprocess = execa('noop-repeat.js', ['1', simpleFull]);118+ const {error, lines} = await throwsAsync(t, subprocess, partialArrayFromAsync);119+ t.deepEqual(lines, [noNewlinesChunks[0]]);120+ assertStdoutAbort(t, subprocess, error);121+ t.is(error, await t.throwsAsync(subprocess));122+});123+124+test('Abort stdout on iterator.throw()', async t => {125+ const subprocess = execa('noop-repeat.js', ['1', simpleFull]);126+ const cause = new Error(foobarString);127+ const {error, lines} = await throwsAsync(t, subprocess.iterable(), errorArrayFromAsync.bind(undefined, t, cause));128+ t.deepEqual(lines, [noNewlinesChunks[0]]);129+ assertStdoutAbort(t, subprocess, error);130+ t.is(error, await t.throwsAsync(subprocess));131+});132+133+test('Propagate subprocess failure', async t => {134+ const subprocess = execa('noop-fail.js', ['1', simpleFull]);135+ const {error, lines} = await throwsAsync(t, subprocess, arrayFromAsync);136+ t.is(error, await t.throwsAsync(subprocess));137+ t.deepEqual(lines, noNewlinesChunks);138+});139+140+const testStdoutError = async (t, destroyStdout, isAbort, cause) => {141+ const subprocess = execa('noop-repeat.js', ['1', simpleFull]);142+ subprocess.stdout.once('data', () => {143+ destroyStdout(subprocess.stdout, cause);144+ });145+146+ const {error} = await throwsAsync(t, subprocess, arrayFromAsync);147+ t.is(error.cause, cause);148+ assertStdoutAbort(t, subprocess, error, isAbort ? undefined : cause);149+ t.is(error, await t.throwsAsync(subprocess));150+};151+152+test('Propagate stdout abort', testStdoutError, subprocessStdout => subprocessStdout.destroy(), true);153+test('Propagate stdout error', testStdoutError, (subprocessStdout, cause) => subprocessStdout.destroy(cause), false, new Error(foobarString));154+test('Propagate stdout "error" event', testStdoutError, (subprocessStdout, cause) => subprocessStdout.emit('error', cause), true, new Error(foobarString));modified:test/convert/loop.js+52 added-20 removed
2 unmodified lines3 import test from 'ava';4 import {setFixtureDir} from '../helpers/fixtures-dir.js';5 import {6 assertStreamOutput,7+ assertIterableChunks,8 assertStreamChunks,9 assertSubprocessOutput,10 getReadableSubprocess,11 getReadWriteSubprocess,12 } from '../helpers/convert.js';13 import {14+ stringToUint8Arrays,15 simpleFull,16 simpleChunks,17 simpleChunksBuffer,18+ simpleChunksUint8Array,19 simpleLines,20 noNewlinesFull,21 complexFull,22 singleComplexBuffer,23+ singleComplexUint8Array,24 complexChunks,25 complexChunksEnd,26 } from '../helpers/lines.js';27 import {outputObjectGenerator, getOutputGenerator} from '../helpers/generator.js';13 unmodified lines41 subprocess.stdin.end(output);42 return subprocess;43 };44 45+const assertChunks = async (t, streamOrIterable, expectedChunks, methodName) => {46+ const assertMethod = methodName === 'iterable' ? assertIterableChunks : assertStreamChunks;47+ await assertMethod(t, streamOrIterable, expectedChunks);48+};49+50 // eslint-disable-next-line max-params42-const testText = async (t, expectedChunks, methodName, binary, preserveNewlines) => {43- const subprocess = getSubprocess(methodName, complexFull);51+const testText = async (t, expectedChunks, methodName, binary, preserveNewlines, isUint8Array) => {52+ const options = isUint8Array ? {encoding: 'buffer'} : {};53+ const subprocess = getSubprocess(methodName, complexFull, options);54 const stream = subprocess[methodName]({binary, preserveNewlines});55 46- await assertStreamChunks(t, stream, expectedChunks);47- await assertSubprocessOutput(t, subprocess, complexFull);56+ await assertChunks(t, stream, expectedChunks, methodName);57+ await assertSubprocessOutput(t, subprocess, stringToUint8Arrays(complexFull, isUint8Array));58 };59 60+test('.iterable() can use "binary: true"', testText, singleComplexUint8Array, 'iterable', true, undefined, false);61+test('.iterable() can use "binary: undefined"', testText, complexChunks, 'iterable', undefined, undefined, false);62+test('.iterable() can use "binary: undefined" + "encoding: buffer"', testText, singleComplexUint8Array, 'iterable', undefined, undefined, true);63+test('.iterable() can use "binary: false"', testText, complexChunks, 'iterable', false, undefined, false);64+test('.iterable() can use "binary: false" + "preserveNewlines: true"', testText, complexChunksEnd, 'iterable', false, true, false);65+test('.iterable() can use "binary: false" + "preserveNewlines: false"', testText, complexChunks, 'iterable', false, false, false);66+test('.readable() can use "binary: true"', testText, singleComplexBuffer, 'readable', true, undefined, false);50-test('.readable() can use "binary: true"', testText, singleComplexBuffer, 'readable', true, undefined);51-test('.readable() can use "binary: undefined"', testText, singleComplexBuffer, 'readable', undefined, undefined);52-test('.readable() can use "binary: false"', testText, complexChunksEnd, 'readable', false, undefined);53-test('.readable() can use "binary: false" + "preserveNewlines: true"', testText, complexChunksEnd, 'readable', false, true);54-test('.readable() can use "binary: false" + "preserveNewlines: false"', testText, complexChunks, 'readable', false, false);55-test('.duplex() can use "binary: true"', testText, singleComplexBuffer, 'duplex', true, undefined);56-test('.duplex() can use "binary: undefined"', testText, singleComplexBuffer, 'duplex', undefined, undefined);57-test('.duplex() can use "binary: false"', testText, complexChunksEnd, 'duplex', false, undefined);58-test('.duplex() can use "binary: false" + "preserveNewlines: true"', testText, complexChunksEnd, 'duplex', false, true);59-test('.duplex() can use "binary: false" + "preserveNewlines: false"', testText, complexChunks, 'duplex', false, false);67+test('.readable() can use "binary: undefined"', testText, singleComplexBuffer, 'readable', undefined, undefined, false);68+test('.readable() can use "binary: undefined" + "encoding: buffer"', testText, singleComplexBuffer, 'readable', undefined, undefined, true);69+test('.readable() can use "binary: false"', testText, complexChunksEnd, 'readable', false, undefined, false);70+test('.readable() can use "binary: false" + "preserveNewlines: true"', testText, complexChunksEnd, 'readable', false, true, false);71+test('.readable() can use "binary: false" + "preserveNewlines: false"', testText, complexChunks, 'readable', false, false, false);72+test('.duplex() can use "binary: true"', testText, singleComplexBuffer, 'duplex', true, undefined, false);73+test('.duplex() can use "binary: undefined"', testText, singleComplexBuffer, 'duplex', undefined, undefined, false);74+test('.duplex() can use "binary: undefined" + "encoding: "buffer"', testText, singleComplexBuffer, 'duplex', undefined, undefined, true);75+test('.duplex() can use "binary: false"', testText, complexChunksEnd, 'duplex', false, undefined, false);76+test('.duplex() can use "binary: false" + "preserveNewlines: true"', testText, complexChunksEnd, 'duplex', false, true, false);77+test('.duplex() can use "binary: false" + "preserveNewlines: false"', testText, complexChunks, 'duplex', false, false, false);78 79 const testTextOutput = async (t, expectedOutput, methodName, preserveNewlines) => {80 const subprocess = getSubprocess(methodName, complexFull);81 const stream = subprocess[methodName]({binary: false, preserveNewlines});20 unmodified lines102 t.is(subprocess.stdout.readableObjectMode, initialObjectMode);103 t.is(subprocess.stdout.readableHighWaterMark, getDefaultHighWaterMark(initialObjectMode));104 105 const stream = subprocess[methodName]({binary, preserveNewlines: true});106+107+ if (methodName !== 'iterable') {88- t.is(stream.readableEncoding, encoding);89- t.is(stream.readableObjectMode, finalObjectMode);90- t.is(stream.readableHighWaterMark, getDefaultHighWaterMark(finalObjectMode));108+ t.is(stream.readableEncoding, encoding);109+ t.is(stream.readableObjectMode, finalObjectMode);110+ t.is(stream.readableHighWaterMark, getDefaultHighWaterMark(finalObjectMode));111+ }112+113 t.is(subprocess.stdout.readableEncoding, encoding);114 t.is(subprocess.stdout.readableObjectMode, initialObjectMode);115 t.is(subprocess.stdout.readableHighWaterMark, getDefaultHighWaterMark(initialObjectMode));116 95- await assertStreamChunks(t, stream, expectedChunks);117+ await assertChunks(t, stream, expectedChunks, methodName);118 await subprocess;119 };120 121+test('.iterable() uses Buffers with "binary: true"', testObjectMode, simpleChunksUint8Array, 'iterable', null, false, false, true);122+test('.iterable() uses strings with "binary: true" and .setEncoding("utf8")', testObjectMode, simpleChunks, 'iterable', 'utf8', false, false, true);123+test('.iterable() uses strings with "binary: true" and "encoding: buffer"', testObjectMode, simpleChunks, 'iterable', 'utf8', false, false, true, {encoding: 'buffer'});124+test('.iterable() uses strings in objectMode with "binary: true" and object transforms', testObjectMode, foobarObjectChunks, 'iterable', null, true, true, true, {stdout: outputObjectGenerator});125+test('.iterable() uses strings in objectMode with "binary: false"', testObjectMode, simpleLines, 'iterable', null, false, true, false);126+test('.iterable() uses strings in objectMode with "binary: false" and .setEncoding("utf8")', testObjectMode, simpleLines, 'iterable', 'utf8', false, true, false);127+test('.iterable() uses strings in objectMode with "binary: false" and "encoding: buffer"', testObjectMode, simpleLines, 'iterable', 'utf8', false, true, false, {encoding: 'buffer'});128+test('.iterable() uses strings in objectMode with "binary: false" and object transforms', testObjectMode, foobarObjectChunks, 'iterable', null, true, true, false, {stdout: outputObjectGenerator});129 test('.readable() uses Buffers with "binary: true"', testObjectMode, simpleChunksBuffer, 'readable', null, false, false, true);130 test('.readable() uses strings with "binary: true" and .setEncoding("utf8")', testObjectMode, simpleChunks, 'readable', 'utf8', false, false, true);131 test('.readable() uses strings with "binary: true" and "encoding: buffer"', testObjectMode, simpleChunks, 'readable', 'utf8', false, false, true, {encoding: 'buffer'});132 test('.readable() uses strings in objectMode with "binary: true" and object transforms', testObjectMode, foobarObjectChunks, 'readable', null, true, true, true, {stdout: outputObjectGenerator});12 unmodified lines145 146 const testObjectSplit = async (t, methodName) => {147 const subprocess = getSubprocess(methodName, foobarString, {stdout: getOutputGenerator(simpleFull, true)});148 const stream = subprocess[methodName]({binary: false});119- await assertStreamChunks(t, stream, [simpleFull]);149+ await assertChunks(t, stream, [simpleFull], methodName);150 await subprocess;151 };152 153+test('.iterable() "binary: false" does not split lines of strings produced by object transforms', testObjectSplit, 'iterable');154 test('.readable() "binary: false" does not split lines of strings produced by object transforms', testObjectSplit, 'readable');155 test('.duplex() "binary: false" does not split lines of strings produced by object transforms', testObjectSplit, 'duplex');156 157 const testMultibyteCharacters = async (t, methodName) => {158 const subprocess = getReadWriteSubprocess();159 const stream = subprocess[methodName]({binary: false});129- const assertPromise = assertStreamOutput(t, stream, `${multibyteChar}${brokenSymbol}`);160+ const assertPromise = assertChunks(t, stream, [`${multibyteChar}${brokenSymbol}`], methodName);161 subprocess.stdin.write(multibyteUint8Array.slice(0, breakingLength));162 await once(subprocess.stdout, 'data');163 subprocess.stdin.end();164 await assertPromise;165 };166 167+test('.iterable() "binary: false" handles partial multibyte characters', testMultibyteCharacters, 'iterable');168 test('.readable() "binary: false" handles partial multibyte characters', testMultibyteCharacters, 'readable');169 test('.duplex() "binary: false" handles partial multibyte characters', testMultibyteCharacters, 'duplex');modified:test/fixtures/noop-delay.js+2 added-1 removed
3 unmodified lines4 import {getWriteStream} from '../helpers/fs.js';5 import {foobarString} from '../helpers/input.js';6 7 const fdNumber = Number(process.argv[2]);8+const bytes = process.argv[3] || foobarString;8-getWriteStream(fdNumber).write(foobarString);9+getWriteStream(fdNumber).write(bytes);10 await setTimeout(100);modified:test/helpers/convert.js+12 added
2 unmodified lines3 import isPlainObj from 'is-plain-obj';4 import {execa} from '../../index.js';5 import {foobarString} from '../helpers/input.js';6 7+export const arrayFromAsync = async (asyncIterable, lines = []) => {8+ for await (const line of asyncIterable) {9+ lines.push(line);10+ }11+12+ return lines;13+};14+15 export const finishedStream = stream => finished(stream, {cleanup: true});16 17 export const assertWritableAborted = (t, writable) => {18 t.false(writable.writableEnded);15 unmodified lines34 export const assertStreamOutput = async (t, stream, expectedOutput = foobarString) => {35 t.is(await text(stream), expectedOutput);36 };37 38+export const assertIterableChunks = async (t, asyncIterable, expectedChunks) => {39+ t.deepEqual(await arrayFromAsync(asyncIterable), expectedChunks);40+};41+42 export const assertStreamChunks = async (t, stream, expectedOutput) => {43 t.deepEqual(await stream.toArray(), expectedOutput);44 };45 28 unmodified linesmodified:test/helpers/lines.js+19 added-15 removed
1 import {Buffer} from 'node:buffer';2 3-export const simpleFull = 'aaa\nbbb\nccc';4-export const simpleChunks = [simpleFull];5-export const simpleChunksBuffer = [Buffer.from(simpleFull)];6-export const simpleLines = ['aaa\n', 'bbb\n', 'ccc'];7-export const simpleFullEndLines = ['aaa\n', 'bbb\n', 'ccc\n'];8-export const noNewlinesFull = 'aaabbbccc';9-export const noNewlinesChunks = ['aaa', 'bbb', 'ccc'];10-export const complexFull = '\naaa\r\nbbb\n\nccc';11-export const singleComplexBuffer = [Buffer.from(complexFull)];12-export const complexChunksEnd = ['\n', 'aaa\r\n', 'bbb\n', '\n', 'ccc'];13-export const complexChunks = ['', 'aaa', 'bbb', '', 'ccc'];14-3 const textEncoder = new TextEncoder();4 const textDecoder = new TextDecoder();5 6 export const getEncoding = isUint8Array => isUint8Array ? 'buffer' : 'utf8';7 20-export const stringsToUint8Arrays = (strings, isUint8Array) => isUint8Array21- ? strings.map(string => textEncoder.encode(string))22- : strings;8+export const stringsToUint8Arrays = (strings, isUint8Array) => strings.map(string => stringToUint8Arrays(string, isUint8Array));9 10+export const stringToUint8Arrays = (string, isUint8Array) => isUint8Array11+ ? textEncoder.encode(string)12+ : string;13+14 export const stringsToBuffers = (strings, isUint8Array) => isUint8Array15 ? strings.map(string => Buffer.from(string))16 : strings;17 3 unmodified lines21 22 const serializeResultItem = (resultItem, isUint8Array) => isUint8Array23 ? textDecoder.decode(resultItem)24 : resultItem;25+26+export const simpleFull = 'aaa\nbbb\nccc';27+export const simpleChunks = [simpleFull];28+export const simpleChunksBuffer = [Buffer.from(simpleFull)];29+export const simpleChunksUint8Array = stringsToUint8Arrays(simpleChunks, true);30+export const simpleLines = ['aaa\n', 'bbb\n', 'ccc'];31+export const simpleFullEndLines = ['aaa\n', 'bbb\n', 'ccc\n'];32+export const noNewlinesFull = 'aaabbbccc';33+export const noNewlinesChunks = ['aaa', 'bbb', 'ccc'];34+export const complexFull = '\naaa\r\nbbb\n\nccc';35+export const singleComplexBuffer = [Buffer.from(complexFull)];36+export const singleComplexUint8Array = stringsToUint8Arrays([complexFull], true);37+export const complexChunksEnd = ['\n', 'aaa\r\n', 'bbb\n', '\n', 'ccc'];38+export const complexChunks = ['', 'aaa', 'bbb', '', 'ccc'];modified:test/helpers/stdio.js+9 added-1 removed
1-import process from 'node:process';1+import process, {platform} from 'node:process';2 import {noopReadable} from './stream.js';3 4 export const identity = value => value;5 12 unmodified lines18 19 export const STANDARD_STREAMS = [process.stdin, process.stdout, process.stderr];20 21 export const prematureClose = {code: 'ERR_STREAM_PREMATURE_CLOSE'};22+23+const isWindows = platform === 'win32';24+25+export const assertEpipe = (t, stderr, fdNumber = 1) => {26+ if (fdNumber === 1 && !isWindows) {27+ t.true(stderr.includes('EPIPE'));28+ }29+};modified:test/pipe/validate.js+157 added
73 unmodified lines74 });75 t.true(error.message.includes(getMessage(message)));76 };77 78+const testIterable = async (t, {79+ message,80+ sourceOptions = {},81+ getSource = () => execa('empty.js', sourceOptions),82+ from,83+}) => {84+ const error = t.throws(() => {85+ getSource().iterable({from});86+ });87+ t.true(error.message.includes(getMessage(message)));88+};89+90 test('Must set "all" option to "true" to use .pipe("all")', testPipeError, {91 from: 'all',92 message: '"all" option must be true',93 });94 test('Must set "all" option to "true" to use .duplex("all")', testNodeStream, {95 from: 'all',96 message: '"all" option must be true',97 });98+test('Must set "all" option to "true" to use .iterable("all")', testIterable, {99+ from: 'all',100+ message: '"all" option must be true',101+});102 test('.pipe() cannot pipe to non-subprocesses', testPipeError, {103 getDestination: () => new PassThrough(),104 message: 'an Execa subprocess',105 });8 unmodified lines114 test('.duplex() "from" option cannot be "stdin"', testNodeStream, {115 from: 'stdin',116 message: '"from" must not be',117 });118+test('.iterable() "from" option cannot be "stdin"', testIterable, {119+ from: 'stdin',120+ message: '"from" must not be',121+});122 test('$.pipe() "from" option cannot be "stdin"', testPipeError, {123 from: 'stdin',124 isScript: true,125 message: '"from" must not be',18 unmodified lines144 test('.duplex() "from" option cannot be any string', testNodeStream, {145 from: 'other',146 message: 'must be "stdout", "stderr", "all"',147 });148+test('.iterable() "from" option cannot be any string', testIterable, {149+ from: 'other',150+ message: 'must be "stdout", "stderr", "all"',151+});152 test('.pipe() "to" option cannot be any string', testPipeError, {153 to: 'other',154 message: 'must be "stdin"',155 });8 unmodified lines164 test('.duplex() "from" option cannot be a number without "fd"', testNodeStream, {165 from: '1',166 message: 'must be "stdout", "stderr", "all"',167 });168+test('.iterable() "from" option cannot be a number without "fd"', testIterable, {169+ from: '1',170+ message: 'must be "stdout", "stderr", "all"',171+});172 test('.pipe() "to" option cannot be a number without "fd"', testPipeError, {173 to: '0',174 message: 'must be "stdin"',175 });8 unmodified lines184 test('.duplex() "from" option cannot be just "fd"', testNodeStream, {185 from: 'fd',186 message: 'must be "stdout", "stderr", "all"',187 });188+test('.iterable() "from" option cannot be just "fd"', testIterable, {189+ from: 'fd',190+ message: 'must be "stdout", "stderr", "all"',191+});192 test('.pipe() "to" option cannot be just "fd"', testPipeError, {193 to: 'fd',194 message: 'must be "stdin"',195 });8 unmodified lines204 test('.duplex() "from" option cannot be a float', testNodeStream, {205 from: 'fd1.5',206 message: 'must be "stdout", "stderr", "all"',207 });208+test('.iterable() "from" option cannot be a float', testIterable, {209+ from: 'fd1.5',210+ message: 'must be "stdout", "stderr", "all"',211+});212 test('.pipe() "to" option cannot be a float', testPipeError, {213 to: 'fd1.5',214 message: 'must be "stdin"',215 });8 unmodified lines224 test('.duplex() "from" option cannot be a negative number', testNodeStream, {225 from: 'fd-1',226 message: 'must be "stdout", "stderr", "all"',227 });228+test('.iterable() "from" option cannot be a negative number', testIterable, {229+ from: 'fd-1',230+ message: 'must be "stdout", "stderr", "all"',231+});232 test('.pipe() "to" option cannot be a negative number', testPipeError, {233 to: 'fd-1',234 message: 'must be "stdin"',235 });8 unmodified lines244 test('.duplex() "from" cannot be a non-existing file descriptor', testNodeStream, {245 from: 'fd3',246 message: 'file descriptor does not exist',247 });248+test('.iterable() "from" cannot be a non-existing file descriptor', testIterable, {249+ from: 'fd3',250+ message: 'file descriptor does not exist',251+});252 test('.pipe() "to" option cannot be a non-existing file descriptor', testPipeError, {253 to: 'fd3',254 message: 'file descriptor does not exist',255 });10 unmodified lines266 sourceOptions: getStdio(3, new Uint8Array()),267 from: 'fd3',268 message: 'must be a readable stream',269 });270+test('.iterable() "from" option cannot be an input file descriptor', testIterable, {271+ sourceOptions: getStdio(3, new Uint8Array()),272+ from: 'fd3',273+ message: 'must be a readable stream',274+});275 test('.pipe() "to" option cannot be an output file descriptor', testPipeError, {276 destinationOptions: fullStdio,277 to: 'fd3',278 message: 'must be a writable stream',20 unmodified lines299 test('Cannot set "stdout" option to "ignore" to use .duplex()', testNodeStream, {300 sourceOptions: {stdout: 'ignore'},301 message: ['stdout', '\'ignore\''],302 });303+test('Cannot set "stdout" option to "ignore" to use .iterable()', testIterable, {304+ sourceOptions: {stdout: 'ignore'},305+ message: ['stdout', '\'ignore\''],306+});307 test('Cannot set "stdin" option to "ignore" to use .pipe()', testPipeError, {308 destinationOptions: {stdin: 'ignore'},309 message: ['stdin', '\'ignore\''],310 });11 unmodified lines322 sourceOptions: {stdout: 'ignore'},323 from: 'fd1',324 message: ['stdout', '\'ignore\''],325 });326+test('Cannot set "stdout" option to "ignore" to use .iterable(1)', testIterable, {327+ sourceOptions: {stdout: 'ignore'},328+ from: 'fd1',329+ message: ['stdout', '\'ignore\''],330+});331 test('Cannot set "stdin" option to "ignore" to use .pipe(0)', testPipeError, {332 destinationOptions: {stdin: 'ignore'},333 message: ['stdin', '\'ignore\''],334 to: 'fd0',12 unmodified lines347 sourceOptions: {stdout: 'ignore'},348 from: 'stdout',349 message: ['stdout', '\'ignore\''],350 });351+test('Cannot set "stdout" option to "ignore" to use .iterable("stdout")', testIterable, {352+ sourceOptions: {stdout: 'ignore'},353+ from: 'stdout',354+ message: ['stdout', '\'ignore\''],355+});356 test('Cannot set "stdin" option to "ignore" to use .pipe("stdin")', testPipeError, {357 destinationOptions: {stdin: 'ignore'},358 message: ['stdin', '\'ignore\''],359 to: 'stdin',10 unmodified lines370 test('Cannot set "stdout" + "stderr" option to "ignore" to use .duplex()', testNodeStream, {371 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},372 message: ['stdout', '\'ignore\''],373 });374+test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable()', testIterable, {375+ sourceOptions: {stdout: 'ignore', stderr: 'ignore'},376+ message: ['stdout', '\'ignore\''],377+});378 test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe(1)', testPipeError, {379 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},380 from: 'fd1',381 message: ['stdout', '\'ignore\''],2 unmodified lines384 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},385 from: 'fd1',386 message: ['stdout', '\'ignore\''],387 });388+test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable(1)', testIterable, {389+ sourceOptions: {stdout: 'ignore', stderr: 'ignore'},390+ from: 'fd1',391+ message: ['stdout', '\'ignore\''],392+});393 test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe("stdout")', testPipeError, {394 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},395 from: 'stdout',396 message: ['stdout', '\'ignore\''],2 unmodified lines399 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},400 from: 'stdout',401 message: ['stdout', '\'ignore\''],402 });403+test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable("stdout")', testIterable, {404+ sourceOptions: {stdout: 'ignore', stderr: 'ignore'},405+ from: 'stdout',406+ message: ['stdout', '\'ignore\''],407+});408 test('Cannot set "stdio[1]" option to "ignore" to use .pipe()', testPipeError, {409 sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},410 message: ['stdio[1]', '\'ignore\''],411 });412 test('Cannot set "stdio[1]" option to "ignore" to use .duplex()', testNodeStream, {413 sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},414 message: ['stdio[1]', '\'ignore\''],415 });416+test('Cannot set "stdio[1]" option to "ignore" to use .iterable()', testIterable, {417+ sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},418+ message: ['stdio[1]', '\'ignore\''],419+});420 test('Cannot set "stdio[0]" option to "ignore" to use .pipe()', testPipeError, {421 destinationOptions: {stdio: ['ignore', 'pipe', 'pipe']},422 message: ['stdio[0]', '\'ignore\''],423 });11 unmodified lines435 sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},436 from: 'fd1',437 message: ['stdio[1]', '\'ignore\''],438 });439+test('Cannot set "stdio[1]" option to "ignore" to use .iterable(1)', testIterable, {440+ sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},441+ from: 'fd1',442+ message: ['stdio[1]', '\'ignore\''],443+});444 test('Cannot set "stdio[0]" option to "ignore" to use .pipe(0)', testPipeError, {445 destinationOptions: {stdio: ['ignore', 'pipe', 'pipe']},446 message: ['stdio[0]', '\'ignore\''],447 to: 'fd0',12 unmodified lines460 sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},461 from: 'stdout',462 message: ['stdio[1]', '\'ignore\''],463 });464+test('Cannot set "stdio[1]" option to "ignore" to use .iterable("stdout")', testIterable, {465+ sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},466+ from: 'stdout',467+ message: ['stdio[1]', '\'ignore\''],468+});469 test('Cannot set "stdio[0]" option to "ignore" to use .pipe("stdin")', testPipeError, {470 destinationOptions: {stdio: ['ignore', 'pipe', 'pipe']},471 message: ['stdio[0]', '\'ignore\''],472 to: 'stdin',12 unmodified lines485 sourceOptions: {stderr: 'ignore'},486 from: 'fd2',487 message: ['stderr', '\'ignore\''],488 });489+test('Cannot set "stderr" option to "ignore" to use .iterable(2)', testIterable, {490+ sourceOptions: {stderr: 'ignore'},491+ from: 'fd2',492+ message: ['stderr', '\'ignore\''],493+});494 test('Cannot set "stderr" option to "ignore" to use .pipe("stderr")', testPipeError, {495 sourceOptions: {stderr: 'ignore'},496 from: 'stderr',497 message: ['stderr', '\'ignore\''],2 unmodified lines500 sourceOptions: {stderr: 'ignore'},501 from: 'stderr',502 message: ['stderr', '\'ignore\''],503 });504+test('Cannot set "stderr" option to "ignore" to use .iterable("stderr")', testIterable, {505+ sourceOptions: {stderr: 'ignore'},506+ from: 'stderr',507+ message: ['stderr', '\'ignore\''],508+});509 test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe(2)', testPipeError, {510 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},511 from: 'fd2',512 message: ['stderr', '\'ignore\''],2 unmodified lines515 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},516 from: 'fd2',517 message: ['stderr', '\'ignore\''],518 });519+test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable(2)', testIterable, {520+ sourceOptions: {stdout: 'ignore', stderr: 'ignore'},521+ from: 'fd2',522+ message: ['stderr', '\'ignore\''],523+});524 test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe("stderr")', testPipeError, {525 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},526 from: 'stderr',527 message: ['stderr', '\'ignore\''],2 unmodified lines530 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},531 from: 'stderr',532 message: ['stderr', '\'ignore\''],533 });534+test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable("stderr")', testIterable, {535+ sourceOptions: {stdout: 'ignore', stderr: 'ignore'},536+ from: 'stderr',537+ message: ['stderr', '\'ignore\''],538+});539 test('Cannot set "stdio[2]" option to "ignore" to use .pipe(2)', testPipeError, {540 sourceOptions: {stdio: ['pipe', 'pipe', 'ignore']},541 from: 'fd2',542 message: ['stdio[2]', '\'ignore\''],2 unmodified lines545 sourceOptions: {stdio: ['pipe', 'pipe', 'ignore']},546 from: 'fd2',547 message: ['stdio[2]', '\'ignore\''],548 });549+test('Cannot set "stdio[2]" option to "ignore" to use .iterable(2)', testIterable, {550+ sourceOptions: {stdio: ['pipe', 'pipe', 'ignore']},551+ from: 'fd2',552+ message: ['stdio[2]', '\'ignore\''],553+});554 test('Cannot set "stdio[2]" option to "ignore" to use .pipe("stderr")', testPipeError, {555 sourceOptions: {stdio: ['pipe', 'pipe', 'ignore']},556 from: 'stderr',557 message: ['stdio[2]', '\'ignore\''],2 unmodified lines560 sourceOptions: {stdio: ['pipe', 'pipe', 'ignore']},561 from: 'stderr',562 message: ['stdio[2]', '\'ignore\''],563 });564+test('Cannot set "stdio[2]" option to "ignore" to use .iterable("stderr")', testIterable, {565+ sourceOptions: {stdio: ['pipe', 'pipe', 'ignore']},566+ from: 'stderr',567+ message: ['stdio[2]', '\'ignore\''],568+});569 test('Cannot set "stdio[3]" option to "ignore" to use .pipe(3)', testPipeError, {570 sourceOptions: getStdio(3, 'ignore'),571 from: 'fd3',572 message: ['stdio[3]', '\'ignore\''],2 unmodified lines575 sourceOptions: getStdio(3, 'ignore'),576 from: 'fd3',577 message: ['stdio[3]', '\'ignore\''],578 });579+test('Cannot set "stdio[3]" option to "ignore" to use .iterable(3)', testIterable, {580+ sourceOptions: getStdio(3, 'ignore'),581+ from: 'fd3',582+ message: ['stdio[3]', '\'ignore\''],583+});584 test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe("all")', testPipeError, {585 sourceOptions: {stdout: 'ignore', stderr: 'ignore', all: true},586 from: 'all',587 message: ['stdout', '\'ignore\''],2 unmodified lines590 sourceOptions: {stdout: 'ignore', stderr: 'ignore', all: true},591 from: 'all',592 message: ['stdout', '\'ignore\''],593 });594+test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable("all")', testIterable, {595+ sourceOptions: {stdout: 'ignore', stderr: 'ignore', all: true},596+ from: 'all',597+ message: ['stdout', '\'ignore\''],598+});599 test('Cannot set "stdio[1]" + "stdio[2]" option to "ignore" to use .pipe("all")', testPipeError, {600 sourceOptions: {stdio: ['pipe', 'ignore', 'ignore'], all: true},601 from: 'all',602 message: ['stdio[1]', '\'ignore\''],2 unmodified lines605 sourceOptions: {stdio: ['pipe', 'ignore', 'ignore'], all: true},606 from: 'all',607 message: ['stdio[1]', '\'ignore\''],608 });609+test('Cannot set "stdio[1]" + "stdio[2]" option to "ignore" to use .iterable("all")', testIterable, {610+ sourceOptions: {stdio: ['pipe', 'ignore', 'ignore'], all: true},611+ from: 'all',612+ message: ['stdio[1]', '\'ignore\''],613+});614 test('Cannot set "stdout" option to "inherit" to use .pipe()', testPipeError, {615 sourceOptions: {stdout: 'inherit'},616 message: ['stdout', '\'inherit\''],617 });618 test('Cannot set "stdout" option to "inherit" to use .duplex()', testNodeStream, {619 sourceOptions: {stdout: 'inherit'},620 message: ['stdout', '\'inherit\''],621 });622+test('Cannot set "stdout" option to "inherit" to use .iterable()', testIterable, {623+ sourceOptions: {stdout: 'inherit'},624+ message: ['stdout', '\'inherit\''],625+});626 test('Cannot set "stdin" option to "inherit" to use .pipe()', testPipeError, {627 destinationOptions: {stdin: 'inherit'},628 message: ['stdin', '\'inherit\''],629 });9 unmodified lines639 test('Cannot set "stdout" option to "ipc" to use .duplex()', testNodeStream, {640 sourceOptions: {stdout: 'ipc'},641 message: ['stdout', '\'ipc\''],642 });643+test('Cannot set "stdout" option to "ipc" to use .iterable()', testIterable, {644+ sourceOptions: {stdout: 'ipc'},645+ message: ['stdout', '\'ipc\''],646+});647 test('Cannot set "stdin" option to "ipc" to use .pipe()', testPipeError, {648 destinationOptions: {stdin: 'ipc'},649 message: ['stdin', '\'ipc\''],650 });9 unmodified lines660 test('Cannot set "stdout" option to file descriptors to use .duplex()', testNodeStream, {661 sourceOptions: {stdout: 1},662 message: ['stdout', '1'],663 });664+test('Cannot set "stdout" option to file descriptors to use .iterable()', testIterable, {665+ sourceOptions: {stdout: 1},666+ message: ['stdout', '1'],667+});668 test('Cannot set "stdin" option to file descriptors to use .pipe()', testPipeError, {669 destinationOptions: {stdin: 0},670 message: ['stdin', '0'],671 });9 unmodified lines681 test('Cannot set "stdout" option to Node.js streams to use .duplex()', testNodeStream, {682 sourceOptions: {stdout: process.stdout},683 message: ['stdout', 'Stream'],684 });685+test('Cannot set "stdout" option to Node.js streams to use .iterable()', testIterable, {686+ sourceOptions: {stdout: process.stdout},687+ message: ['stdout', 'Stream'],688+});689 test('Cannot set "stdin" option to Node.js streams to use .pipe()', testPipeError, {690 destinationOptions: {stdin: process.stdin},691 message: ['stdin', 'Stream'],692 });11 unmodified lines704 sourceOptions: getStdio(3, process.stdout),705 message: ['stdio[3]', 'Stream'],706 from: 'fd3',707 });708+test('Cannot set "stdio[3]" option to Node.js Writable streams to use .iterable()', testIterable, {709+ sourceOptions: getStdio(3, process.stdout),710+ message: ['stdio[3]', 'Stream'],711+ from: 'fd3',712+});713 test('Cannot set "stdio[3]" option to Node.js Readable streams to use .pipe()', testPipeError, {714 destinationOptions: getStdio(3, process.stdin),715 message: ['stdio[3]', 'Stream'],716 to: 'fd3',67 unmodified linesmodified:test/stream/subprocess.js+2 added-7 removed
1-import {platform} from 'node:process';1 import {setTimeout} from 'node:timers/promises';2 import test from 'ava';3 import {execa} from '../../index.js';4 import {setFixtureDir} from '../helpers/fixtures-dir.js';6-import {fullStdio, getStdio, prematureClose} from '../helpers/stdio.js';5+import {fullStdio, getStdio, prematureClose, assertEpipe} from '../helpers/stdio.js';6 import {infiniteGenerator} from '../helpers/generator.js';7 8 setFixtureDir();9 11-const isWindows = platform === 'win32';12-10 const getStreamInputSubprocess = fdNumber => execa('stdin-fd.js', [`${fdNumber}`], fdNumber === 311 ? getStdio(3, [new Uint8Array(), infiniteGenerator])12 : {});13 const getStreamOutputSubprocess = fdNumber => execa('noop-repeat.js', [`${fdNumber}`], fdNumber === 3 ? fullStdio : {});13 unmodified lines27 t.is(signal, undefined);28 t.false(isTerminated);29 t.true(failed);30 34- if (fdNumber === 1 && !isWindows) {35- t.true(stderr.includes('EPIPE'));36- }31+ assertEpipe(t, stderr, fdNumber);32 };33 34 const testStreamInputAbort = async (t, fdNumber) => {35 const subprocess = getStreamInputSubprocess(fdNumber);82 unmodified linesmodified:test/stream/wait.js+2 added-7 removed
1-import {platform} from 'node:process';1 import {setImmediate} from 'node:timers/promises';2 import test from 'ava';3 import {execa} from '../../index.js';4 import {setFixtureDir} from '../helpers/fixtures-dir.js';6-import {getStdio, prematureClose} from '../helpers/stdio.js';5+import {getStdio, prematureClose, assertEpipe} from '../helpers/stdio.js';6 import {foobarString} from '../helpers/input.js';7 import {noopGenerator} from '../helpers/generator.js';8 import {noopReadable, noopWritable, noopDuplex} from '../helpers/stream.js';9 10 setFixtureDir();11 13-const isWindows = platform === 'win32';14-12 const noop = () => {};13 14 const endOptionStream = ({stream}) => {15 stream.end();107 unmodified lines123 const {exitCode, stdio, stderr} = await t.throwsAsync(subprocess);124 t.is(exitCode, 1);125 t.is(stdio[fdNumber], '');126 t.true(stream.destroyed);130- if (fdNumber !== 2 && !isWindows) {131- t.true(stderr.includes('EPIPE'));132- }127+ assertEpipe(t, stderr, fdNumber);128 };129 130 test('Throws EPIPE when stdout option ends with more writes', testStreamEpipeFail, endOptionStream, noopWritable(), 1, false);131 test('Throws EPIPE when stdout option aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopWritable(), 1, false);80 unmodified linesmodified:index.d.ts+31 added-6 removed
989 unmodified lines990 991 /**992 If `false`, the stream iterates over lines. Each line is a string. Also, the stream is in [object mode](https://nodejs.org/api/stream.html#object-mode).993 994- If `true`, the stream iterates over arbitrary chunks of data. Each line is a [`Buffer`](https://nodejs.org/api/buffer.html#class-buffer).994+ If `true`, the stream iterates over arbitrary chunks of data. Each line is an `Uint8Array` (with `.iterable()`) or a [`Buffer`](https://nodejs.org/api/buffer.html#class-buffer) (otherwise).995 996- @default true996+ @default `false` with `.iterable()` and `encoding: 'buffer'`, `true` otherwise997 */998 readonly binary?: boolean;999 1000 /**1001 If both this option and the `binary` option is `false`, newlines are stripped from each line.1002 1003- @default true1003+ @default `false` with `.iterable()`, `true` otherwise1004 */1005 readonly preserveNewlines?: boolean;1006 };1007 7 unmodified lines1015 };1016 1017 type DuplexOptions = ReadableOptions & WritableOptions;1018 1019+type SubprocessAsyncIterable<1020+ BinaryOption extends boolean | undefined,1021+ EncodingOption extends Options['encoding'],1022+> = AsyncIterableIterator<1023+BinaryOption extends true1024+ ? Uint8Array1025+ : BinaryOption extends false1026+ ? string1027+ : EncodingOption extends 'buffer'1028+ ? Uint8Array1029+ : string1030+>;1031+1032 export type ExecaResultPromise<OptionsType extends Options = Options> = {1033 stdin: StreamUnlessIgnored<'0', OptionsType>;1034 1035 stdout: StreamUnlessIgnored<'1', OptionsType>;25 unmodified lines1061 kill(signal: Parameters<ChildProcess['kill']>[0], error?: Error): ReturnType<ChildProcess['kill']>;1062 kill(error?: Error): ReturnType<ChildProcess['kill']>;1063 1064 /**1065+ Subprocesses are [async iterables](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/asyncIterator). They iterate over each output line.1066+1067+ The iteration waits for the subprocess to end. It throws if the subprocess fails. This means you do not need to `await` the subprocess' promise.1068+ */1069+ [Symbol.asyncIterator](): SubprocessAsyncIterable<undefined, OptionsType['encoding']>;1070+1071+ /**1072+ Same as `subprocess[Symbol.asyncIterator]` except options can be provided.1073+ */1074+ iterable<IterableOptions extends ReadableOptions = {}>(readableOptions?: IterableOptions): SubprocessAsyncIterable<IterableOptions['binary'], OptionsType['encoding']>;1075+1076+ /**1077 Converts the subprocess to a readable stream.1078 1079 Unlike [`subprocess.stdout`](https://nodejs.org/api/child_process.html#subprocessstdout), the stream waits for the subprocess to end and emits an [`error`](https://nodejs.org/api/stream.html#event-error) event if the subprocess fails. This means you do not need to `await` the subprocess' promise. On the other hand, you do need to handle to the stream `error` event. This can be done by using [`await finished(stream)`](https://nodejs.org/api/stream.html#streamfinishedstream-options), [`await pipeline(..., stream)`](https://nodejs.org/api/stream.html#streampipelinesource-transforms-destination-options) or [`await text(stream)`](https://nodejs.org/api/webstreams.html#streamconsumerstextstream) which throw an exception when the stream errors.1080 1056- Before using this method, please first consider the `stdin`/`stdout`/`stderr`/`stdio` options or the `subprocess.pipe()` method.1081+ Before using this method, please first consider the `stdin`/`stdout`/`stderr`/`stdio` options, `subprocess.pipe()` or `subprocess.iterable()`.1082 */1083 readable(readableOptions?: ReadableOptions): Readable;1084 1085 /**1086 Converts the subprocess to a writable stream.1087 1088 Unlike [`subprocess.stdin`](https://nodejs.org/api/child_process.html#subprocessstdin), the stream waits for the subprocess to end and emits an [`error`](https://nodejs.org/api/stream.html#event-error) event if the subprocess fails. This means you do not need to `await` the subprocess' promise. On the other hand, you do need to handle to the stream `error` event. This can be done by using [`await finished(stream)`](https://nodejs.org/api/stream.html#streamfinishedstream-options) or [`await pipeline(stream, ...)`](https://nodejs.org/api/stream.html#streampipelinesource-transforms-destination-options) which throw an exception when the stream errors.1089 1065- Before using this method, please first consider the `stdin`/`stdout`/`stderr`/`stdio` options or the `subprocess.pipe()` method.1090+ Before using this method, please first consider the `stdin`/`stdout`/`stderr`/`stdio` options or `subprocess.pipe()`.1091 */1092 writable(writableOptions?: WritableOptions): Writable;1093 1094 /**1095 Converts the subprocess to a duplex stream.1096 1097 The stream waits for the subprocess to end and emits an [`error`](https://nodejs.org/api/stream.html#event-error) event if the subprocess fails. This means you do not need to `await` the subprocess' promise. On the other hand, you do need to handle to the stream `error` event. This can be done by using [`await finished(stream)`](https://nodejs.org/api/stream.html#streamfinishedstream-options), [`await pipeline(..., stream, ...)`](https://nodejs.org/api/stream.html#streampipelinesource-transforms-destination-options) or [`await text(stream)`](https://nodejs.org/api/webstreams.html#streamconsumerstextstream) which throw an exception when the stream errors.1098 1074- Before using this method, please first consider the `stdin`/`stdout`/`stderr`/`stdio` options or the `subprocess.pipe()` method.1099+ Before using this method, please first consider the `stdin`/`stdout`/`stderr`/`stdio` options, `subprocess.pipe()` or `subprocess.iterable()`.1100 */1101 duplex(duplexOptions?: DuplexOptions): Duplex;1102 } & PipableSubprocess;1103 477 unmodified linesmodified:index.test-d.ts+67 added
266 unmodified lines267 expectType<string>(scriptShortcutPipeResult.stdout);268 const ignoreShortcutScriptPipeResult = await scriptPromise.pipe('stdin', {stdout: 'ignore'});269 expectType<undefined>(ignoreShortcutScriptPipeResult.stdout);270 271+ const asyncIteration = async () => {272+ for await (const line of scriptPromise) {273+ expectType<string>(line);274+ }275+276+ for await (const line of scriptPromise.iterable()) {277+ expectType<string>(line);278+ }279+280+ for await (const line of scriptPromise.iterable({binary: false})) {281+ expectType<string>(line);282+ }283+284+ for await (const line of scriptPromise.iterable({binary: true})) {285+ expectType<Uint8Array>(line);286+ }287+288+ for await (const line of scriptPromise.iterable({} as {binary: boolean})) {289+ expectType<string | Uint8Array>(line);290+ }291+292+ for await (const line of execaBufferPromise) {293+ expectType<Uint8Array>(line);294+ }295+296+ for await (const line of execaBufferPromise.iterable()) {297+ expectType<Uint8Array>(line);298+ }299+300+ for await (const line of execaBufferPromise.iterable({binary: false})) {301+ expectType<string>(line);302+ }303+304+ for await (const line of execaBufferPromise.iterable({binary: true})) {305+ expectType<Uint8Array>(line);306+ }307+308+ for await (const line of execaBufferPromise.iterable({} as {binary: boolean})) {309+ expectType<string | Uint8Array>(line);310+ }311+ };312+313+ await asyncIteration();314+ expectAssignable<AsyncIterable<string>>(scriptPromise.iterable());315+ expectAssignable<AsyncIterable<string>>(scriptPromise.iterable({binary: false}));316+ expectAssignable<AsyncIterable<Uint8Array>>(scriptPromise.iterable({binary: true}));317+ expectAssignable<AsyncIterable<string | Uint8Array>>(scriptPromise.iterable({} as {binary: boolean}));318+ expectAssignable<AsyncIterable<Uint8Array>>(execaBufferPromise.iterable());319+ expectAssignable<AsyncIterable<string>>(execaBufferPromise.iterable({binary: false}));320+ expectAssignable<AsyncIterable<Uint8Array>>(execaBufferPromise.iterable({binary: true}));321+ expectAssignable<AsyncIterable<string | Uint8Array>>(execaBufferPromise.iterable({} as {binary: boolean}));322+323 expectType<Readable>(scriptPromise.readable());324 expectType<Writable>(scriptPromise.writable());325 expectType<Duplex>(scriptPromise.duplex());326 327+ scriptPromise.iterable({});328+ scriptPromise.iterable({from: 'stdout'});329+ scriptPromise.iterable({from: 'stderr'});330+ scriptPromise.iterable({from: 'all'});331+ scriptPromise.iterable({from: 'fd3'});332+ scriptPromise.iterable({binary: false});333+ scriptPromise.iterable({preserveNewlines: false});334+ expectError(scriptPromise.iterable('stdout'));335+ expectError(scriptPromise.iterable({from: 'stdin'}));336+ expectError(scriptPromise.iterable({from: 'fd'}));337+ expectError(scriptPromise.iterable({from: 'fdNotANumber'}));338+ expectError(scriptPromise.iterable({binary: 'false'}));339+ expectError(scriptPromise.iterable({preserveNewlines: 'false'}));340+ expectError(scriptPromise.iterable({to: 'stdin'}));341+ expectError(scriptPromise.iterable({other: 'stdout'}));342 scriptPromise.readable({});343 scriptPromise.readable({from: 'stdout'});344 scriptPromise.readable({from: 'stderr'});345 scriptPromise.readable({from: 'all'});1394 unmodified linesmodified:readme.md+35 added-7 removed
206 unmodified lines207 console.log(pipedFrom[0]); // Result of `sort`208 console.log(pipedFrom[0].pipedFrom[0]); // Result of `npm run build`209 ```210 211+#### Iterate over output lines212+213+```js214+import {execa} from 'execa';215+216+for await (const line of execa('npm', ['run', 'build'])) {217+ if (line.includes('ERROR')) {218+ console.log(line);219+ }220+}221+```222+223 ### Handling Errors224 225 ```js226 import {execa} from 'execa';222 unmodified lines449 When an error is passed as argument, it is set to the subprocess' [`error.cause`](#cause). The subprocess is then terminated with the default signal. This does not emit the [`error` event](https://nodejs.org/api/child_process.html#event-error).450 451 [More info.](https://nodejs.org/api/child_process.html#subprocesskillsignal)452 453+#### [Symbol.asyncIterator]()454+455+_Returns_: `AsyncIterable`456+457+Subprocesses are [async iterables](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/asyncIterator). They iterate over each output line.458+459+The iteration waits for the subprocess to end. It throws if the subprocess [fails](#subprocessresult). This means you do not need to `await` the subprocess' [promise](#subprocess).460+461+#### iterable(readableOptions?)462+463+`readableOptions`: [`ReadableOptions`](#readableoptions)\464+_Returns_: `AsyncIterable`465+466+Same as [`subprocess[Symbol.asyncIterator]`](#symbolasynciterator) except [options](#readableoptions) can be provided.467+468 #### readable(readableOptions?)469 470 `readableOptions`: [`ReadableOptions`](#readableoptions)\471 _Returns_: [`Readable`](https://nodejs.org/api/stream.html#class-streamreadable) Node.js stream1 unmodified line473 Converts the subprocess to a readable stream.474 475 Unlike [`subprocess.stdout`](https://nodejs.org/api/child_process.html#subprocessstdout), the stream waits for the subprocess to end and emits an [`error`](https://nodejs.org/api/stream.html#event-error) event if the subprocess [fails](#subprocessresult). This means you do not need to `await` the subprocess' [promise](#subprocess). On the other hand, you do need to handle to the stream `error` event. This can be done by using [`await finished(stream)`](https://nodejs.org/api/stream.html#streamfinishedstream-options), [`await pipeline(..., stream)`](https://nodejs.org/api/stream.html#streampipelinesource-transforms-destination-options) or [`await text(stream)`](https://nodejs.org/api/webstreams.html#streamconsumerstextstream) which throw an exception when the stream errors.476 450-Before using this method, please first consider the [`stdin`](#stdin)/[`stdout`](#stdout-1)/[`stderr`](#stderr-1)/[`stdio`](#stdio-1) options or the [`subprocess.pipe()`](#pipefile-arguments-options) method.477+Before using this method, please first consider the [`stdin`](#stdin)/[`stdout`](#stdout-1)/[`stderr`](#stderr-1)/[`stdio`](#stdio-1) options, [`subprocess.pipe()`](#pipefile-arguments-options) or [`subprocess.iterable()`](#iterablereadableoptions).478 479 #### writable(writableOptions?)480 481 `writableOptions`: [`WritableOptions`](#writableoptions)\2 unmodified lines484 Converts the subprocess to a writable stream.485 486 Unlike [`subprocess.stdin`](https://nodejs.org/api/child_process.html#subprocessstdin), the stream waits for the subprocess to end and emits an [`error`](https://nodejs.org/api/stream.html#event-error) event if the subprocess [fails](#subprocessresult). This means you do not need to `await` the subprocess' [promise](#subprocess). On the other hand, you do need to handle to the stream `error` event. This can be done by using [`await finished(stream)`](https://nodejs.org/api/stream.html#streamfinishedstream-options) or [`await pipeline(stream, ...)`](https://nodejs.org/api/stream.html#streampipelinesource-transforms-destination-options) which throw an exception when the stream errors.487 461-Before using this method, please first consider the [`stdin`](#stdin)/[`stdout`](#stdout-1)/[`stderr`](#stderr-1)/[`stdio`](#stdio-1) options or the [`subprocess.pipe()`](#pipefile-arguments-options) method.488+Before using this method, please first consider the [`stdin`](#stdin)/[`stdout`](#stdout-1)/[`stderr`](#stderr-1)/[`stdio`](#stdio-1) options or [`subprocess.pipe()`](#pipefile-arguments-options).489 490 #### duplex(duplexOptions?)491 492 `duplexOptions`: [`ReadableOptions | WritableOptions`](#readableoptions)\2 unmodified lines495 Converts the subprocess to a duplex stream.496 497 The stream waits for the subprocess to end and emits an [`error`](https://nodejs.org/api/stream.html#event-error) event if the subprocess [fails](#subprocessresult). This means you do not need to `await` the subprocess' [promise](#subprocess). On the other hand, you do need to handle to the stream `error` event. This can be done by using [`await finished(stream)`](https://nodejs.org/api/stream.html#streamfinishedstream-options), [`await pipeline(..., stream, ...)`](https://nodejs.org/api/stream.html#streampipelinesource-transforms-destination-options) or [`await text(stream)`](https://nodejs.org/api/webstreams.html#streamconsumerstextstream) which throw an exception when the stream errors.498 472-Before using this method, please first consider the [`stdin`](#stdin)/[`stdout`](#stdout-1)/[`stderr`](#stderr-1)/[`stdio`](#stdio-1) options or the [`subprocess.pipe()`](#pipefile-arguments-options) method.499+Before using this method, please first consider the [`stdin`](#stdin)/[`stdout`](#stdout-1)/[`stderr`](#stderr-1)/[`stdio`](#stdio-1) options, [`subprocess.pipe()`](#pipefile-arguments-options) or [`subprocess.iterable()`](#iterablereadableoptions).500 501 ##### readableOptions502 503 Type: `object`8 unmodified lines512 `"all"` reads both `stdout` and `stderr`. This requires the [`all` option](#all-2) to be `true`.513 514 ##### readableOptions.binary515 489-Type: `boolean`\490-Default: `true`516+Type: `boolean`517 518 If `false`, the stream iterates over lines. Each line is a string. Also, the stream is in [object mode](https://nodejs.org/api/stream.html#object-mode).519 494-If `true`, the stream iterates over arbitrary chunks of data. Each line is a [`Buffer`](https://nodejs.org/api/buffer.html#class-buffer).520+If `true`, the stream iterates over arbitrary chunks of data. Each line is an `Uint8Array` (with [`.iterable()`](#iterablereadableoptions)) or a [`Buffer`](https://nodejs.org/api/buffer.html#class-buffer) (otherwise).521 522+With [`.readable()`](#readablereadableoptions)/[`.duplex()`](#duplexduplexoptions), the default value is `true`. With [`.iterable()`](#iterablereadableoptions), the default value is `true` if the [`encoding` option](#encoding) is `buffer`, otherwise it is `false`.523+524 ##### readableOptions.preserveNewlines525 526 Type: `boolean`\499-Default: `true`527+Default: `false` with [`.iterable()`](#iterablereadableoptions), `true` with [`.readable()`](#readablereadableoptions)/[`.duplex()`](#duplexduplexoptions)528 529 If both this option and the [`binary` option](#readableoptionsbinary) is `false`, newlines are stripped from each line.530 531 ##### writableOptions679 unmodified lines