Refactor `stdio` option (#927)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent d786fcf · Browse files · 24 files·+317 added−293 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
24 files+317 added−293 removed
- other:+317 added−293 removed
Provenance
- Commit
c9cdd2d- Tree
a1d9861- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
d786fcf
24 files changed+317 added−293 removed
modified:lib/pipe/abort.js+2 added-2 removed
3 unmodified lines456788910111212133 unmodified linesexport const unpipeOnAbort = (unpipeSignal, ...args) => unpipeSignal === undefined ? [] : [unpipeOnSignalAbort(unpipeSignal, ...args)];
const unpipeOnSignalAbort = async (unpipeSignal, {sourceStream, mergedStream, stdioStreamsGroups, sourceOptions, startTime}) => {const unpipeOnSignalAbort = async (unpipeSignal, {sourceStream, mergedStream, fileDescriptors, sourceOptions, startTime}) => { await aborted(unpipeSignal, sourceStream); await mergedStream.remove(sourceStream); const error = new Error('Pipe cancelled by `unpipeSignal` option.'); throw createNonCommandError({error, stdioStreamsGroups, sourceOptions, startTime}); throw createNonCommandError({error, fileDescriptors, sourceOptions, startTime});};modified:lib/pipe/setup.js+3 added-3 removed
27 unmodified lines2829303132323334353637383940414142434445464748495050515253546 unmodified lines27 unmodified lines destination, destinationStream, destinationError, unpipeSignal, stdioStreamsGroups, fileDescriptors, startTime,}) => { const subprocessPromises = getSubprocessPromises(sourcePromise, destination); handlePipeArgumentsError({ sourceStream, sourceError, destinationStream, destinationError, stdioStreamsGroups, fileDescriptors, sourceOptions, startTime, }); const maxListenersController = new AbortController(); try { const mergedStream = pipeSubprocessStream(sourceStream, destinationStream, maxListenersController); return await Promise.race([ waitForBothSubprocesses(subprocessPromises), ...unpipeOnAbort(unpipeSignal, {sourceStream, mergedStream, sourceOptions, stdioStreamsGroups, startTime}), ...unpipeOnAbort(unpipeSignal, {sourceStream, mergedStream, sourceOptions, fileDescriptors, startTime}), ]); } finally { maxListenersController.abort(); }6 unmodified linesmodified:lib/pipe/throw.js+4 added-4 removed
4 unmodified lines567899101112131415151617181911 unmodified lines3132333435353637383939404142432 unmodified lines4 unmodified lines sourceStream, sourceError, destinationStream, destinationError, stdioStreamsGroups, fileDescriptors, sourceOptions, startTime,}) => { const error = getPipeArgumentsError({sourceStream, sourceError, destinationStream, destinationError}); if (error !== undefined) { throw createNonCommandError({error, stdioStreamsGroups, sourceOptions, startTime}); throw createNonCommandError({error, fileDescriptors, sourceOptions, startTime}); }};
const getPipeArgumentsError = ({sourceStream, sourceError, destinationStream, destinationError}) => {11 unmodified lines return sourceError; }};
export const createNonCommandError = ({error, stdioStreamsGroups, sourceOptions, startTime}) => makeEarlyError({export const createNonCommandError = ({error, fileDescriptors, sourceOptions, startTime}) => makeEarlyError({ error, command: PIPE_COMMAND_MESSAGE, escapedCommand: PIPE_COMMAND_MESSAGE, stdioStreamsGroups, fileDescriptors, options: sourceOptions, startTime, isSync: false,});2 unmodified linesmodified:lib/pipe/validate.js+13 added-13 removed
12 unmodified lines13 from,14 unpipeSignal,15 } = getDestinationStream(boundOptions, args);16 const {sourceStream, sourceError} = getSourceStream(source, from);17- const {options: sourceOptions, stdioStreamsGroups} = SUBPROCESS_OPTIONS.get(source);17+ const {options: sourceOptions, fileDescriptors} = SUBPROCESS_OPTIONS.get(source);18 return {19 sourcePromise,20 sourceStream,21 sourceOptions,1 unmodified line23 destination,24 destinationStream,25 destinationError,26 unpipeSignal,27- stdioStreamsGroups,27+ fileDescriptors,28 startTime,29 };30 };31 42 unmodified lines74 export const SUBPROCESS_OPTIONS = new WeakMap();75 76 export const getWritable = (destination, to = 'stdin') => {77 const isWritable = true;78- const {options, stdioStreamsGroups} = SUBPROCESS_OPTIONS.get(destination);79- const fdNumber = getFdNumber(stdioStreamsGroups, to, isWritable);78+ const {options, fileDescriptors} = SUBPROCESS_OPTIONS.get(destination);79+ const fdNumber = getFdNumber(fileDescriptors, to, isWritable);80 const destinationStream = destination.stdio[fdNumber];81 82 if (destinationStream === null) {83 throw new TypeError(getInvalidStdioOptionMessage(fdNumber, to, options, isWritable));12 unmodified lines96 };97 98 export const getReadable = (source, from = 'stdout') => {99 const isWritable = false;100- const {options, stdioStreamsGroups} = SUBPROCESS_OPTIONS.get(source);101- const fdNumber = getFdNumber(stdioStreamsGroups, from, isWritable);100+ const {options, fileDescriptors} = SUBPROCESS_OPTIONS.get(source);101+ const fdNumber = getFdNumber(fileDescriptors, from, isWritable);102 const sourceStream = fdNumber === 'all' ? source.all : source.stdio[fdNumber];103 104 if (sourceStream === null || sourceStream === undefined) {105 throw new TypeError(getInvalidStdioOptionMessage(fdNumber, from, options, isWritable));1 unmodified line107 108 return sourceStream;109 };110 111-const getFdNumber = (stdioStreamsGroups, fdName, isWritable) => {111+const getFdNumber = (fileDescriptors, fdName, isWritable) => {112 const fdNumber = parseFdNumber(fdName, isWritable);113- validateFdNumber(fdNumber, fdName, isWritable, stdioStreamsGroups);113+ validateFdNumber(fdNumber, fdName, isWritable, fileDescriptors);114 return fdNumber;115 };116 117 const parseFdNumber = (fdName, isWritable) => {19 unmodified lines137 };138 139 const FD_REGEXP = /^fd(\d+)$/;140 141-const validateFdNumber = (fdNumber, fdName, isWritable, stdioStreamsGroups) => {141+const validateFdNumber = (fdNumber, fdName, isWritable, fileDescriptors) => {142 const usedDescriptor = getUsedDescriptor(fdNumber);143- const stdioStreams = stdioStreamsGroups[usedDescriptor];144- if (stdioStreams === undefined) {143+ const fileDescriptor = fileDescriptors.find(fileDescriptor => fileDescriptor.fdNumber === usedDescriptor);144+ if (fileDescriptor === undefined) {145 throw new TypeError(`"${getOptionName(isWritable)}" must not be ${fdName}. That file descriptor does not exist.146 Please set the "stdio" option to ensure that file descriptor exists.`);147 }148 149- if (stdioStreams[0].direction === 'input' && !isWritable) {149+ if (fileDescriptor.direction === 'input' && !isWritable) {150 throw new TypeError(`"${getOptionName(isWritable)}" must not be ${fdName}. It must be a readable stream, not writable.`);151 }152 153- if (stdioStreams[0].direction !== 'input' && isWritable) {153+ if (fileDescriptor.direction !== 'input' && isWritable) {154 throw new TypeError(`"${getOptionName(isWritable)}" must not be ${fdName}. It must be a writable stream, not readable.`);155 }156 };157 39 unmodified linesmodified:lib/return/early-error.js+7 added-7 removed
123345678910910111213131415161617181920212122232425252627282912 unmodified linesimport {ChildProcess} from 'node:child_process';import {PassThrough, Readable, Writable, Duplex} from 'node:stream';import {cleanupStdioStreams} from '../stdio/async.js';import {cleanupCustomStreams} from '../stdio/async.js';import {makeEarlyError} from './error.js';import {handleResult} from './output.js';
// When the subprocess fails to spawn.// We ensure the returned error is always both a promise and a subprocess.export const handleEarlyError = ({error, command, escapedCommand, stdioStreamsGroups, options, startTime, verboseInfo}) => { cleanupStdioStreams(stdioStreamsGroups);export const handleEarlyError = ({error, command, escapedCommand, fileDescriptors, options, startTime, verboseInfo}) => { cleanupCustomStreams(fileDescriptors);
const subprocess = new ChildProcess(); createDummyStreams(subprocess, stdioStreamsGroups); createDummyStreams(subprocess, fileDescriptors); Object.assign(subprocess, {readable, writable, duplex});
const earlyError = makeEarlyError({error, command, escapedCommand, stdioStreamsGroups, options, startTime, isSync: false}); const earlyError = makeEarlyError({error, command, escapedCommand, fileDescriptors, options, startTime, isSync: false}); const promise = handleDummyPromise(earlyError, verboseInfo, options); return {subprocess, promise};};
const createDummyStreams = (subprocess, stdioStreamsGroups) => {const createDummyStreams = (subprocess, fileDescriptors) => { const stdin = createDummyStream(); const stdout = createDummyStream(); const stderr = createDummyStream(); const extraStdio = Array.from({length: stdioStreamsGroups.length - 3}, createDummyStream); const extraStdio = Array.from({length: fileDescriptors.length - 3}, createDummyStream); const all = createDummyStream(); const stdio = [stdin, stdout, stderr, ...extraStdio]; Object.assign(subprocess, {stdin, stdout, stderr, all, stdio});};12 unmodified linesmodified:lib/return/error.js+2 added-2 removed
32 unmodified lines33 export const makeEarlyError = ({34 error,35 command,36 escapedCommand,37- stdioStreamsGroups,37+ fileDescriptors,38 options,39 startTime,40 isSync,41 }) => makeError({2 unmodified lines44 escapedCommand,45 startTime,46 timedOut: false,47 isCanceled: false,48- stdio: Array.from({length: stdioStreamsGroups.length}),48+ stdio: Array.from({length: fileDescriptors.length}),49 options,50 isSync,51 });52 144 unmodified linesmodified:lib/stdio/async.js+31 added-24 removed
16 unmodified lines17 18 const addPropertiesAsync = {19 input: {20 generator: generatorToDuplexStream,21- fileUrl: ({value}) => ({value: createReadStream(value)}),22- filePath: ({value}) => ({value: createReadStream(value.file)}),23- webStream: ({value}) => ({value: Readable.fromWeb(value)}),24- iterable: ({value}) => ({value: Readable.from(value)}),25- string: ({value}) => ({value: Readable.from(value)}),26- uint8Array: ({value}) => ({value: Readable.from(Buffer.from(value))}),21+ fileUrl: ({value}) => ({stream: createReadStream(value)}),22+ filePath: ({value}) => ({stream: createReadStream(value.file)}),23+ webStream: ({value}) => ({stream: Readable.fromWeb(value)}),24+ nodeStream: ({value}) => ({stream: value}),25+ iterable: ({value}) => ({stream: Readable.from(value)}),26+ string: ({value}) => ({stream: Readable.from(value)}),27+ uint8Array: ({value}) => ({stream: Readable.from(Buffer.from(value))}),28+ native() {},29 },30 output: {31 generator: generatorToDuplexStream,30- fileUrl: ({value}) => ({value: createWriteStream(value)}),31- filePath: ({value}) => ({value: createWriteStream(value.file)}),32- webStream: ({value}) => ({value: Writable.fromWeb(value)}),32+ fileUrl: ({value}) => ({stream: createWriteStream(value)}),33+ filePath: ({value}) => ({stream: createWriteStream(value.file)}),34+ webStream: ({value}) => ({stream: Writable.fromWeb(value)}),35+ nodeStream: ({value}) => ({stream: value}),36 iterable: forbiddenIfAsync,37+ string: forbiddenIfAsync,38 uint8Array: forbiddenIfAsync,39+ native() {},40 },41 };42 43 // Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, after spawning, in async mode44 // When multiple input streams are used, we merge them to ensure the output stream ends only once each input stream has ended40-export const pipeOutputAsync = (subprocess, stdioStreamsGroups, stdioState, controller) => {45+export const pipeOutputAsync = (subprocess, fileDescriptors, stdioState, controller) => {46 stdioState.subprocess = subprocess;47 const inputStreamsGroups = {};48 44- for (const stdioStreams of stdioStreamsGroups) {45- for (const generatorStream of stdioStreams.filter(({type}) => type === 'generator')) {46- pipeGenerator(subprocess, generatorStream);49+ for (const {stdioItems, direction, fdNumber} of fileDescriptors) {50+ for (const {stream} of stdioItems.filter(({type}) => type === 'generator')) {51+ pipeGenerator(subprocess, stream, direction, fdNumber);52 }53 49- for (const nonGeneratorStream of stdioStreams.filter(({type}) => type !== 'generator')) {50- pipeStdioOption(subprocess, nonGeneratorStream, inputStreamsGroups, controller);54+ for (const {stream} of stdioItems.filter(({type}) => type !== 'generator')) {55+ pipeStdioItem({subprocess, stream, direction, fdNumber, inputStreamsGroups, controller});56 }57 }58 59 for (const [fdNumber, inputStreams] of Object.entries(inputStreamsGroups)) {1 unmodified line61 pipeStreams(inputStream, subprocess.stdio[fdNumber]);62 }63 };64 60-const pipeStdioOption = (subprocess, {type, value, direction, fdNumber}, inputStreamsGroups, controller) => {61- if (type === 'native') {65+const pipeStdioItem = ({subprocess, stream, direction, fdNumber, inputStreamsGroups, controller}) => {66+ if (stream === undefined) {67 return;68 }69 65- setStandardStreamMaxListeners(value, controller);70+ setStandardStreamMaxListeners(stream, controller);71 72 if (direction === 'output') {68- pipeStreams(subprocess.stdio[fdNumber], value);73+ pipeStreams(subprocess.stdio[fdNumber], stream);74 } else {70- inputStreamsGroups[fdNumber] = [...(inputStreamsGroups[fdNumber] ?? []), value];75+ inputStreamsGroups[fdNumber] = [...(inputStreamsGroups[fdNumber] ?? []), stream];76 }77 };78 79 // Multiple subprocesses might be piping from/to `process.std*` at the same time.12 unmodified lines92 // The stream error handling is performed by the piping logic above, which cannot be performed before subprocess spawning.93 // If the subprocess spawning fails (e.g. due to an invalid command), the streams need to be manually destroyed.94 // We need to create those streams before subprocess spawning, in case their creation fails, e.g. when passing an invalid generator as argument.95 // Like this, an exception would be thrown, which would prevent spawning a subprocess.91-export const cleanupStdioStreams = stdioStreamsGroups => {92- for (const {value, type} of stdioStreamsGroups.flat()) {93- if (type !== 'native' && !isStandardStream(value)) {94- value.destroy();96+export const cleanupCustomStreams = fileDescriptors => {97+ for (const {stdioItems} of fileDescriptors) {98+ for (const {stream} of stdioItems) {99+ if (stream !== undefined && !isStandardStream(stream)) {100+ stream.destroy();101+ }102 }103 }104 };modified:lib/stdio/direction.js+17 added-20 removed
8 unmodified lines9 // For `stdio[fdNumber]` beyond stdin/stdout/stderr, we need to guess whether the value passed is intended for inputs or outputs.10 // This allows us to know whether to pipe _into_ or _from_ the stream.11 // When `stdio[fdNumber]` is a single value, this guess is fairly straightforward.12 // However, when it is an array instead, we also need to make sure the different values are not incompatible with each other.13-export const addStreamDirection = stdioStreams => {14- const directions = stdioStreams.map(stdioStream => getStreamDirection(stdioStream));13+export const getStreamDirection = (stdioItems, fdNumber, optionName) => {14+ const directions = stdioItems.map(stdioItem => getStdioItemDirection(stdioItem, fdNumber));15 16 if (directions.includes('input') && directions.includes('output')) {17- throw new TypeError(`The \`${stdioStreams[0].optionName}\` option must not be an array of both readable and writable values.`);17+ throw new TypeError(`The \`${optionName}\` option must not be an array of both readable and writable values.`);18 }19 20- const direction = directions.find(Boolean);21- return stdioStreams.map(stdioStream => addDirection(stdioStream, direction));20+ return directions.find(Boolean) ?? DEFAULT_DIRECTION;21 };22 24-const getStreamDirection = ({fdNumber, type, value}) => KNOWN_DIRECTIONS[fdNumber] ?? guessStreamDirection[type](value);23+const getStdioItemDirection = ({type, value}, fdNumber) => KNOWN_DIRECTIONS[fdNumber] ?? guessStreamDirection[type](value);24 25 // `stdin`/`stdout`/`stderr` have a known direction26 const KNOWN_DIRECTIONS = ['input', 'output', 'output'];27 6 unmodified lines34 fileUrl: anyDirection,35 filePath: anyDirection,36 iterable: alwaysInput,37 uint8Array: alwaysInput,39- webStream: stdioOption => isWritableStream(stdioOption) ? 'output' : 'input',40- nodeStream(stdioOption) {41- const standardStreamDirection = getStandardStreamDirection(stdioOption);38+ webStream: value => isWritableStream(value) ? 'output' : 'input',39+ nodeStream(value) {40+ const standardStreamDirection = getStandardStreamDirection(value);41 if (standardStreamDirection !== undefined) {42 return standardStreamDirection;43 }44 46- if (!isNodeReadableStream(stdioOption, {checkOpen: false})) {45+ if (!isNodeReadableStream(value, {checkOpen: false})) {46 return 'output';47 }48 50- return isNodeWritableStream(stdioOption, {checkOpen: false}) ? undefined : 'input';49+ return isNodeWritableStream(value, {checkOpen: false}) ? undefined : 'input';50 },52- native(stdioOption) {53- const standardStreamDirection = getStandardStreamDirection(stdioOption);51+ native(value) {52+ const standardStreamDirection = getStandardStreamDirection(value);53 if (standardStreamDirection !== undefined) {54 return standardStreamDirection;55 }56 58- if (isNodeStream(stdioOption, {checkOpen: false})) {59- return guessStreamDirection.nodeStream(stdioOption);57+ if (isNodeStream(value, {checkOpen: false})) {58+ return guessStreamDirection.nodeStream(value);59 }60 },61 };62 64-const getStandardStreamDirection = stdioOption => {65- if ([0, process.stdin].includes(stdioOption)) {63+const getStandardStreamDirection = value => {64+ if ([0, process.stdin].includes(value)) {65 return 'input';66 }67 69- if ([1, 2, process.stdout, process.stderr].includes(stdioOption)) {68+ if ([1, 2, process.stdout, process.stderr].includes(value)) {69 return 'output';70 }71 };72 74-const addDirection = (stdioStream, direction = DEFAULT_DIRECTION) => ({...stdioStream, direction});75-73 // When ambiguous, we initially keep the direction as `undefined`.74 // This allows arrays of `stdio` values to resolve the ambiguity.75 // For example, `stdio[3]: DuplexStream` is ambiguous, but `stdio[3]: [DuplexStream, WritableStream]` is not.76 // When the ambiguity remains, we default to `output` since it is the most common use case for additional file descriptors.1 unmodified linemodified:lib/stdio/encoding-final.js+18 added-24 removed
1 import {StringDecoder} from 'node:string_decoder';2 import {isSimpleEncoding} from '../encoding.js';3-import {willPipeStreams} from './forward.js';3 4 // Apply the `encoding` option using an implicit generator.5 // This encodes the final output of `stdout`/`stderr`.7-export const handleStreamsEncoding = (stdioStreams, {encoding}, isSync) => {8- const newStdioStreams = stdioStreams.map(stdioStream => ({...stdioStream, encoding}));9- if (!shouldEncodeOutput(newStdioStreams, encoding, isSync)) {10- return newStdioStreams;6+export const handleStreamsEncoding = ({stdioItems, options: {encoding}, isSync, direction, optionName}) => {7+ if (!shouldEncodeOutput({stdioItems, encoding, isSync, direction})) {8+ return [];9 }10 13- const lastObjectStdioStream = newStdioStreams.findLast(({type, value}) => type === 'generator' && value.objectMode !== undefined);14- const writableObjectMode = lastObjectStdioStream !== undefined && lastObjectStdioStream.value.objectMode;15- if (writableObjectMode) {16- return newStdioStreams;17- }18-11 const stringDecoder = new StringDecoder(encoding);20- return [21- ...newStdioStreams,22- {23- ...newStdioStreams[0],24- type: 'generator',25- value: {26- transform: encodingStringGenerator.bind(undefined, stringDecoder),27- final: encodingStringFinal.bind(undefined, stringDecoder),28- binary: true,12+ return [{13+ type: 'generator',14+ value: {15+ transform: encodingStringGenerator.bind(undefined, stringDecoder),16+ final: encodingStringFinal.bind(undefined, stringDecoder),17+ binary: true,29- },18 },19+ optionName,31- ];20+ }];21 };22 34-const shouldEncodeOutput = (stdioStreams, encoding, isSync) => stdioStreams[0].direction === 'output'23+const shouldEncodeOutput = ({stdioItems, encoding, isSync, direction}) => direction === 'output'24 && !isSimpleEncoding(encoding)25 && !isSync37- && willPipeStreams(stdioStreams);26+ && !isWritableObjectMode(stdioItems);27 28+const isWritableObjectMode = stdioItems => {29+ const lastObjectStdioItem = stdioItems.findLast(({type, value}) => type === 'generator' && value.objectMode !== undefined);30+ return lastObjectStdioItem !== undefined && lastObjectStdioItem.value.objectMode;31+};32+33 const encodingStringGenerator = function * (stringDecoder, chunk) {34 yield stringDecoder.write(chunk);35 };36 6 unmodified linesmodified:lib/stdio/forward.js+9 added-11 removed
1-// When the `std*: Iterable | WebStream | URL | filePath`, `input` or `inputFile` option is used, we pipe to `subprocess.std*`.2-// When the `std*: Array` option is used, we emulate some of the native values ('inherit', Node.js stream and file descriptor integer). To do so, we also need to pipe to `subprocess.std*`.3-// Therefore the `std*` options must be either `pipe` or `overlapped`. Other values do not set `subprocess.std*`.4-export const forwardStdio = stdioStreamsGroups => stdioStreamsGroups.map(stdioStreams => forwardStdioItem(stdioStreams));5-1 // Whether `subprocess.std*` will be set7-export const willPipeStreams = stdioStreams => PIPED_STDIO_VALUES.has(forwardStdioItem(stdioStreams));2+export const willPipeFileDescriptor = stdioItems => PIPED_STDIO_VALUES.has(forwardStdio(stdioItems));3 4 export const PIPED_STDIO_VALUES = new Set(['pipe', 'overlapped', undefined, null]);5 6+// When the `std*: Iterable | WebStream | URL | filePath`, `input` or `inputFile` option is used, we pipe to `subprocess.std*`.7+// When the `std*: Array` option is used, we emulate some of the native values ('inherit', Node.js stream and file descriptor integer). To do so, we also need to pipe to `subprocess.std*`.8+// Therefore the `std*` options must be either `pipe` or `overlapped`. Other values do not set `subprocess.std*`.11-const forwardStdioItem = stdioStreams => {12- if (stdioStreams.length > 1) {13- return stdioStreams.some(({value}) => value === 'overlapped') ? 'overlapped' : 'pipe';9+export const forwardStdio = stdioItems => {10+ if (stdioItems.length > 1) {11+ return stdioItems.some(({value}) => value === 'overlapped') ? 'overlapped' : 'pipe';12 }13 16- const [stdioStream] = stdioStreams;17- return stdioStream.type !== 'native' && stdioStream.value !== 'overlapped' ? 'pipe' : stdioStream.value;14+ const [{type, value}] = stdioItems;15+ return type === 'native' ? value : 'pipe';16 };modified:lib/stdio/generator.js+17 added-17 removed
4 unmodified lines5 import {pipeStreams} from './pipeline.js';6 import {isGeneratorOptions, isAsyncGenerator} from './type.js';7 import {getValidateTransformReturn} from './validate.js';8 9-export const normalizeGenerators = (stdioStreams, options) => {10- const nonGenerators = stdioStreams.filter(({type}) => type !== 'generator');11- const generators = stdioStreams.filter(({type}) => type === 'generator');9+export const normalizeGenerators = (stdioItems, direction, {encoding}) => {10+ const nonGenerators = stdioItems.filter(({type}) => type !== 'generator');11+ const generators = stdioItems.filter(({type}) => type === 'generator');12 13 const newGenerators = Array.from({length: generators.length});14 15- for (const [index, stdioStream] of Object.entries(generators)) {16- newGenerators[index] = normalizeGenerator(stdioStream, Number(index), newGenerators, options);15+ for (const [index, stdioItem] of Object.entries(generators)) {16+ newGenerators[index] = normalizeGenerator({stdioItem, index: Number(index), newGenerators, direction, encoding});17 }18 19- return [...nonGenerators, ...sortGenerators(newGenerators)];19+ return [...nonGenerators, ...sortGenerators(newGenerators, direction)];20 };21 22-const normalizeGenerator = ({value, ...stdioStream}, index, newGenerators, {encoding}) => {22+const normalizeGenerator = ({stdioItem, stdioItem: {value}, index, newGenerators, direction, encoding}) => {23 const {24 transform,25 final,26 binary: binaryOption = false,27 preserveNewlines = false,28 objectMode,29 } = isGeneratorOptions(value) ? value : {transform: value};30 const binary = binaryOption || isBinaryEncoding(encoding);31- const objectModes = stdioStream.direction === 'output'31+ const objectModes = direction === 'output'32 ? getOutputObjectModes(objectMode, index, newGenerators)33 : getInputObjectModes(objectMode, index, newGenerators);34- return {...stdioStream, value: {transform, final, binary, preserveNewlines, ...objectModes}};34+ return {...stdioItem, value: {transform, final, binary, preserveNewlines, ...objectModes}};35 };36 37 /*38 `objectMode` determines the return value's type, i.e. the `readableObjectMode`.17 unmodified lines56 const readableObjectMode = index !== newGenerators.length - 1 && (objectMode ?? writableObjectMode);57 return {writableObjectMode, readableObjectMode};58 };59 60-const sortGenerators = newGenerators => newGenerators[0]?.direction === 'input' ? newGenerators.reverse() : newGenerators;60+const sortGenerators = (newGenerators, direction) => direction === 'input' ? newGenerators.reverse() : newGenerators;61 62 /*63 Generators can be used to transform/filter standard streams.64 24 unmodified lines89 getAppendNewlineGenerator({binary, preserveNewlines, readableObjectMode, state}),90 ].filter(Boolean);91 const transformAsync = isAsyncGenerator(transform);92 const finalAsync = isAsyncGenerator(final);93- const duplexStream = generatorsToTransform(generators, {transformAsync, finalAsync, writableObjectMode, readableObjectMode});94- return {value: duplexStream};93+ const stream = generatorsToTransform(generators, {transformAsync, finalAsync, writableObjectMode, readableObjectMode});94+ return {stream};95 };96 97 // `subprocess.stdin|stdout|stderr|stdio` is directly mutated.98-export const pipeGenerator = (subprocess, {value, direction, fdNumber}) => {98+export const pipeGenerator = (subprocess, stream, direction, fdNumber) => {99 if (direction === 'output') {100- pipeStreams(subprocess.stdio[fdNumber], value);100+ pipeStreams(subprocess.stdio[fdNumber], stream);101 } else {102- pipeStreams(value, subprocess.stdio[fdNumber]);102+ pipeStreams(stream, subprocess.stdio[fdNumber]);103 }104 105 const streamProperty = SUBPROCESS_STREAM_PROPERTIES[fdNumber];106 if (streamProperty !== undefined) {107- subprocess[streamProperty] = value;107+ subprocess[streamProperty] = stream;108 }109 110- subprocess.stdio[fdNumber] = value;110+ subprocess.stdio[fdNumber] = stream;111 };112 113 const SUBPROCESS_STREAM_PROPERTIES = ['stdin', 'stdout', 'stderr'];modified:lib/stdio/handle.js+65 added-39 removed
1 import {handleStreamsVerbose} from '../verbose/output.js';2-import {getStdioOptionType, isRegularUrl, isUnknownStdioString} from './type.js';3-import {addStreamDirection} from './direction.js';2+import {getStdioItemType, isRegularUrl, isUnknownStdioString} from './type.js';3+import {getStreamDirection} from './direction.js';4 import {normalizeStdio} from './option.js';5 import {handleNativeStream} from './native.js';6 import {handleInputOptions} from './input.js';7 import {handleStreamsLines} from './lines.js';8 import {handleStreamsEncoding} from './encoding-final.js';9 import {normalizeGenerators} from './generator.js';10-import {forwardStdio} from './forward.js';10+import {forwardStdio, willPipeFileDescriptor} from './forward.js';11 12 // Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in async/sync mode13 export const handleInput = (addProperties, options, verboseInfo, isSync) => {14 const stdioState = {};15 const stdio = normalizeStdio(options);16- const [stdinStreams, ...otherStreamsGroups] = stdio.map((stdioOption, fdNumber) => getStdioStreams(stdioOption, fdNumber));17- const stdioStreamsGroups = [[...stdinStreams, ...handleInputOptions(options)], ...otherStreamsGroups]18- .map(stdioStreams => validateStreams(stdioStreams))19- .map(stdioStreams => addStreamDirection(stdioStreams))20- .map(stdioStreams => handleStreamsVerbose({stdioStreams, options, isSync, stdioState, verboseInfo}))21- .map(stdioStreams => handleStreamsLines(stdioStreams, options, isSync))22- .map(stdioStreams => handleStreamsEncoding(stdioStreams, options, isSync))23- .map(stdioStreams => normalizeGenerators(stdioStreams, options))24- .map(stdioStreams => addStreamsProperties(stdioStreams, addProperties));25- options.stdio = forwardStdio(stdioStreamsGroups);26- return {stdioStreamsGroups, stdioState};16+ const fileDescriptors = stdio.map((stdioOption, fdNumber) =>17+ getFileDescriptor({stdioOption, fdNumber, addProperties, options, isSync, stdioState, verboseInfo}));18+ options.stdio = fileDescriptors.map(({stdioItems}) => forwardStdio(stdioItems));19+ return {fileDescriptors, stdioState};20 };21 22 // We make sure passing an array with a single item behaves the same as passing that item without an array.23 // This is what users would expect.24 // For example, `stdout: ['ignore']` behaves the same as `stdout: 'ignore'`.32-const getStdioStreams = (stdioOption, fdNumber) => {25+const getFileDescriptor = ({stdioOption, fdNumber, addProperties, options, isSync, stdioState, verboseInfo}) => {26 const optionName = getOptionName(fdNumber);34- const stdioOptions = Array.isArray(stdioOption) ? stdioOption : [stdioOption];35- const rawStdioStreams = stdioOptions.map(stdioOption => getStdioStream(stdioOption, optionName, fdNumber));36- const stdioStreams = filterDuplicates(rawStdioStreams);37- const isStdioArray = stdioStreams.length > 1;38- validateStdioArray(stdioStreams, isStdioArray, optionName);39- return stdioStreams.map(stdioStream => handleNativeStream(stdioStream, isStdioArray));27+ const stdioItems = initializeStdioItems(stdioOption, fdNumber, options, optionName);28+ const direction = getStreamDirection(stdioItems, fdNumber, optionName);29+ const normalizedStdioItems = normalizeStdioItems({stdioItems, fdNumber, optionName, addProperties, options, isSync, direction, stdioState, verboseInfo});30+ return {fdNumber, direction, stdioItems: normalizedStdioItems};31 };32 33 const getOptionName = fdNumber => KNOWN_OPTION_NAMES[fdNumber] ?? `stdio[${fdNumber}]`;34 const KNOWN_OPTION_NAMES = ['stdin', 'stdout', 'stderr'];35 45-const getStdioStream = (stdioOption, optionName, fdNumber) => {46- const type = getStdioOptionType(stdioOption, optionName);47- return {type, value: stdioOption, optionName, fdNumber};36+const initializeStdioItems = (stdioOption, fdNumber, options, optionName) => {37+ const values = Array.isArray(stdioOption) ? stdioOption : [stdioOption];38+ const initialStdioItems = [39+ ...values.map(value => initializeStdioItem(value, optionName)),40+ ...handleInputOptions(options, fdNumber),41+ ];42+43+ const stdioItems = filterDuplicates(initialStdioItems);44+ const isStdioArray = stdioItems.length > 1;45+ validateStdioArray(stdioItems, isStdioArray, optionName);46+ validateStreams(stdioItems);47+ return stdioItems.map(stdioItem => handleNativeStream(stdioItem, isStdioArray, fdNumber));48 };49 50-const filterDuplicates = stdioStreams => stdioStreams.filter((stdioStreamOne, indexOne) =>51- stdioStreams.every((stdioStreamTwo, indexTwo) =>52- stdioStreamOne.value !== stdioStreamTwo.value || indexOne >= indexTwo || stdioStreamOne.type === 'generator'));50+const initializeStdioItem = (value, optionName) => ({51+ type: getStdioItemType(value, optionName),52+ value,53+ optionName,54+});55 56+const filterDuplicates = stdioItems => stdioItems.filter((stdioItemOne, indexOne) =>57+ stdioItems.every((stdioItemTwo, indexTwo) =>58+ stdioItemOne.value !== stdioItemTwo.value || indexOne >= indexTwo || stdioItemOne.type === 'generator'));59+54-const validateStdioArray = (stdioStreams, isStdioArray, optionName) => {55- if (stdioStreams.length === 0) {60+const validateStdioArray = (stdioItems, isStdioArray, optionName) => {61+ if (stdioItems.length === 0) {62 throw new TypeError(`The \`${optionName}\` option must not be an empty array.`);63 }64 65 if (!isStdioArray) {66 return;67 }68 63- for (const {value, optionName} of stdioStreams) {69+ for (const {value, optionName} of stdioItems) {70 if (INVALID_STDIO_ARRAY_OPTIONS.has(value)) {71 throw new Error(`The \`${optionName}\` option must not include \`${value}\`.`);72 }73 }2 unmodified lines76 // Using those `stdio` values together with others for the same stream does not make sense, so we make it fail.77 // However, we do allow it if the array has a single item.78 const INVALID_STDIO_ARRAY_OPTIONS = new Set(['ignore', 'ipc']);79 74-const validateStreams = stdioStreams => {75- for (const stdioStream of stdioStreams) {76- validateFileStdio(stdioStream);80+const validateStreams = stdioItems => {81+ for (const stdioItem of stdioItems) {82+ validateFileStdio(stdioItem);83 }78-79- return stdioStreams;84 };85 86 const validateFileStdio = ({type, value, optionName}) => {87 if (isRegularUrl(value)) {5 unmodified lines93 throw new TypeError(`The \`${optionName}: { file: '...' }\` option must be used instead of \`${optionName}: '...'\`.`);94 }95 };96 97+const normalizeStdioItems = ({stdioItems, fdNumber, optionName, addProperties, options, isSync, direction, stdioState, verboseInfo}) => {98+ const allStdioItems = addInternalStdioItems({stdioItems, fdNumber, optionName, options, isSync, direction, stdioState, verboseInfo});99+ const normalizedStdioItems = normalizeGenerators(allStdioItems, direction, options);100+ return normalizedStdioItems.map(stdioItem => addStreamProperties(stdioItem, addProperties, direction));101+};102+103+const addInternalStdioItems = ({stdioItems, fdNumber, optionName, options, isSync, direction, stdioState, verboseInfo}) => {104+ if (!willPipeFileDescriptor(stdioItems)) {105+ return stdioItems;106+ }107+108+ const newStdioItems = [109+ ...stdioItems,110+ ...handleStreamsVerbose({stdioItems, options, isSync, stdioState, verboseInfo, fdNumber, optionName}),111+ ...handleStreamsLines({options, isSync, direction, optionName}),112+ ];113+ return [114+ ...newStdioItems,115+ ...handleStreamsEncoding({stdioItems: newStdioItems, options, isSync, direction, optionName}),116+ ];117+};118+119 // Some `stdio` values require Execa to create streams.120 // For example, file paths create file read/write streams.121 // Those transformations are specified in `addProperties`, which is both direction-specific and type-specific.96-const addStreamsProperties = (stdioStreams, addProperties) => stdioStreams.map(stdioStream => ({97- ...stdioStream,98- ...addProperties[stdioStream.direction][stdioStream.type]?.(stdioStream),99-}));122+const addStreamProperties = (stdioItem, addProperties, direction) => ({123+ ...stdioItem,124+ ...addProperties[direction][stdioItem.type](stdioItem),125+});modified:lib/stdio/input.js+10 added-10 removed
1 unmodified line2 import {isUint8Array} from '../encoding.js';3 import {isUrl, isFilePathString} from './type.js';4 5 // Append the `stdin` option with the `input` and `inputFile` options6-export const handleInputOptions = ({input, inputFile}) => [7- handleInputOption(input),8- handleInputFileOption(inputFile),9-].filter(Boolean);6+export const handleInputOptions = ({input, inputFile}, fdNumber) => fdNumber === 07+ ? [8+ ...handleInputOption(input),9+ ...handleInputFileOption(inputFile),10+ ]11+ : [];12 11-const handleInputOption = input => input === undefined ? undefined : {13+const handleInputOption = input => input === undefined ? [] : [{14 type: getInputType(input),15 value: input,16 optionName: 'input',15- fdNumber: 0,16-};17+}];18 19 const getInputType = input => {20 if (isReadableStream(input, {checkOpen: false})) {21 return 'nodeStream';9 unmodified lines31 32 throw new Error('The `input` option must be a string, a Uint8Array or a Node.js Readable stream.');33 };34 34-const handleInputFileOption = inputFile => inputFile === undefined ? undefined : {35+const handleInputFileOption = inputFile => inputFile === undefined ? [] : [{36 ...getInputFileType(inputFile),37 optionName: 'inputFile',37- fdNumber: 0,38-};38+}];39 40 const getInputFileType = inputFile => {41 if (isUrl(inputFile)) {42 return {type: 'fileUrl', value: inputFile};8 unmodified linesmodified:lib/stdio/lines.js+9 added-14 removed
1 import {isBinaryEncoding} from '../encoding.js';2-import {willPipeStreams} from './forward.js';2 3 // Split chunks line-wise for streams exposed to users like `subprocess.stdout`.4 // Appending a noop transform in object mode is enough to do this, since every non-binary transform iterates line-wise.6-export const handleStreamsLines = (stdioStreams, {lines, encoding, stripFinalNewline}, isSync) => shouldSplitLines({stdioStreams, lines, encoding, isSync})7- ? [8- ...stdioStreams,9- {10- ...stdioStreams[0],11- type: 'generator',12- value: {transform: linesEndGenerator, objectMode: true, preserveNewlines: !stripFinalNewline},13- },14- ]15- : stdioStreams;5+export const handleStreamsLines = ({options: {lines, encoding, stripFinalNewline}, isSync, direction, optionName}) => shouldSplitLines({lines, encoding, isSync, direction})6+ ? [{7+ type: 'generator',8+ value: {transform: linesEndGenerator, objectMode: true, preserveNewlines: !stripFinalNewline},9+ optionName,10+ }]11+ : [];12 17-const shouldSplitLines = ({stdioStreams, lines, encoding, isSync}) => stdioStreams[0].direction === 'output'13+const shouldSplitLines = ({lines, encoding, isSync, direction}) => direction === 'output'14 && lines15 && !isBinaryEncoding(encoding)20- && !isSync21- && willPipeStreams(stdioStreams);16+ && !isSync;17 18 const linesEndGenerator = function * (chunk) {19 yield chunk;20 };modified:lib/stdio/native.js+7 added-7 removed
6 unmodified lines7 // - Node.js streams are marked as `type: nodeStream`8 // - 'inherit' becomes `process.stdin|stdout|stderr`9 // - any file descriptor integer becomes `process.stdio[fdNumber]`10 // All of the above transformations tell Execa to perform manual piping.11-export const handleNativeStream = (stdioStream, isStdioArray) => {12- const {type, value, fdNumber, optionName} = stdioStream;11+export const handleNativeStream = (stdioItem, isStdioArray, fdNumber) => {12+ const {type, value, optionName} = stdioItem;13 14 if (!isStdioArray || type !== 'native') {15- return stdioStream;15+ return stdioItem;16 }17 18 if (value === 'inherit') {19- return {...stdioStream, type: 'nodeStream', value: getStandardStream(fdNumber, value, optionName)};19+ return {type: 'nodeStream', value: getStandardStream(fdNumber, value, optionName), optionName};20 }21 22 if (typeof value === 'number') {23- return {...stdioStream, type: 'nodeStream', value: getStandardStream(value, value, optionName)};23+ return {type: 'nodeStream', value: getStandardStream(value, value, optionName), optionName};24 }25 26 if (isNodeStream(value, {checkOpen: false})) {27- return {...stdioStream, type: 'nodeStream'};27+ return {type: 'nodeStream', value, optionName};28 }29 30- return stdioStream;30+ return stdioItem;31 };32 33 // Node.js does not allow to easily retrieve file descriptors beyond stdin/stdout/stderr as streams.34 // - `fs.createReadStream()`/`fs.createWriteStream()` with the `fd` option do not work with character devices that use blocking reads/writes (such as interactive TTYs).12 unmodified linesmodified:lib/stdio/sync.js+29 added-19 removed
3 unmodified lines4 import {TYPE_TO_MESSAGE} from './type.js';5 6 // Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in sync mode7 export const handleInputSync = (options, verboseInfo) => {8- const {stdioStreamsGroups} = handleInput(addPropertiesSync, options, verboseInfo, true);9- addInputOptionSync(stdioStreamsGroups, options);10- return stdioStreamsGroups;8+ const {fileDescriptors} = handleInput(addPropertiesSync, options, verboseInfo, true);9+ addInputOptionSync(fileDescriptors, options);10+ return fileDescriptors;11 };12 13 const forbiddenIfSync = ({type, optionName}) => {14 throw new TypeError(`The \`${optionName}\` option cannot be ${TYPE_TO_MESSAGE[type]} in sync mode.`);1 unmodified line16 17 const addPropertiesSync = {18 input: {19 generator: forbiddenIfSync,20- fileUrl: ({value}) => ({value: bufferToUint8Array(readFileSync(value)), type: 'uint8Array'}),21- filePath: ({value}) => ({value: bufferToUint8Array(readFileSync(value.file)), type: 'uint8Array'}),20+ fileUrl: ({value}) => ({contents: bufferToUint8Array(readFileSync(value))}),21+ filePath: ({value: {file}}) => ({contents: bufferToUint8Array(readFileSync(file))}),22 webStream: forbiddenIfSync,23 nodeStream: forbiddenIfSync,24 iterable: forbiddenIfSync,25+ string: ({value}) => ({contents: value}),26+ uint8Array: ({value}) => ({contents: value}),27+ native() {},28 },29 output: {30 generator: forbiddenIfSync,28- filePath: ({value}) => ({value: value.file}),31+ fileUrl: ({value}) => ({path: value}),32+ filePath: ({value: {file}}) => ({path: file}),33 webStream: forbiddenIfSync,34 nodeStream: forbiddenIfSync,35 iterable: forbiddenIfSync,36+ string: forbiddenIfSync,37 uint8Array: forbiddenIfSync,38+ native() {},39 },40 };41 36-const addInputOptionSync = (stdioStreamsGroups, options) => {37- const inputs = stdioStreamsGroups.flat().filter(({direction, type}) => direction === 'input' && (type === 'string' || type === 'uint8Array'));38- if (inputs.length === 0) {42+const addInputOptionSync = (fileDescriptors, options) => {43+ const allContents = fileDescriptors44+ .filter(({direction}) => direction === 'input')45+ .flatMap(({stdioItems}) => stdioItems)46+ .map(({contents}) => contents)47+ .filter(contents => contents !== undefined);48+ if (allContents.length === 0) {49 return;50 }51 42- options.input = inputs.length === 143- ? inputs[0].value44- : inputs.map(stdioStream => serializeInput(stdioStream)).join('');52+ options.input = allContents.length === 153+ ? allContents[0]54+ : allContents.map(contents => serializeContents(contents)).join('');55 };56 47-const serializeInput = ({type, value}) => type === 'string' ? value : uint8ArrayToString(value);57+const serializeContents = contents => typeof contents === 'string' ? contents : uint8ArrayToString(contents);58 59 // Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, after spawning, in sync mode50-export const pipeOutputSync = (stdioStreamsGroups, {output}) => {60+export const pipeOutputSync = (fileDescriptors, {output}) => {61 if (output === null) {62 return;63 }64 55- for (const stdioStreams of stdioStreamsGroups) {56- for (const stdioStream of stdioStreams) {57- pipeStdioOptionSync(output[stdioStream.fdNumber], stdioStream);65+ for (const {stdioItems, fdNumber, direction} of fileDescriptors) {66+ for (const {type, path} of stdioItems) {67+ pipeStdioItemSync(output[fdNumber], type, path, direction);68 }69 }70 };71 62-const pipeStdioOptionSync = (result, {type, value, direction}) => {72+const pipeStdioItemSync = (result, type, path, direction) => {73 if (result === null || direction === 'input') {74 return;75 }76 77 if (type === 'fileUrl' || type === 'filePath') {68- writeFileSync(value, result);78+ writeFileSync(path, result);79 }80 };modified:lib/stdio/type.js+31 added-29 removed
1 import {isStream as isNodeStream} from 'is-stream';2 import {isUint8Array} from '../encoding.js';3 4 // The `stdin`/`stdout`/`stderr` option can be of many types. This detects it.5-export const getStdioOptionType = (stdioOption, optionName) => {6- if (isGenerator(stdioOption)) {5+export const getStdioItemType = (value, optionName) => {6+ if (isGenerator(value)) {7 return 'generator';8 }9 10- if (isUrl(stdioOption)) {10+ if (isUrl(value)) {11 return 'fileUrl';12 }13 14- if (isFilePathObject(stdioOption)) {14+ if (isFilePathObject(value)) {15 return 'filePath';16 }17 18- if (isWebStream(stdioOption)) {18+ if (isWebStream(value)) {19 return 'webStream';20 }21 22- if (isNodeStream(stdioOption, {checkOpen: false})) {22+ if (isNodeStream(value, {checkOpen: false})) {23 return 'native';24 }25 26- if (isUint8Array(stdioOption)) {26+ if (isUint8Array(value)) {27 return 'uint8Array';28 }29 30- if (isIterableObject(stdioOption)) {30+ if (isIterableObject(value)) {31 return 'iterable';32 }33 34- if (isGeneratorOptions(stdioOption)) {35- return getGeneratorObjectType(stdioOption, optionName);34+ if (isGeneratorOptions(value)) {35+ return getGeneratorObjectType(value, optionName);36 }37 38 return 'native';39 };18 unmodified lines58 throw new TypeError(`The \`${optionName}\` option must use a boolean.`);59 }60 };61 62-const isGenerator = stdioOption => isAsyncGenerator(stdioOption) || isSyncGenerator(stdioOption);63-export const isAsyncGenerator = stdioOption => Object.prototype.toString.call(stdioOption) === '[object AsyncGeneratorFunction]';64-const isSyncGenerator = stdioOption => Object.prototype.toString.call(stdioOption) === '[object GeneratorFunction]';65-export const isGeneratorOptions = stdioOption => typeof stdioOption === 'object'66- && stdioOption !== null67- && (stdioOption.transform !== undefined || stdioOption.final !== undefined);62+const isGenerator = value => isAsyncGenerator(value) || isSyncGenerator(value);63+export const isAsyncGenerator = value => Object.prototype.toString.call(value) === '[object AsyncGeneratorFunction]';64+const isSyncGenerator = value => Object.prototype.toString.call(value) === '[object GeneratorFunction]';65+export const isGeneratorOptions = value => typeof value === 'object'66+ && value !== null67+ && (value.transform !== undefined || value.final !== undefined);68 69-export const isUrl = stdioOption => Object.prototype.toString.call(stdioOption) === '[object URL]';70-export const isRegularUrl = stdioOption => isUrl(stdioOption) && stdioOption.protocol !== 'file:';69+export const isUrl = value => Object.prototype.toString.call(value) === '[object URL]';70+export const isRegularUrl = value => isUrl(value) && value.protocol !== 'file:';71 72-const isFilePathObject = stdioOption => typeof stdioOption === 'object'73- && stdioOption !== null74- && Object.keys(stdioOption).length === 175- && isFilePathString(stdioOption.file);72+const isFilePathObject = value => typeof value === 'object'73+ && value !== null74+ && Object.keys(value).length === 175+ && isFilePathString(value.file);76 export const isFilePathString = file => typeof file === 'string';77 78-export const isUnknownStdioString = (type, stdioOption) => type === 'native' && typeof stdioOption === 'string' && !KNOWN_STDIO_STRINGS.has(stdioOption);78+export const isUnknownStdioString = (type, value) => type === 'native'79+ && typeof value === 'string'80+ && !KNOWN_STDIO_STRINGS.has(value);81 const KNOWN_STDIO_STRINGS = new Set(['ipc', 'ignore', 'inherit', 'overlapped', 'pipe']);82 81-const isReadableStream = stdioOption => Object.prototype.toString.call(stdioOption) === '[object ReadableStream]';82-export const isWritableStream = stdioOption => Object.prototype.toString.call(stdioOption) === '[object WritableStream]';83-const isWebStream = stdioOption => isReadableStream(stdioOption) || isWritableStream(stdioOption);83+const isReadableStream = value => Object.prototype.toString.call(value) === '[object ReadableStream]';84+export const isWritableStream = value => Object.prototype.toString.call(value) === '[object WritableStream]';85+const isWebStream = value => isReadableStream(value) || isWritableStream(value);86 85-const isIterableObject = stdioOption => typeof stdioOption === 'object'86- && stdioOption !== null87- && (typeof stdioOption[Symbol.asyncIterator] === 'function' || typeof stdioOption[Symbol.iterator] === 'function');87+const isIterableObject = value => typeof value === 'object'88+ && value !== null89+ && (typeof value[Symbol.asyncIterator] === 'function' || typeof value[Symbol.iterator] === 'function');90 91 // Convert types to human-friendly strings for error messages92 export const TYPE_TO_MESSAGE = {93 generator: 'a generator',9 unmodified linesmodified:lib/stream/all.js+2 added-1 removed
22 unmodified lines23 // - `getStreamAsArray()` for the chunks in objectMode, to return as an array without changing each chunk24 // - `getStreamAsArrayBuffer()` or `getStream()` for the chunks not in objectMode, to convert them from Buffers to string or Uint8Array25 // We do this by emulating the Buffer -> string|Uint8Array conversion performed by `get-stream` with our own, which is identical.26 const getAllStream = ({all, stdout, stderr}, encoding) => all && stdout && stderr && stdout.readableObjectMode !== stderr.readableObjectMode27- ? all.pipe(generatorToDuplexStream(getAllStreamTransform(encoding)).value)27+ ? all.pipe(generatorToDuplexStream(getAllStreamTransform(encoding)).stream)28 : all;29 30 const getAllStreamTransform = encoding => ({31 value: {3 unmodified lines35 readableObjectMode: true,36 preserveNewlines: true,37 },38 forceEncoding: true,39+ optionName: 'all',40 });modified:lib/stream/resolve.js+8 added-8 removed
1 import {once} from 'node:events';2-import {isStream} from 'is-stream';2+import {isStream as isNodeStream} from 'is-stream';3 import {waitForSuccessfulExit} from '../exit/code.js';4 import {errorSignal} from '../exit/kill.js';5 import {throwOnTimeout} from '../exit/timeout.js';6 import {isStandardStream} from '../utils.js';6 unmodified lines13 export const getSubprocessResult = async ({14 subprocess,15 options: {encoding, buffer, maxBuffer, timeoutDuration: timeout},16 context,17- stdioStreamsGroups,17+ fileDescriptors,18 originalStreams,19 controller,20 }) => {21 const exitPromise = waitForExit(subprocess);22- const streamInfo = {originalStreams, stdioStreamsGroups, subprocess, exitPromise, propagating: false};22+ const streamInfo = {originalStreams, fileDescriptors, subprocess, exitPromise, propagating: false};23 24 const stdioPromises = waitForSubprocessStreams({subprocess, encoding, buffer, maxBuffer, streamInfo});25 const allPromise = waitForAllStream({subprocess, encoding, buffer, maxBuffer, streamInfo});26 const originalPromises = waitForOriginalStreams(originalStreams, subprocess, streamInfo);27- const customStreamsEndPromises = waitForCustomStreamsEnd(stdioStreamsGroups, streamInfo);27+ const customStreamsEndPromises = waitForCustomStreamsEnd(fileDescriptors, streamInfo);28 29 try {30 return await Promise.race([31 Promise.all([33 unmodified lines65 66 // Some `stdin`/`stdout`/`stderr` options create a stream, e.g. when passing a file path.67 // The `.pipe()` method automatically ends that stream when `subprocess` ends.68 // This makes sure we wait for the completion of those streams, in order to catch any error.69-const waitForCustomStreamsEnd = (stdioStreamsGroups, streamInfo) => stdioStreamsGroups.flat()70- .filter(({value}) => isStream(value, {checkOpen: false}) && !isStandardStream(value))71- .map(({type, value, fdNumber}) => waitForStream(value, fdNumber, streamInfo, {69+const waitForCustomStreamsEnd = (fileDescriptors, streamInfo) => fileDescriptors.flatMap(({stdioItems, fdNumber}) => stdioItems70+ .filter(({value, stream = value}) => isNodeStream(stream, {checkOpen: false}) && !isStandardStream(stream))71+ .map(({type, value, stream = value}) => waitForStream(stream, fdNumber, streamInfo, {72 isSameDirection: type === 'generator',73 stopOnExit: type === 'native',74- }));74+ })));75 76 const throwOnSubprocessError = async (subprocess, {signal}) => {77 const [error] = await once(subprocess, 'error', {signal});78 throw error;6 unmodified linesmodified:lib/stream/subprocess.js+1 added-1 removed
6 unmodified lines7 if (!stream) {8 return;9 }10 11- if (isInputFileDescriptor(fdNumber, streamInfo.stdioStreamsGroups)) {11+ if (isInputFileDescriptor(fdNumber, streamInfo.fileDescriptors)) {12 await waitForStream(stream, fdNumber, streamInfo);13 return;14 }15 56 unmodified linesmodified:lib/stream/wait.js+4 added-5 removed
69 unmodified lines70 return isStreamEpipe(error) || isStreamAbort(error);71 }72 73 streamInfo.propagating = true;74- return isInputFileDescriptor(fdNumber, streamInfo.stdioStreamsGroups) === isSameDirection74+ return isInputFileDescriptor(fdNumber, streamInfo.fileDescriptors) === isSameDirection75 ? isStreamEpipe(error)76 : isStreamAbort(error);77 };78 1 unmodified line80 // For example, `subprocess.stdin` is technically a Duplex, but can only be used as a writable.81 // Therefore, we need to use the file descriptor's direction (`stdin` is input, `stdout` is output, etc.).82 // However, while `subprocess.std*` and transforms follow that direction, any stream passed the `std*` option has the opposite direction.83 // For example, `subprocess.stdin` is a writable, but the `stdin` option is a readable.84-export const isInputFileDescriptor = (fdNumber, stdioStreamsGroups) => {85- const [{direction}] = stdioStreamsGroups.find(stdioStreams => stdioStreams[0].fdNumber === fdNumber);86- return direction === 'input';87-};84+export const isInputFileDescriptor = (fdNumber, fileDescriptors) => fileDescriptors85+ .find(fileDescriptor => fileDescriptor.fdNumber === fdNumber)86+ .direction === 'input';87 88 // When `stream.destroy()` is called without an `error` argument, stream is aborted.89 // This is the only way to abort a readable stream, which can be useful in some instances.90 // Therefore, we ignore this error on readable streams.8 unmodified linesmodified:lib/verbose/output.js+10 added-15 removed
2 unmodified lines3 import {isBinaryEncoding} from '../encoding.js';4 import {PIPED_STDIO_VALUES} from '../stdio/forward.js';5 import {verboseLog} from './log.js';6 7-export const handleStreamsVerbose = ({stdioStreams, options, isSync, stdioState, verboseInfo}) => {8- if (!shouldLogOutput(stdioStreams, options, isSync, verboseInfo)) {9- return stdioStreams;10- }11-12- const [{fdNumber}] = stdioStreams;13- return [...stdioStreams, {14- ...stdioStreams[0],7+export const handleStreamsVerbose = ({stdioItems, options, isSync, stdioState, verboseInfo, fdNumber, optionName}) => shouldLogOutput({stdioItems, options, isSync, verboseInfo, fdNumber})8+ ? [{9 type: 'generator',10 value: verboseGenerator.bind(undefined, {stdioState, fdNumber, verboseInfo}),17- }];18-};11+ optionName,12+ }]13+ : [];14 15 // `ignore` opts-out of `verbose` for a specific stream.16 // `ipc` cannot use piping.17 // `inherit` would result in double printing.18 // They can also lead to double printing when passing file descriptor integers or `process.std*`.19 // This only leaves with `pipe` and `overlapped`.25-const shouldLogOutput = (stdioStreams, {encoding}, isSync, {verbose}) => verbose === 'full'20+const shouldLogOutput = ({stdioItems, options: {encoding}, isSync, verboseInfo: {verbose}, fdNumber}) => verbose === 'full'21 && !isSync22 && !isBinaryEncoding(encoding)28- && fdUsesVerbose(stdioStreams)29- && (stdioStreams.some(({type, value}) => type === 'native' && PIPED_STDIO_VALUES.has(value))30- || stdioStreams.every(({type}) => type === 'generator'));23+ && fdUsesVerbose(fdNumber)24+ && (stdioItems.some(({type, value}) => type === 'native' && PIPED_STDIO_VALUES.has(value))25+ || stdioItems.every(({type}) => type === 'generator'));26 27 // Printing input streams would be confusing.28 // Files and streams can produce big outputs, which we don't want to print.29 // We could print `stdio[3+]` but it often is redirected to files and streams, with the same issue.30 // So we only print stdout and stderr.36-const fdUsesVerbose = ([{fdNumber}]) => fdNumber === 1 || fdNumber === 2;31+const fdUsesVerbose = fdNumber => fdNumber === 1 || fdNumber === 2;32 33 const verboseGenerator = function * ({stdioState: {subprocess: {stdio}}, fdNumber, verboseInfo}, line) {34 if (!isPiping(stdio[fdNumber])) {35 logOutput(line, verboseInfo);24 unmodified linesmodified:lib/async.js+11 added-11 removed
14 unmodified lines15 import {getSubprocessResult} from './stream/resolve.js';16 import {mergePromise} from './promise.js';17 18 export const execa = (rawFile, rawArgs, rawOptions) => {19- const {file, args, command, escapedCommand, startTime, verboseInfo, options, stdioStreamsGroups, stdioState} = handleAsyncArguments(rawFile, rawArgs, rawOptions);20- const {subprocess, promise} = spawnSubprocessAsync({file, args, options, startTime, verboseInfo, command, escapedCommand, stdioStreamsGroups, stdioState});19+ const {file, args, command, escapedCommand, startTime, verboseInfo, options, fileDescriptors, stdioState} = handleAsyncArguments(rawFile, rawArgs, rawOptions);20+ const {subprocess, promise} = spawnSubprocessAsync({file, args, options, startTime, verboseInfo, command, escapedCommand, fileDescriptors, stdioState});21 subprocess.pipe = pipeToSubprocess.bind(undefined, {source: subprocess, sourcePromise: promise, boundOptions: {}});22 mergePromise(subprocess, promise);23- SUBPROCESS_OPTIONS.set(subprocess, {options, stdioStreamsGroups});23+ SUBPROCESS_OPTIONS.set(subprocess, {options, fileDescriptors});24 return subprocess;25 };26 27 const handleAsyncArguments = (rawFile, rawArgs, rawOptions) => {2 unmodified lines30 31 try {32 const {file, args, options: normalizedOptions} = handleArguments(rawFile, rawArgs, rawOptions);33 const options = handleAsyncOptions(normalizedOptions);34- const {stdioStreamsGroups, stdioState} = handleInputAsync(options, verboseInfo);35- return {file, args, command, escapedCommand, startTime, verboseInfo, options, stdioStreamsGroups, stdioState};34+ const {fileDescriptors, stdioState} = handleInputAsync(options, verboseInfo);35+ return {file, args, command, escapedCommand, startTime, verboseInfo, options, fileDescriptors, stdioState};36 } catch (error) {37 logEarlyResult(error, startTime, verboseInfo);38 throw error;39 }7 unmodified lines47 48 return {...options, timeoutDuration: timeout, signal: cancelSignal};49 };50 51-const spawnSubprocessAsync = ({file, args, options, startTime, verboseInfo, command, escapedCommand, stdioStreamsGroups, stdioState}) => {51+const spawnSubprocessAsync = ({file, args, options, startTime, verboseInfo, command, escapedCommand, fileDescriptors, stdioState}) => {52 let subprocess;53 try {54 subprocess = spawn(file, args, options);55 } catch (error) {56- return handleEarlyError({error, command, escapedCommand, stdioStreamsGroups, options, startTime, verboseInfo});56+ return handleEarlyError({error, command, escapedCommand, fileDescriptors, options, startTime, verboseInfo});57 }58 59 const controller = new AbortController();60 setMaxListeners(Number.POSITIVE_INFINITY, controller.signal);61 62 const originalStreams = [...subprocess.stdio];63- pipeOutputAsync(subprocess, stdioStreamsGroups, stdioState, controller);63+ pipeOutputAsync(subprocess, fileDescriptors, stdioState, controller);64 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, options);69 70- const promise = handlePromise({subprocess, options, startTime, verboseInfo, stdioStreamsGroups, originalStreams, command, escapedCommand, controller});70+ const promise = handlePromise({subprocess, options, startTime, verboseInfo, fileDescriptors, originalStreams, command, escapedCommand, controller});71 return {subprocess, promise};72 };73 74-const handlePromise = async ({subprocess, options, startTime, verboseInfo, stdioStreamsGroups, originalStreams, command, escapedCommand, controller}) => {74+const handlePromise = async ({subprocess, options, startTime, verboseInfo, fileDescriptors, originalStreams, command, escapedCommand, controller}) => {75 const context = {timedOut: false};76 77 const [78 errorInfo,79 [exitCode, signal],80 stdioResults,81 allResult,82- ] = await getSubprocessResult({subprocess, options, context, stdioStreamsGroups, originalStreams, controller});82+ ] = await getSubprocessResult({subprocess, options, context, fileDescriptors, originalStreams, controller});83 controller.abort();84 85 const stdio = stdioResults.map(stdioResult => handleOutput(options, stdioResult));86 const all = handleOutput(options, allResult);20 unmodified linesmodified:lib/sync.js+7 added-7 removed
5 unmodified lines6 import {logEarlyResult} from './verbose/complete.js';7 import {getSyncExitResult} from './exit/code.js';8 9 export const execaSync = (rawFile, rawArgs, rawOptions) => {10- const {file, args, command, escapedCommand, startTime, verboseInfo, options, stdioStreamsGroups} = handleSyncArguments(rawFile, rawArgs, rawOptions);11- const result = spawnSubprocessSync({file, args, options, command, escapedCommand, stdioStreamsGroups, startTime});10+ const {file, args, command, escapedCommand, startTime, verboseInfo, options, fileDescriptors} = handleSyncArguments(rawFile, rawArgs, rawOptions);11+ const result = spawnSubprocessSync({file, args, options, command, escapedCommand, fileDescriptors, startTime});12 return handleResult(result, verboseInfo, options);13 };14 15 const handleSyncArguments = (rawFile, rawArgs, rawOptions) => {3 unmodified lines19 try {20 const syncOptions = normalizeSyncOptions(rawOptions);21 const {file, args, options} = handleArguments(rawFile, rawArgs, syncOptions);22 validateSyncOptions(options);23- const stdioStreamsGroups = handleInputSync(options, verboseInfo);24- return {file, args, command, escapedCommand, startTime, verboseInfo, options, stdioStreamsGroups};23+ const fileDescriptors = handleInputSync(options, verboseInfo);24+ return {file, args, command, escapedCommand, startTime, verboseInfo, options, fileDescriptors};25 } catch (error) {26 logEarlyResult(error, startTime, verboseInfo);27 throw error;28 }6 unmodified lines35 throw new TypeError('The "ipc: true" option cannot be used with synchronous methods.');36 }37 };38 39-const spawnSubprocessSync = ({file, args, options, command, escapedCommand, stdioStreamsGroups, startTime}) => {39+const spawnSubprocessSync = ({file, args, options, command, escapedCommand, fileDescriptors, startTime}) => {40 let syncResult;41 try {42 syncResult = spawnSync(file, args, options);43 } catch (error) {44- return makeEarlyError({error, command, escapedCommand, stdioStreamsGroups, options, startTime, isSync: true});44+ return makeEarlyError({error, command, escapedCommand, fileDescriptors, options, startTime, isSync: true});45 }46 47 const {error, exitCode, signal} = getSyncExitResult(syncResult);48- pipeOutputSync(stdioStreamsGroups, syncResult);48+ pipeOutputSync(fileDescriptors, syncResult);49 50 const output = syncResult.output || Array.from({length: 3});51 const stdio = output.map(stdioOutput => handleOutput(options, stdioOutput));52 return getSyncResult({error, exitCode, signal, stdio, options, command, escapedCommand, startTime});17 unmodified lines