Fix `.pipe()` and stream conversion edge cases
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Sindre Sorhus · committed by Sindre Sorhus · parent fb92da1 · Browse files · 16 files·+394 added−26 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
16 files+394 added−26 removed
- tests:+303 added−1 removed
- other:+91 added−25 removed
Provenance
- Commit
d3ec10d- Tree
b9f0430- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
fb92da1
16 files changed+394 added−26 removed
modified:lib/convert/readable.js+6 added-5 removed
7 unmodified lines891011121213141516100 unmodified lines1171181191201211221211221231241251261251261271281291301311327 unmodified linesimport {addConcurrentStream, waitForConcurrentStreams} from './concurrent.js';import { safeWaitForSubprocessStdin, waitForSubprocessStdout, waitForSubprocess, throwDestroyError, destroyOtherStream,} from './shared.js';
// Create a `Readable` stream that forwards from `stdout` and awaits the subprocess100 unmodified lines};
// When `readable` aborts/errors, do the same on `subprocess.stdout`export const onReadableDestroy = async ({subprocessStdout, subprocess, waitReadableDestroy}, error) => { if (!await waitForConcurrentStreams(waitReadableDestroy, subprocess)) { return; if (await waitForConcurrentStreams(waitReadableDestroy, subprocess)) { // Breaking out of `for await (const chunk of readable)` or cancelling `subprocess.readableStream()` destroys `readable` with an `AbortError`. Like `readable.destroy()`, this aborts `subprocess.stdout` instead of making it fail. destroyOtherReadable(subprocessStdout, error?.code === 'ABORT_ERR' ? undefined : error); await subprocess; }
destroyOtherReadable(subprocessStdout, error); await waitForSubprocess(subprocess, error); throwDestroyError(error);};
const destroyOtherReadable = (stream, error) => { destroyOtherStream(stream, stream.readable, error);};modified:lib/convert/shared.js+3 added-3 removed
27 unmodified lines28293031323334323334353637388 unmodified lines27 unmodified linesexport const waitForSubprocessStdout = async subprocessStdout => { await finished(subprocessStdout, {cleanup: true, readable: true, writable: false});};
// When `readable` or `writable` aborts/errors, awaits the subprocess, for the reason mentioned aboveexport const waitForSubprocess = async (subprocess, error) => { await subprocess;// When `readable` or `writable` aborts/errors, the caller awaits the subprocess, for the reason mentioned above.// Then, the error passed to `stream.destroy(error)` is emitted, including when the subprocess has already ended.export const throwDestroyError = error => { if (error) { throw error; }};8 unmodified linesmodified:lib/convert/writable.js+10 added-7 removed
5 unmodified lines6 import {addConcurrentStream, waitForConcurrentStreams} from './concurrent.js';7 import {8 safeWaitForSubprocessStdout,9 waitForSubprocessStdin,10- waitForSubprocess,10+ throwDestroyError,11 destroyOtherStream,12 } from './shared.js';13 14 // Create a `Writable` stream that forwards to `stdin` and awaits the subprocess62 unmodified lines77 writable.end();78 }79 } catch (error) {80 await safeWaitForSubprocessStdout(subprocessStdout);81+ // `writable.writable` is already `false` once `writable.end()` is called, although its pending writes still wait for `stdin`81- destroyOtherWritable(writable, await getSubprocessError(subprocess, error));82+ destroyOtherStream(writable, !writable.writableFinished, await getSubprocessError(subprocess, error));83 }84 };85 86 const getSubprocessError = async (subprocess, error) => {9 unmodified lines96 97 return error;98 };99 100+// `EPIPE` happens when the subprocess fails without reading its `stdin`, e.g. when it fails to spawn101 const shouldUseSubprocessError = error => error === undefined100- || isStreamAbort(error);102+ || isStreamAbort(error)103+ || error.code === 'EPIPE';104 105 // When `writable` aborts/errors, do the same on `subprocess.stdin`106 export const onWritableDestroy = async ({subprocessStdin, subprocess, waitWritableFinal, waitWritableDestroy}, error) => {107 await waitForConcurrentStreams(waitWritableFinal, subprocess);105- if (!await waitForConcurrentStreams(waitWritableDestroy, subprocess)) {106- return;108+ if (await waitForConcurrentStreams(waitWritableDestroy, subprocess)) {109+ destroyOtherWritable(subprocessStdin, error);110+ await subprocess;111 }112 109- destroyOtherWritable(subprocessStdin, error);110- await waitForSubprocess(subprocess, error);113+ throwDestroyError(error);114 };115 116 const destroyOtherWritable = (stream, error) => {117 destroyOtherStream(stream, stream.writable, error);1 unmodified linemodified:lib/io/pipeline.js+9 added-4 removed
1 import {finished} from 'node:stream/promises';2 import {isStandardStream} from '../utils/standard-stream.js';3 4-// Similar to `Stream.pipeline(source, destination)`, but does not destroy standard streams5-export const pipeStreams = (source, destination) => {4+// Similar to `Stream.pipeline(source, destination)`, but does not destroy standard streams.5+// `onDestinationEnd` runs when the destination ends, before the source is aborted.6+export const pipeStreams = (source, destination, onDestinationEnd) => {7 source.pipe(destination);8 onSourceFinish(source, destination);8- onDestinationFinish(source, destination);9+ onDestinationFinish(source, destination, onDestinationEnd);10 };11 12 // `source.pipe(destination)` makes `destination` end when `source` ends.13 // But it does not propagate aborts or errors. This function does it.15 unmodified lines29 }30 };31 32 // We do the same thing in the other direction as well.32-const onDestinationFinish = async (source, destination) => {33+const onDestinationFinish = async (source, destination, onDestinationEnd) => {34 if (isStandardStream(source) || isStandardStream(destination)) {35 return;36 }37 38 try {39 await finished(destination, {cleanup: true, readable: false, writable: true});40 } catch {}41 42+ if (onDestinationEnd !== undefined) {43+ await onDestinationEnd();44+ }45+46 abortSourceStream(source);47 };48 49 export const abortSourceStream = source => {4 unmodified linesmodified:lib/pipe/abort.js+2 added-1 removed
1 import {aborted} from 'node:util';2 import {createNonCommandError} from './throw.js';3+import {unpipeSubprocessStream} from './streaming.js';4 5 // When passing an `unpipeSignal` option, abort piping when the signal is aborted.6 // However, do not terminate the subprocesses.7 export const unpipeOnAbort = (unpipeSignal, unpipeContext) => unpipeSignal === undefined1 unmodified line9 : [unpipeOnSignalAbort(unpipeSignal, unpipeContext)];10 11 const unpipeOnSignalAbort = async (unpipeSignal, {sourceStream, mergedStream, fileDescriptors, sourceOptions, startTime}) => {12 await aborted(unpipeSignal, sourceStream);12- await mergedStream.remove(sourceStream);13+ await unpipeSubprocessStream(mergedStream, sourceStream);14 const error = new Error('Pipe canceled by `unpipeSignal` option.');15 throw createNonCommandError({16 error,17 fileDescriptors,4 unmodified linesmodified:lib/pipe/pipe-arguments.js+1 added
15 unmodified lines16 } = getDestinationStream(boundOptions, createNested, pipeArguments);17 const {sourceStream, sourceError} = getSourceStream(source, from);18 const {options: sourceOptions, fileDescriptors} = SUBPROCESS_OPTIONS.get(source);19 return {20+ source,21 sourcePromise,22 sourceStream,23 sourceOptions,24 sourceError,99 unmodified linesmodified:lib/pipe/sequence.js+3 added-2 removed
4 unmodified lines5 export const waitForBothSubprocesses = async subprocessPromises => {6 const [7 {status: sourceStatus, reason: sourceReason, value: sourceResult = sourceReason},8 {status: destinationStatus, reason: destinationReason, value: destinationResult = destinationReason},9+ {reason: pipedFromReason, value: pipedFromResult = pipedFromReason},10 ] = await subprocessPromises;11 11- if (!destinationResult.pipedFrom.includes(sourceResult)) {12- destinationResult.pipedFrom.push(sourceResult);12+ if (!destinationResult.pipedFrom.includes(pipedFromResult)) {13+ destinationResult.pipedFrom.push(pipedFromResult);14 }15 16 if (destinationStatus === 'rejected') {17 throw destinationResult;8 unmodified linesmodified:lib/pipe/setup.js+12 added-2 removed
19 unmodified lines20 boundOptions: {...sourceInfo.boundOptions, ...pipeArguments[0]},21 });22 }23 24+ // The previous `.pipe()` failed because of its arguments, so there is no source. Its promise rejects with that error.25+ // The destination is not spawned, since nothing would end its `stdin`.26+ if (sourceInfo.source === undefined) {27+ return sourceInfo.sourcePromise;28+ }29+30 const {destination, ...normalizedInfo} = normalizePipeArguments(sourceInfo, ...pipeArguments);31 const pipeFailureController = new AbortController();32 const promise = handlePipePromise({...normalizedInfo, destination, pipeFailureController});33 promise.pipe = pipeToSubprocess.bind(undefined, {46 unmodified lines80 Object.defineProperty(promise, 'all', {81 get() {82 setAllProperty(promise, destination.all);83 const all = promise.readable({from: 'all'});84+ // Like `subprocess.all`, the pipe's failure is handled by awaiting it, not by listening to the stream's `error` event. Consumers like `text(all)` still fail.85+ all.on('error', () => {});86 setAllProperty(promise, all);87 return all;88 },89 enumerable: true,98 unmodified lines188 // `writable()`, `duplex()`, `writableStream()` and `transformStream()` are intentionally not forwarded: they write to the destination's `stdin`, which is already being piped from the source.189 190 // Asynchronous logic when piping subprocesses191 const handlePipePromise = async ({192+ source,193 sourcePromise,194 sourceStream,195 sourceOptions,196 sourceError,6 unmodified lines203 pipeFailureController,204 }) => {205 const maxListenersController = new AbortController();206 try {198- const subprocessPromises = getSubprocessPromises(sourcePromise, destination);207+ const subprocessPromises = getSubprocessPromises(sourcePromise, destination, source);208 handlePipeArgumentsError({209 sourceStream,210 sourceError,211 destinationStream,23 unmodified lines235 236 // `.pipe()` awaits the subprocess promises.237 // When invalid arguments are passed to `.pipe()`, we throw an error, which prevents awaiting them.238 // We need to ensure this does not create unhandled rejections.230-const getSubprocessPromises = (sourcePromise, destination) => Promise.allSettled([sourcePromise, destination]);239+// With `source.pipe(destination).pipe(secondDestination)`, the second `sourcePromise` is the first `.pipe()`, which rejects with the error of either subprocess. However, `secondDestination` is only piped from `destination`.240+const getSubprocessPromises = (sourcePromise, destination, source) => Promise.allSettled([sourcePromise, destination, source]);modified:lib/pipe/streaming.js+44 added-1 removed
20 unmodified lines21 22 // We use `merge-streams` to allow for multiple sources to pipe to the same destination.23 const pipeFirstSubprocessStream = (sourceStream, destinationStream) => {24 const mergedStream = mergeStreams([sourceStream]);25- pipeStreams(mergedStream, destinationStream);25+ addMergeSource(mergedStream, sourceStream);26+ pipeStreams(mergedStream, destinationStream, () => unpipeSourcesOnDestinationEnd(mergedStream));27 MERGED_STREAMS.set(destinationStream, mergedStream);28 return mergedStream;29 };30 31 const pipeMoreSubprocessStream = (sourceStream, destinationStream) => {32 const mergedStream = MERGED_STREAMS.get(destinationStream);33 mergedStream.add(sourceStream);34+ addMergeSource(mergedStream, sourceStream);35 return mergedStream;36 };37 38+/*39+One source stream can be piped to multiple destinations, e.g. `subprocess.pipe(first)` and `subprocess.pipe(second)`.40+When a destination ends, its source must only be aborted when it is its last destination, so the other destinations keep receiving data.41+Sources with several destinations are then only removed from the ended destination's merge stream, instead of being aborted.42+This also holds when a source has been piped to one destination and unpiped from another one.43+*/44+const MERGE_SOURCES = new WeakMap();45+const SOURCE_MERGES = new WeakMap();46+47+const addMergeSource = (mergedStream, sourceStream) => {48+ addToSetMap(MERGE_SOURCES, mergedStream, sourceStream);49+ addToSetMap(SOURCE_MERGES, sourceStream, mergedStream);50+};51+52+const addToSetMap = (map, key, value) => {53+ if (!map.has(key)) {54+ map.set(key, new Set());55+ }56+57+ map.get(key).add(value);58+};59+60+// Stop piping a source into a destination, e.g. with the `unpipeSignal` option61+export const unpipeSubprocessStream = async (mergedStream, sourceStream) => {62+ MERGE_SOURCES.get(mergedStream)?.delete(sourceStream);63+ SOURCE_MERGES.get(sourceStream)?.delete(mergedStream);64+ await mergedStream.remove(sourceStream);65+};66+67+const unpipeSourcesOnDestinationEnd = async mergedStream => {68+ for (const sourceStream of MERGE_SOURCES.get(mergedStream)) {69+ const mergedStreams = SOURCE_MERGES.get(sourceStream);70+ mergedStreams.delete(mergedStream);71+ if (mergedStreams.size > 0) {72+ // Other destinations still need that source, so it must not be aborted73+ // eslint-disable-next-line no-await-in-loop74+ await mergedStream.remove(sourceStream);75+ }76+ }77+};78+79 const cleanupMergedStreamsMap = async destinationStream => {80 try {81 await finished(destinationStream, {cleanup: true, readable: false, writable: true});82 } catch {}12 unmodified linesmodified:lib/resolve/wait-stream.js+1 added
95 unmodified lines96 97 // When `stream.destroy()` is called without an `error` argument, stream is aborted.98 // This is the only way to abort a readable stream, which can be useful in some instances.99 // Therefore, we ignore this error on readable streams.100+// Breaking out of `for await (const chunk of subprocess.stdout)` aborts it with an `AbortError` instead. However, that error cannot be told apart from an `AbortError` thrown by a transform, which must make the subprocess fail. So this is not supported, and `subprocess.readable()` or `subprocess.iterable()` should be used instead.101 export const isStreamAbort = error => error?.code === 'ERR_STREAM_PREMATURE_CLOSE';102 103 // When `stream.write()` is called but the underlying source has been closed, `EPIPE` is emitted.104 // When piping subprocesses, the source subprocess usually decides when to stop piping.4 unmodified linesmodified:test/convert/readable.js+32 added
81 unmodified lines82 83 test('.readable() buffers until read', () => testBuffering('readable'));84 test('.duplex() buffers until read', () => testBuffering('duplex'));85 86+// Breaking out of `for await` or cancelling a web stream destroys the stream with an `AbortError`, which aborts it like `stream.destroy()`87+const testStopIteration = async stopIteration => {88+ const subprocess = execa('noop-delay.js', ['1', foobarString]);89+ await stopIteration(subprocess);90+ const {exitCode} = await subprocess;91+ assert.equal(exitCode, 0);92+};93+94+const stopIterator = async asyncIterable => {95+ const iterator = asyncIterable[Symbol.asyncIterator]();96+ await iterator.next();97+ await iterator.return();98+};99+100+const cancelReader = async readableStream => {101+ const reader = readableStream.getReader();102+ await reader.read();103+ await reader.cancel();104+};105+106+test('.readable() iteration can be stopped', () => testStopIteration(subprocess => stopIterator(subprocess.readable())));107+// This destroys `subprocess.stdout` with an `AbortError`, which cannot be told apart from an `AbortError` thrown by a transform. So this is not supported, and `subprocess.readable()` or `subprocess.iterable()` must be used instead.108+test('subprocess.stdout iteration cannot be stopped', async () => {109+ const subprocess = execa('noop-delay.js', ['1', foobarString]);110+ await stopIterator(subprocess.stdout);111+ const {code} = await assertRejects(subprocess);112+ assert.equal(code, 'ABORT_ERR');113+});114+test('.readableStream() can be cancelled', () => testStopIteration(subprocess => cancelReader(subprocess.readableStream())));115+test('.readableStream() iteration can be stopped', () => testStopIteration(subprocess => stopIterator(subprocess.readableStream())));116+test('.iterable() iteration can be stopped', () => testStopIteration(subprocess => stopIterator(subprocess.iterable())));117+118 test('.readable() abort -> subprocess fail', async () => {119 const subprocess = execa('noop-repeat.js');120 const stream = subprocess.readable();121 374 unmodified linesmodified:test/convert/shared.js+94 added
1 import assert from 'node:assert/strict';2+import {once} from 'node:events';3+import {setImmediate} from 'node:timers/promises';4 import test from 'node:test';5 import {assertRejects, assertThrows} from '../helpers/assert.js';6 import {execa} from '../../index.js';7 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';50 unmodified lines58 test('Do not need to await subprocess with .readable()', () => testSubprocessError('readable'));59 test('Do not need to await subprocess with .writable()', () => testSubprocessError('writable'));60 test('Do not need to await subprocess with .duplex()', () => testSubprocessError('duplex'));61 62+// Once the subprocess has ended, the error passed to `stream.destroy(error)` must still be emitted, including when another stream uses the same file descriptor63+const testDestroyAfterExit = async (methodName, fixtureName, otherMethodName) => {64+ const subprocess = execa(fixtureName, {reject: false});65+ const stream = subprocess[methodName]();66+ if (otherMethodName !== undefined) {67+ subprocess[otherMethodName]().on('error', () => {});68+ }69+70+ await subprocess;71+ const cause = new Error(foobarString);72+ let errorEvent;73+ stream.on('error', error => {74+ errorEvent = error;75+ });76+ stream.destroy(cause);77+ await assertRejects(finishedStream(stream));78+ assert.equal(errorEvent, cause);79+};80+81+test('.readable() destroy error after the subprocess ended', () => testDestroyAfterExit('readable', 'empty.js'));82+test('.writable() destroy error after the subprocess ended', () => testDestroyAfterExit('writable', 'empty.js'));83+test('.duplex() destroy error after the subprocess ended', () => testDestroyAfterExit('duplex', 'empty.js'));84+test('.readable() destroy error after the subprocess ended, with .duplex()', () => testDestroyAfterExit('readable', 'empty.js', 'duplex'));85+test('.writable() destroy error after the subprocess ended, with .duplex()', () => testDestroyAfterExit('writable', 'empty.js', 'duplex'));86+test('.duplex() destroy error after the subprocess ended, with .writable()', () => testDestroyAfterExit('duplex', 'empty.js', 'writable'));87+test('.duplex() destroy error after the subprocess ended, with .duplex()', () => testDestroyAfterExit('duplex', 'empty.js', 'duplex'));88+test('.readable() destroy error after the subprocess failed, with .duplex()', () => testDestroyAfterExit('readable', 'fail.js', 'duplex'));89+test('.writable() destroy error after the subprocess failed, with .duplex()', () => testDestroyAfterExit('writable', 'fail.js', 'duplex'));90+test('.duplex() destroy error after the subprocess failed, with .writable()', () => testDestroyAfterExit('duplex', 'fail.js', 'writable'));91+92+// The pending write waits for the `drain` event, so it must fail instead of hanging93+test('.writable() write fails when the subprocess fails to spawn', async () => {94+ const subprocess = execa('nonexistent-command-for-execa');95+ const stream = subprocess.writable();96+ const chunk = '.'.repeat(1e5);97+ const writeAll = async () => {98+ for (let index = 0; index < 1e2; index += 1) {99+ if (!stream.write(chunk)) {100+ // eslint-disable-next-line no-await-in-loop101+ await once(stream, 'drain');102+ }103+ }104+105+ stream.end();106+ await finishedStream(stream);107+ };108+109+ const error = await assertRejects(writeAll());110+ assert.equal(error, await assertRejects(subprocess));111+});112+113+// The subprocess error is more useful than the `EPIPE` error it causes on `stdin`114+const testSpawnFailureWrite = async methodName => {115+ const subprocess = execa('nonexistent-command-for-execa');116+ const stream = subprocess[methodName]();117+ stream.end(foobarString);118+ const error = await assertRejects(finishedStream(stream));119+ assert.equal(error, await assertRejects(subprocess));120+ assert.equal(error.code, 'ENOENT');121+};122+123+test('.writable() fails with the subprocess error when the subprocess fails to spawn', () => testSpawnFailureWrite('writable'));124+test('.duplex() fails with the subprocess error when the subprocess fails to spawn', () => testSpawnFailureWrite('duplex'));125+126+// The pending write waits for the `drain` event of `stdin`, which has been destroyed, so the stream must be destroyed too, even though it is ending127+const testWriteAfterExit = async (methodName, isSameTick) => {128+ const subprocess = execa('empty.js');129+ await subprocess;130+ const stream = subprocess[methodName]();131+ if (!isSameTick) {132+ await setImmediate();133+ }134+135+ stream.end(foobarString);136+ const error = await assertRejects(finishedStream(stream));137+ assert.equal(error.code, 'ERR_STREAM_PREMATURE_CLOSE');138+};139+140+test('.writable() fails when ending it after the subprocess ended', () => testWriteAfterExit('writable', true));141+test('.duplex() fails when ending it after the subprocess ended', () => testWriteAfterExit('duplex', true));142+test('.writable() fails when ending it later after the subprocess ended', () => testWriteAfterExit('writable', false));143+test('.duplex() fails when ending it later after the subprocess ended', () => testWriteAfterExit('duplex', false));144+145+test('.writable() fails with the subprocess error when the subprocess fails without reading stdin', async () => {146+ const subprocess = execa('fail.js');147+ const stream = subprocess.writable();148+ stream.end('.'.repeat(1e6));149+ const error = await assertRejects(finishedStream(stream));150+ assert.equal(error, await assertRejects(subprocess));151+ assert.equal(error.exitCode, 2);152+});153+154 const testNullOptions = async methodName => {155 const subprocess = getReadWriteSubprocess();156 subprocess.stdin.end();157 assertThrows(() => {9 unmodified linesmodified:test/pipe/methods.js+23 added-1 removed
1 import assert from 'node:assert/strict';2 import {setTimeout} from 'node:timers/promises';3-import {Readable} from 'node:stream';3+import {Readable, Writable} from 'node:stream';4 import {text} from 'node:stream/consumers';5 import test from 'node:test';6 import {assertThrows, assertRejects} from '../helpers/assert.js';7 import {execa} from '../../index.js';369 unmodified lines377 378 await assertRejects(text(piped.all), {message: /Command failed with exit code 2/});379 });380 381+// Like `subprocess.all`, `.all` does not need an `error` listener, as long as the pipe is awaited382+test('The .pipe() return value .all does not need an error listener on source failure', async () => {383+ const piped = execa('fail.js').pipe('stdin.js', {all: true});384+ piped.all.resume();385+ await assertRejects(piped, {message: /Command failed with exit code 2/});386+ await setTimeout(0);387+});388+389+test('The .pipe() return value .all does not need an error listener when piped', async () => {390+ const piped = execa('fail.js').pipe('stdin.js', {all: true});391+ const chunks = [];392+ piped.all.pipe(new Writable({393+ write(chunk, encoding, done) {394+ chunks.push(chunk);395+ done();396+ },397+ }));398+ await assertRejects(piped, {message: /Command failed with exit code 2/});399+ await setTimeout(0);400+ assert.deepEqual(chunks, []);401+});402+403 const assertCanceledPipeReader = async (t, getReader, shouldAbortBeforePipe = false) => {404 const abortController = new AbortController();405 if (shouldAbortBeforePipe) {406 abortController.abort();50 unmodified linesmodified:test/pipe/streaming.js+86 added
1 import assert from 'node:assert/strict';2 import {once} from 'node:events';3+import {setTimeout} from 'node:timers/promises';4 import {PassThrough} from 'node:stream';5 import test from 'node:test';6 import {assertRejects, assertLike} from '../helpers/assert.js';7 import {execa} from '../../index.js';364 unmodified lines372 assert.deepEqual(destinationResult.pipedFrom, [sourceResult]);373 assert.deepEqual(sourceResult.pipedFrom, []);374 });375 376+// The second destination is piped from the first destination, not from the source which failed377+test('Returns pipedFrom on deep source failure', async () => {378+ const source = execa('noop-fail.js', ['1', foobarString]);379+ const destination = execa('stdin.js');380+ const secondDestination = execa('stdin.js');381+ const pipePromise = source.pipe(destination);382+ const secondPipePromise = pipePromise.pipe(secondDestination);383+384+ const destinationResult = await destination;385+ const secondDestinationResult = await secondDestination;386+ const sourceResult = await assertRejects(source);387+388+ assert.equal(await assertRejects(secondPipePromise), sourceResult);389+ assert.deepEqual(secondDestinationResult.pipedFrom, [destinationResult]);390+ assert.equal(await assertRejects(pipePromise), sourceResult);391+ assert.deepEqual(destinationResult.pipedFrom, [sourceResult]);392+ assert.deepEqual(sourceResult.pipedFrom, []);393+});394+395+test('Returns pipedFrom on deep success, with a template string', async () => {396+ const pipePromise = execa('noop.js', [foobarString]).pipe`stdin.js`.pipe`stdin.js`;397+ const {stdout, pipedFrom} = await pipePromise;398+ assert.equal(stdout, foobarString);399+ const [destinationResult] = pipedFrom;400+ assert.equal(destinationResult.command, 'stdin.js');401+ assert.equal(destinationResult.pipedFrom[0].command, `noop.js ${foobarString}`);402+});403+404 test('Returns pipedFrom from multiple sources', async () => {405 const source = execa('noop.js', [foobarString]);406 const secondSource = execa('noop.js', [foobarString]);407 const destination = execa('stdin.js');70 unmodified lines478 stdio: ['pipe', 'pipe', 'pipe', {value: 'pipe', input: true}],479 });480 assert.equal(stdout, foobarString);481 });482+483+// `noop-repeat.js` writes every 10ms. `noop.js` exits right away, since it does not read its `stdin`.484+const testNoStarvation = async ({pipeOptions, sourceOptions, getExitingDestination = () => execa('noop.js')}) => {485+ const source = execa('noop-repeat.js', ['1', `${foobarString}\n`], sourceOptions);486+ const exitingDestination = getExitingDestination();487+ const receivingDestination = execa('stdin.js');488+ source.pipe(exitingDestination, pipeOptions).catch(() => {});489+ source.pipe(receivingDestination, pipeOptions).catch(() => {});490+491+ await exitingDestination;492+ await setTimeout(100);493+ source.kill();494+ // The source is not aborted with `EPIPE` when the first destination exits495+ const {isTerminated} = await assertRejects(source);496+ assert.ok(isTerminated);497+ const {stdout} = await receivingDestination;498+ assert.ok(stdout.split('\n').length > 2);499+};500+501+test('One destination exiting does not starve the other destinations', () => testNoStarvation({}));502+test('One destination exiting does not starve the other destinations, from "all"', () => testNoStarvation({sourceOptions: {all: true}, pipeOptions: {from: 'all'}}));503+// `stdin.js` exits when its `stdin` ends, while `noop-repeat.js` keeps running504+test('One destination ending its stdin does not starve the other destinations', () => testNoStarvation({505+ getExitingDestination() {506+ const destination = execa('stdin.js');507+ destination.stdin.end();508+ return destination;509+ },510+}));511+512+test('The source is aborted when all its destinations exit', async () => {513+ const source = execa('noop-repeat.js', ['1', `${foobarString}\n`]);514+ source.pipe(execa('noop.js')).catch(() => {});515+ source.pipe(execa('noop.js')).catch(() => {});516+ const {isTerminated, exitCode} = await assertRejects(source);517+ assert.ok(!isTerminated);518+ assert.equal(exitCode, 1);519+});520+521+test('The other sources of an exiting destination are aborted, unless they have other destinations', async () => {522+ const source = execa('noop-repeat.js', ['1', `${foobarString}\n`]);523+ const secondSource = execa('noop-repeat.js', ['1', `${foobarString}\n`]);524+ const exitingDestination = execa('noop.js');525+ const receivingDestination = execa('stdin.js');526+ source.pipe(exitingDestination).catch(() => {});527+ secondSource.pipe(exitingDestination).catch(() => {});528+ source.pipe(receivingDestination).catch(() => {});529+530+ const {exitCode} = await assertRejects(secondSource);531+ assert.equal(exitCode, 1);532+ await setTimeout(200);533+ source.kill();534+ const {isTerminated} = await assertRejects(source);535+ assert.ok(isTerminated);536+ const {stdout} = await receivingDestination;537+ assert.ok(stdout.split('\n').length > 2);538+});modified:test/pipe/throw.js+23 added
38 unmodified lines39 const {stdout} = await source;40 assert.equal(stdout, undefined);41 });42 43+// When a previous `.pipe()` failed because of its arguments, the next `.pipe()` has no source.44+// It must reject with that error, without spawning its destination, which would otherwise keep waiting for its `stdin`.45+const testChainedInvalidPipe = async (getPipePromise, firstPipeArguments = [false], expectedMessage = 'an Execa subprocess') => {46+ const source = execa('noop.js', [foobarString]);47+ let isSpawned = false;48+ const verbose = (verboseLine, {type}) => {49+ if (type === 'command') {50+ isSpawned = true;51+ }52+ };53+54+ const pipePromise = getPipePromise(source.pipe(...firstPipeArguments), verbose);55+ await assertPipeError(pipePromise, expectedMessage);56+ assert.equal(isSpawned, false);57+ await source;58+};59+60+test('.pipe("file") after invalid arguments', () => testChainedInvalidPipe((pipePromise, verbose) => pipePromise.pipe('stdin.js', {verbose})));61+test('.pipe`command` after invalid arguments', () => testChainedInvalidPipe((pipePromise, verbose) => pipePromise.pipe({verbose})`stdin.js`));62+test('.pipe.pipe("file") after invalid arguments', () => testChainedInvalidPipe((pipePromise, verbose) => pipePromise.pipe('stdin.js', {verbose}).pipe('stdin.js', {verbose})));63+test('.pipe(false) after invalid arguments', () => testChainedInvalidPipe(pipePromise => pipePromise.pipe(false)));64+test('.pipe("file") after an invalid "to" option', () => testChainedInvalidPipe((pipePromise, verbose) => pipePromise.pipe('stdin.js', {verbose}), ['empty.js', {to: 'fd9'}], 'fd9'));65+66 // The destination subprocess is spawned before the `to` option is validated, so its error must be handled.67 // This runs in another process, since that is where the unhandled rejection crashes it.68 test('Destination subprocess error is not unhandled when the "to" option is invalid', async () => {69 const {stdout} = await execa('pipe-destination-error.js', ['fail.js']);28 unmodified linesmodified:test/transform/generator-error.js+45 added
1 import assert from 'node:assert/strict';2 import {once} from 'node:events';3+import {setTimeout} from 'node:timers/promises';4 import {readFile, rm} from 'node:fs/promises';5 import test from 'node:test';6 import tempfile from 'tempfile';7 import {assertThrows, assertRejects, assertLike} from '../helpers/assert.js';109 unmodified lines117 };118 119 test('Transform errors on stdout do not skip the stderr file', () => testTransformErrorOtherFd(execa));120 test('Transform errors on stdout do not skip the stderr file, sync', () => testTransformErrorOtherFd(execaSync));121+122+// Many signal-aware Node.js APIs reject with an `AbortError`, which must not be mistaken for the stream being aborted123+const testAbortErrorTransform = async abortedLine => {124+ const controller = new AbortController();125+ const {failed, cause} = await execa('noop-fd.js', ['1', 'a\nb\nc'], {126+ async * stdout(line) {127+ if (line === abortedLine) {128+ controller.abort();129+ }130+131+ await setTimeout(0, undefined, {signal: controller.signal});132+ yield line;133+ },134+ reject: false,135+ });136+ assert.equal(failed, true);137+ assert.equal(cause.code, 'ABORT_ERR');138+};139+140+test('Output generators throwing an AbortError make the subprocess fail', () => testAbortErrorTransform('a'));141+test('Output generators throwing an AbortError after some output make the subprocess fail', () => testAbortErrorTransform('b'));142+143+const abortErrorGenerator = async function * (line) {144+ await setTimeout(0, undefined, {signal: AbortSignal.abort()});145+ yield line;146+};147+148+const testAbortErrorConversion = async consumeOutput => {149+ const subprocess = execa('noop-fd.js', ['1', foobarString], {stdout: abortErrorGenerator});150+ const error = await assertRejects(consumeOutput(subprocess));151+ assert.equal(error.cause.code, 'ABORT_ERR');152+ await assertRejects(subprocess);153+};154+155+test('Output generators throwing an AbortError make the subprocess fail, with .readable()', () => testAbortErrorConversion(subprocess => subprocess.readable().toArray()));156+test('Output generators throwing an AbortError make the subprocess fail, with .duplex()', () => testAbortErrorConversion(subprocess => subprocess.duplex().toArray()));157+test('Output generators throwing an AbortError make the subprocess fail, with .iterable()', () => testAbortErrorConversion(subprocess => Array.fromAsync(subprocess.iterable())));158+test('Output generators throwing an AbortError make the subprocess fail, with .readableStream()', () => testAbortErrorConversion(subprocess => Array.fromAsync(subprocess.readableStream())));159+160+test('Input generators throwing an AbortError make the subprocess fail', async () => {161+ const {failed, cause} = await execa('stdin.js', {stdin: abortErrorGenerator, input: foobarString, reject: false});162+ assert.equal(failed, true);163+ assert.equal(cause.code, 'ABORT_ERR');164+});