Skip to content
Myr

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

24 files+317 added−293 removed

modified:lib/pipe/abort.js+2 added-2 removed
modified:lib/pipe/setup.js+3 added-3 removed
modified:lib/pipe/throw.js+4 added-4 removed
modified:lib/pipe/validate.js+13 added-13 removed
12 unmodified lines
13 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 line
23 destination,24 destinationStream,25 destinationError,26 unpipeSignal,27 stdioStreamsGroups,27 fileDescriptors,28 startTime,29 };30};31
42 unmodified lines
74export const SUBPROCESS_OPTIONS = new WeakMap();7576export 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];8182 if (destinationStream === null) {83 throw new TypeError(getInvalidStdioOptionMessage(fdNumber, to, options, isWritable));
12 unmodified lines
96};9798export 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];103104 if (sourceStream === null || sourceStream === undefined) {105 throw new TypeError(getInvalidStdioOptionMessage(fdNumber, from, options, isWritable));
1 unmodified line
107108 return sourceStream;109};110111const getFdNumber = (stdioStreamsGroups, fdName, isWritable) => {111const 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};116117const parseFdNumber = (fdName, isWritable) => {
19 unmodified lines
137};138139const FD_REGEXP = /^fd(\d+)$/;140141const validateFdNumber = (fdNumber, fdName, isWritable, stdioStreamsGroups) => {141const 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.146Please set the "stdio" option to ensure that file descriptor exists.`);147 }148149 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 }152153 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 lines
modified:lib/return/early-error.js+7 added-7 removed
modified:lib/return/error.js+2 added-2 removed
32 unmodified lines
33export const makeEarlyError = ({34 error,35 command,36 escapedCommand,37 stdioStreamsGroups,37 fileDescriptors,38 options,39 startTime,40 isSync,41}) => makeError({
2 unmodified lines
44 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 lines
modified:lib/stdio/async.js+31 added-24 removed
16 unmodified lines
1718const 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};4243// 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 ended40export const pipeOutputAsync = (subprocess, stdioStreamsGroups, stdioState, controller) => {45export const pipeOutputAsync = (subprocess, fileDescriptors, stdioState, controller) => {46 stdioState.subprocess = subprocess;47 const inputStreamsGroups = {};4844 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 }5349 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 }5859 for (const [fdNumber, inputStreams] of Object.entries(inputStreamsGroups)) {
1 unmodified line
61 pipeStreams(inputStream, subprocess.stdio[fdNumber]);62 }63};6460const pipeStdioOption = (subprocess, {type, value, direction, fdNumber}, inputStreamsGroups, controller) => {61 if (type === 'native') {65const pipeStdioItem = ({subprocess, stream, direction, fdNumber, inputStreamsGroups, controller}) => {66 if (stream === undefined) {67 return;68 }6965 setStandardStreamMaxListeners(value, controller);70 setStandardStreamMaxListeners(stream, controller);7172 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};7879// Multiple subprocesses might be piping from/to `process.std*` at the same time.
12 unmodified lines
92// 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.91export const cleanupStdioStreams = stdioStreamsGroups => {92 for (const {value, type} of stdioStreamsGroups.flat()) {93 if (type !== 'native' && !isStandardStream(value)) {94 value.destroy();96export 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 lines
9// 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.13export const addStreamDirection = stdioStreams => {14 const directions = stdioStreams.map(stdioStream => getStreamDirection(stdioStream));13export const getStreamDirection = (stdioItems, fdNumber, optionName) => {14 const directions = stdioItems.map(stdioItem => getStdioItemDirection(stdioItem, fdNumber));1516 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 }1920 const direction = directions.find(Boolean);21 return stdioStreams.map(stdioStream => addDirection(stdioStream, direction));20 return directions.find(Boolean) ?? DEFAULT_DIRECTION;21};2224const getStreamDirection = ({fdNumber, type, value}) => KNOWN_DIRECTIONS[fdNumber] ?? guessStreamDirection[type](value);23const getStdioItemDirection = ({type, value}, fdNumber) => KNOWN_DIRECTIONS[fdNumber] ?? guessStreamDirection[type](value);2425// `stdin`/`stdout`/`stderr` have a known direction26const KNOWN_DIRECTIONS = ['input', 'output', 'output'];27
6 unmodified lines
34 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 }4446 if (!isNodeReadableStream(stdioOption, {checkOpen: false})) {45 if (!isNodeReadableStream(value, {checkOpen: false})) {46 return 'output';47 }4850 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 }5658 if (isNodeStream(stdioOption, {checkOpen: false})) {59 return guessStreamDirection.nodeStream(stdioOption);57 if (isNodeStream(value, {checkOpen: false})) {58 return guessStreamDirection.nodeStream(value);59 }60 },61};6264const getStandardStreamDirection = stdioOption => {65 if ([0, process.stdin].includes(stdioOption)) {63const getStandardStreamDirection = value => {64 if ([0, process.stdin].includes(value)) {65 return 'input';66 }6769 if ([1, 2, process.stdout, process.stderr].includes(stdioOption)) {68 if ([1, 2, process.stdout, process.stderr].includes(value)) {69 return 'output';70 }71};7274const addDirection = (stdioStream, direction = DEFAULT_DIRECTION) => ({...stdioStream, direction});7573// 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 line
modified:lib/stdio/encoding-final.js+18 added-24 removed
1import {StringDecoder} from 'node:string_decoder';2import {isSimpleEncoding} from '../encoding.js';3import {willPipeStreams} from './forward.js';34// Apply the `encoding` option using an implicit generator.5// This encodes the final output of `stdout`/`stderr`.7export const handleStreamsEncoding = (stdioStreams, {encoding}, isSync) => {8 const newStdioStreams = stdioStreams.map(stdioStream => ({...stdioStream, encoding}));9 if (!shouldEncodeOutput(newStdioStreams, encoding, isSync)) {10 return newStdioStreams;6export const handleStreamsEncoding = ({stdioItems, options: {encoding}, isSync, direction, optionName}) => {7 if (!shouldEncodeOutput({stdioItems, encoding, isSync, direction})) {8 return [];9 }1013 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 }1811 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};2234const shouldEncodeOutput = (stdioStreams, encoding, isSync) => stdioStreams[0].direction === 'output'23const shouldEncodeOutput = ({stdioItems, encoding, isSync, direction}) => direction === 'output'24 && !isSimpleEncoding(encoding)25 && !isSync37 && willPipeStreams(stdioStreams);26 && !isWritableObjectMode(stdioItems);2728const isWritableObjectMode = stdioItems => {29 const lastObjectStdioItem = stdioItems.findLast(({type, value}) => type === 'generator' && value.objectMode !== undefined);30 return lastObjectStdioItem !== undefined && lastObjectStdioItem.value.objectMode;31};3233const encodingStringGenerator = function * (stringDecoder, chunk) {34 yield stringDecoder.write(chunk);35};36
6 unmodified lines
modified: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*`.4export const forwardStdio = stdioStreamsGroups => stdioStreamsGroups.map(stdioStreams => forwardStdioItem(stdioStreams));51// Whether `subprocess.std*` will be set7export const willPipeStreams = stdioStreams => PIPED_STDIO_VALUES.has(forwardStdioItem(stdioStreams));2export const willPipeFileDescriptor = stdioItems => PIPED_STDIO_VALUES.has(forwardStdio(stdioItems));34export const PIPED_STDIO_VALUES = new Set(['pipe', 'overlapped', undefined, null]);56// 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*`.11const forwardStdioItem = stdioStreams => {12 if (stdioStreams.length > 1) {13 return stdioStreams.some(({value}) => value === 'overlapped') ? 'overlapped' : 'pipe';9export const forwardStdio = stdioItems => {10 if (stdioItems.length > 1) {11 return stdioItems.some(({value}) => value === 'overlapped') ? 'overlapped' : 'pipe';12 }1316 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 lines
5import {pipeStreams} from './pipeline.js';6import {isGeneratorOptions, isAsyncGenerator} from './type.js';7import {getValidateTransformReturn} from './validate.js';89export const normalizeGenerators = (stdioStreams, options) => {10 const nonGenerators = stdioStreams.filter(({type}) => type !== 'generator');11 const generators = stdioStreams.filter(({type}) => type === 'generator');9export const normalizeGenerators = (stdioItems, direction, {encoding}) => {10 const nonGenerators = stdioItems.filter(({type}) => type !== 'generator');11 const generators = stdioItems.filter(({type}) => type === 'generator');1213 const newGenerators = Array.from({length: generators.length});1415 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 }1819 return [...nonGenerators, ...sortGenerators(newGenerators)];19 return [...nonGenerators, ...sortGenerators(newGenerators, direction)];20};2122const normalizeGenerator = ({value, ...stdioStream}, index, newGenerators, {encoding}) => {22const 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};3637/*38`objectMode` determines the return value's type, i.e. the `readableObjectMode`.
17 unmodified lines
56 const readableObjectMode = index !== newGenerators.length - 1 && (objectMode ?? writableObjectMode);57 return {writableObjectMode, readableObjectMode};58};5960const sortGenerators = newGenerators => newGenerators[0]?.direction === 'input' ? newGenerators.reverse() : newGenerators;60const sortGenerators = (newGenerators, direction) => direction === 'input' ? newGenerators.reverse() : newGenerators;6162/*63Generators can be used to transform/filter standard streams.64
24 unmodified lines
89 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};9697// `subprocess.stdin|stdout|stderr|stdio` is directly mutated.98export const pipeGenerator = (subprocess, {value, direction, fdNumber}) => {98export 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 }104105 const streamProperty = SUBPROCESS_STREAM_PROPERTIES[fdNumber];106 if (streamProperty !== undefined) {107 subprocess[streamProperty] = value;107 subprocess[streamProperty] = stream;108 }109110 subprocess.stdio[fdNumber] = value;110 subprocess.stdio[fdNumber] = stream;111};112113const SUBPROCESS_STREAM_PROPERTIES = ['stdin', 'stdout', 'stderr'];
modified:lib/stdio/handle.js+65 added-39 removed
1import {handleStreamsVerbose} from '../verbose/output.js';2import {getStdioOptionType, isRegularUrl, isUnknownStdioString} from './type.js';3import {addStreamDirection} from './direction.js';2import {getStdioItemType, isRegularUrl, isUnknownStdioString} from './type.js';3import {getStreamDirection} from './direction.js';4import {normalizeStdio} from './option.js';5import {handleNativeStream} from './native.js';6import {handleInputOptions} from './input.js';7import {handleStreamsLines} from './lines.js';8import {handleStreamsEncoding} from './encoding-final.js';9import {normalizeGenerators} from './generator.js';10import {forwardStdio} from './forward.js';10import {forwardStdio, willPipeFileDescriptor} from './forward.js';1112// Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in async/sync mode13export 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};2122// 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'`.32const getStdioStreams = (stdioOption, fdNumber) => {25const 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};3233const getOptionName = fdNumber => KNOWN_OPTION_NAMES[fdNumber] ?? `stdio[${fdNumber}]`;34const KNOWN_OPTION_NAMES = ['stdin', 'stdout', 'stderr'];3545const getStdioStream = (stdioOption, optionName, fdNumber) => {46 const type = getStdioOptionType(stdioOption, optionName);47 return {type, value: stdioOption, optionName, fdNumber};36const 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 ];4243 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};4950const filterDuplicates = stdioStreams => stdioStreams.filter((stdioStreamOne, indexOne) =>51 stdioStreams.every((stdioStreamTwo, indexTwo) =>52 stdioStreamOne.value !== stdioStreamTwo.value || indexOne >= indexTwo || stdioStreamOne.type === 'generator'));50const initializeStdioItem = (value, optionName) => ({51 type: getStdioItemType(value, optionName),52 value,53 optionName,54});5556const filterDuplicates = stdioItems => stdioItems.filter((stdioItemOne, indexOne) =>57 stdioItems.every((stdioItemTwo, indexTwo) =>58 stdioItemOne.value !== stdioItemTwo.value || indexOne >= indexTwo || stdioItemOne.type === 'generator'));5954const validateStdioArray = (stdioStreams, isStdioArray, optionName) => {55 if (stdioStreams.length === 0) {60const validateStdioArray = (stdioItems, isStdioArray, optionName) => {61 if (stdioItems.length === 0) {62 throw new TypeError(`The \`${optionName}\` option must not be an empty array.`);63 }6465 if (!isStdioArray) {66 return;67 }6863 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 lines
76// 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.78const INVALID_STDIO_ARRAY_OPTIONS = new Set(['ignore', 'ipc']);7974const validateStreams = stdioStreams => {75 for (const stdioStream of stdioStreams) {76 validateFileStdio(stdioStream);80const validateStreams = stdioItems => {81 for (const stdioItem of stdioItems) {82 validateFileStdio(stdioItem);83 }7879 return stdioStreams;84};8586const validateFileStdio = ({type, value, optionName}) => {87 if (isRegularUrl(value)) {
5 unmodified lines
93 throw new TypeError(`The \`${optionName}: { file: '...' }\` option must be used instead of \`${optionName}: '...'\`.`);94 }95};9697const 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};102103const addInternalStdioItems = ({stdioItems, fdNumber, optionName, options, isSync, direction, stdioState, verboseInfo}) => {104 if (!willPipeFileDescriptor(stdioItems)) {105 return stdioItems;106 }107108 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};118119// 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.96const addStreamsProperties = (stdioStreams, addProperties) => stdioStreams.map(stdioStream => ({97 ...stdioStream,98 ...addProperties[stdioStream.direction][stdioStream.type]?.(stdioStream),99}));122const addStreamProperties = (stdioItem, addProperties, direction) => ({123 ...stdioItem,124 ...addProperties[direction][stdioItem.type](stdioItem),125});
modified:lib/stdio/input.js+10 added-10 removed
1 unmodified line
2import {isUint8Array} from '../encoding.js';3import {isUrl, isFilePathString} from './type.js';45// Append the `stdin` option with the `input` and `inputFile` options6export const handleInputOptions = ({input, inputFile}) => [7 handleInputOption(input),8 handleInputFileOption(inputFile),9].filter(Boolean);6export const handleInputOptions = ({input, inputFile}, fdNumber) => fdNumber === 07 ? [8 ...handleInputOption(input),9 ...handleInputFileOption(inputFile),10 ]11 : [];1211const handleInputOption = input => input === undefined ? undefined : {13const handleInputOption = input => input === undefined ? [] : [{14 type: getInputType(input),15 value: input,16 optionName: 'input',15 fdNumber: 0,16};17}];1819const getInputType = input => {20 if (isReadableStream(input, {checkOpen: false})) {21 return 'nodeStream';
9 unmodified lines
3132 throw new Error('The `input` option must be a string, a Uint8Array or a Node.js Readable stream.');33};3434const handleInputFileOption = inputFile => inputFile === undefined ? undefined : {35const handleInputFileOption = inputFile => inputFile === undefined ? [] : [{36 ...getInputFileType(inputFile),37 optionName: 'inputFile',37 fdNumber: 0,38};38}];3940const getInputFileType = inputFile => {41 if (isUrl(inputFile)) {42 return {type: 'fileUrl', value: inputFile};
8 unmodified lines
modified:lib/stdio/lines.js+9 added-14 removed
1import {isBinaryEncoding} from '../encoding.js';2import {willPipeStreams} from './forward.js';23// 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.6export 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;5export 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 : [];1217const shouldSplitLines = ({stdioStreams, lines, encoding, isSync}) => stdioStreams[0].direction === 'output'13const shouldSplitLines = ({lines, encoding, isSync, direction}) => direction === 'output'14 && lines15 && !isBinaryEncoding(encoding)20 && !isSync21 && willPipeStreams(stdioStreams);16 && !isSync;1718const linesEndGenerator = function * (chunk) {19 yield chunk;20};
modified:lib/stdio/native.js+7 added-7 removed
6 unmodified lines
7// - 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.11export const handleNativeStream = (stdioStream, isStdioArray) => {12 const {type, value, fdNumber, optionName} = stdioStream;11export const handleNativeStream = (stdioItem, isStdioArray, fdNumber) => {12 const {type, value, optionName} = stdioItem;1314 if (!isStdioArray || type !== 'native') {15 return stdioStream;15 return stdioItem;16 }1718 if (value === 'inherit') {19 return {...stdioStream, type: 'nodeStream', value: getStandardStream(fdNumber, value, optionName)};19 return {type: 'nodeStream', value: getStandardStream(fdNumber, value, optionName), optionName};20 }2122 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 }2526 if (isNodeStream(value, {checkOpen: false})) {27 return {...stdioStream, type: 'nodeStream'};27 return {type: 'nodeStream', value, optionName};28 }2930 return stdioStream;30 return stdioItem;31};3233// 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 lines
modified:lib/stdio/sync.js+29 added-19 removed
3 unmodified lines
4import {TYPE_TO_MESSAGE} from './type.js';56// Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in sync mode7export 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};1213const forbiddenIfSync = ({type, optionName}) => {14 throw new TypeError(`The \`${optionName}\` option cannot be ${TYPE_TO_MESSAGE[type]} in sync mode.`);
1 unmodified line
1617const 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};4136const addInputOptionSync = (stdioStreamsGroups, options) => {37 const inputs = stdioStreamsGroups.flat().filter(({direction, type}) => direction === 'input' && (type === 'string' || type === 'uint8Array'));38 if (inputs.length === 0) {42const 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 }5142 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};5647const serializeInput = ({type, value}) => type === 'string' ? value : uint8ArrayToString(value);57const serializeContents = contents => typeof contents === 'string' ? contents : uint8ArrayToString(contents);5859// Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, after spawning, in sync mode50export const pipeOutputSync = (stdioStreamsGroups, {output}) => {60export const pipeOutputSync = (fileDescriptors, {output}) => {61 if (output === null) {62 return;63 }6455 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};7162const pipeStdioOptionSync = (result, {type, value, direction}) => {72const pipeStdioItemSync = (result, type, path, direction) => {73 if (result === null || direction === 'input') {74 return;75 }7677 if (type === 'fileUrl' || type === 'filePath') {68 writeFileSync(value, result);78 writeFileSync(path, result);79 }80};
modified:lib/stdio/type.js+31 added-29 removed
1import {isStream as isNodeStream} from 'is-stream';2import {isUint8Array} from '../encoding.js';34// The `stdin`/`stdout`/`stderr` option can be of many types. This detects it.5export const getStdioOptionType = (stdioOption, optionName) => {6 if (isGenerator(stdioOption)) {5export const getStdioItemType = (value, optionName) => {6 if (isGenerator(value)) {7 return 'generator';8 }910 if (isUrl(stdioOption)) {10 if (isUrl(value)) {11 return 'fileUrl';12 }1314 if (isFilePathObject(stdioOption)) {14 if (isFilePathObject(value)) {15 return 'filePath';16 }1718 if (isWebStream(stdioOption)) {18 if (isWebStream(value)) {19 return 'webStream';20 }2122 if (isNodeStream(stdioOption, {checkOpen: false})) {22 if (isNodeStream(value, {checkOpen: false})) {23 return 'native';24 }2526 if (isUint8Array(stdioOption)) {26 if (isUint8Array(value)) {27 return 'uint8Array';28 }2930 if (isIterableObject(stdioOption)) {30 if (isIterableObject(value)) {31 return 'iterable';32 }3334 if (isGeneratorOptions(stdioOption)) {35 return getGeneratorObjectType(stdioOption, optionName);34 if (isGeneratorOptions(value)) {35 return getGeneratorObjectType(value, optionName);36 }3738 return 'native';39};
18 unmodified lines
58 throw new TypeError(`The \`${optionName}\` option must use a boolean.`);59 }60};6162const isGenerator = stdioOption => isAsyncGenerator(stdioOption) || isSyncGenerator(stdioOption);63export const isAsyncGenerator = stdioOption => Object.prototype.toString.call(stdioOption) === '[object AsyncGeneratorFunction]';64const isSyncGenerator = stdioOption => Object.prototype.toString.call(stdioOption) === '[object GeneratorFunction]';65export const isGeneratorOptions = stdioOption => typeof stdioOption === 'object'66 && stdioOption !== null67 && (stdioOption.transform !== undefined || stdioOption.final !== undefined);62const isGenerator = value => isAsyncGenerator(value) || isSyncGenerator(value);63export const isAsyncGenerator = value => Object.prototype.toString.call(value) === '[object AsyncGeneratorFunction]';64const isSyncGenerator = value => Object.prototype.toString.call(value) === '[object GeneratorFunction]';65export const isGeneratorOptions = value => typeof value === 'object'66 && value !== null67 && (value.transform !== undefined || value.final !== undefined);6869export const isUrl = stdioOption => Object.prototype.toString.call(stdioOption) === '[object URL]';70export const isRegularUrl = stdioOption => isUrl(stdioOption) && stdioOption.protocol !== 'file:';69export const isUrl = value => Object.prototype.toString.call(value) === '[object URL]';70export const isRegularUrl = value => isUrl(value) && value.protocol !== 'file:';7172const isFilePathObject = stdioOption => typeof stdioOption === 'object'73 && stdioOption !== null74 && Object.keys(stdioOption).length === 175 && isFilePathString(stdioOption.file);72const isFilePathObject = value => typeof value === 'object'73 && value !== null74 && Object.keys(value).length === 175 && isFilePathString(value.file);76export const isFilePathString = file => typeof file === 'string';7778export const isUnknownStdioString = (type, stdioOption) => type === 'native' && typeof stdioOption === 'string' && !KNOWN_STDIO_STRINGS.has(stdioOption);78export const isUnknownStdioString = (type, value) => type === 'native'79 && typeof value === 'string'80 && !KNOWN_STDIO_STRINGS.has(value);81const KNOWN_STDIO_STRINGS = new Set(['ipc', 'ignore', 'inherit', 'overlapped', 'pipe']);8281const isReadableStream = stdioOption => Object.prototype.toString.call(stdioOption) === '[object ReadableStream]';82export const isWritableStream = stdioOption => Object.prototype.toString.call(stdioOption) === '[object WritableStream]';83const isWebStream = stdioOption => isReadableStream(stdioOption) || isWritableStream(stdioOption);83const isReadableStream = value => Object.prototype.toString.call(value) === '[object ReadableStream]';84export const isWritableStream = value => Object.prototype.toString.call(value) === '[object WritableStream]';85const isWebStream = value => isReadableStream(value) || isWritableStream(value);8685const isIterableObject = stdioOption => typeof stdioOption === 'object'86 && stdioOption !== null87 && (typeof stdioOption[Symbol.asyncIterator] === 'function' || typeof stdioOption[Symbol.iterator] === 'function');87const isIterableObject = value => typeof value === 'object'88 && value !== null89 && (typeof value[Symbol.asyncIterator] === 'function' || typeof value[Symbol.iterator] === 'function');9091// Convert types to human-friendly strings for error messages92export const TYPE_TO_MESSAGE = {93 generator: 'a generator',
9 unmodified lines
modified:lib/stream/all.js+2 added-1 removed
22 unmodified lines
23// - `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.26const 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;2930const getAllStreamTransform = encoding => ({31 value: {
3 unmodified lines
35 readableObjectMode: true,36 preserveNewlines: true,37 },38 forceEncoding: true,39 optionName: 'all',40});
modified:lib/stream/resolve.js+8 added-8 removed
1import {once} from 'node:events';2import {isStream} from 'is-stream';2import {isStream as isNodeStream} from 'is-stream';3import {waitForSuccessfulExit} from '../exit/code.js';4import {errorSignal} from '../exit/kill.js';5import {throwOnTimeout} from '../exit/timeout.js';6import {isStandardStream} from '../utils.js';
6 unmodified lines
13export 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};2324 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);2829 try {30 return await Promise.race([31 Promise.all([
33 unmodified lines
6566// 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.69const waitForCustomStreamsEnd = (stdioStreamsGroups, streamInfo) => stdioStreamsGroups.flat()70 .filter(({value}) => isStream(value, {checkOpen: false}) && !isStandardStream(value))71 .map(({type, value, fdNumber}) => waitForStream(value, fdNumber, streamInfo, {69const 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 })));7576const throwOnSubprocessError = async (subprocess, {signal}) => {77 const [error] = await once(subprocess, 'error', {signal});78 throw error;
6 unmodified lines
modified:lib/stream/subprocess.js+1 added-1 removed
6 unmodified lines
7 if (!stream) {8 return;9 }1011 if (isInputFileDescriptor(fdNumber, streamInfo.stdioStreamsGroups)) {11 if (isInputFileDescriptor(fdNumber, streamInfo.fileDescriptors)) {12 await waitForStream(stream, fdNumber, streamInfo);13 return;14 }15
56 unmodified lines
modified:lib/stream/wait.js+4 added-5 removed
69 unmodified lines
70 return isStreamEpipe(error) || isStreamAbort(error);71 }7273 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 line
80// 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.84export const isInputFileDescriptor = (fdNumber, stdioStreamsGroups) => {85 const [{direction}] = stdioStreamsGroups.find(stdioStreams => stdioStreams[0].fdNumber === fdNumber);86 return direction === 'input';87};84export const isInputFileDescriptor = (fdNumber, fileDescriptors) => fileDescriptors85 .find(fileDescriptor => fileDescriptor.fdNumber === fdNumber)86 .direction === 'input';8788// 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 lines
modified:lib/verbose/output.js+10 added-15 removed
2 unmodified lines
3import {isBinaryEncoding} from '../encoding.js';4import {PIPED_STDIO_VALUES} from '../stdio/forward.js';5import {verboseLog} from './log.js';67export const handleStreamsVerbose = ({stdioStreams, options, isSync, stdioState, verboseInfo}) => {8 if (!shouldLogOutput(stdioStreams, options, isSync, verboseInfo)) {9 return stdioStreams;10 }1112 const [{fdNumber}] = stdioStreams;13 return [...stdioStreams, {14 ...stdioStreams[0],7export 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 : [];1415// `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`.25const shouldLogOutput = (stdioStreams, {encoding}, isSync, {verbose}) => verbose === 'full'20const 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'));2627// 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.36const fdUsesVerbose = ([{fdNumber}]) => fdNumber === 1 || fdNumber === 2;31const fdUsesVerbose = fdNumber => fdNumber === 1 || fdNumber === 2;3233const verboseGenerator = function * ({stdioState: {subprocess: {stdio}}, fdNumber, verboseInfo}, line) {34 if (!isPiping(stdio[fdNumber])) {35 logOutput(line, verboseInfo);
24 unmodified lines
modified:lib/async.js+11 added-11 removed
14 unmodified lines
15import {getSubprocessResult} from './stream/resolve.js';16import {mergePromise} from './promise.js';1718export 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};2627const handleAsyncArguments = (rawFile, rawArgs, rawOptions) => {
2 unmodified lines
3031 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 lines
4748 return {...options, timeoutDuration: timeout, signal: cancelSignal};49};5051const spawnSubprocessAsync = ({file, args, options, startTime, verboseInfo, command, escapedCommand, stdioStreamsGroups, stdioState}) => {51const 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 }5859 const controller = new AbortController();60 setMaxListeners(Number.POSITIVE_INFINITY, controller.signal);6162 const originalStreams = [...subprocess.stdio];63 pipeOutputAsync(subprocess, stdioStreamsGroups, stdioState, controller);63 pipeOutputAsync(subprocess, fileDescriptors, stdioState, controller);64 cleanupOnExit(subprocess, options, controller);6566 subprocess.kill = subprocessKill.bind(undefined, {kill: subprocess.kill.bind(subprocess), subprocess, options, controller});67 subprocess.all = makeAllStream(subprocess, options);68 addConvertedStreams(subprocess, options);6970 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};7374const handlePromise = async ({subprocess, options, startTime, verboseInfo, stdioStreamsGroups, originalStreams, command, escapedCommand, controller}) => {74const handlePromise = async ({subprocess, options, startTime, verboseInfo, fileDescriptors, originalStreams, command, escapedCommand, controller}) => {75 const context = {timedOut: false};7677 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();8485 const stdio = stdioResults.map(stdioResult => handleOutput(options, stdioResult));86 const all = handleOutput(options, allResult);
20 unmodified lines
modified:lib/sync.js+7 added-7 removed
5 unmodified lines
6import {logEarlyResult} from './verbose/complete.js';7import {getSyncExitResult} from './exit/code.js';89export 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};1415const handleSyncArguments = (rawFile, rawArgs, rawOptions) => {
3 unmodified lines
19 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 lines
35 throw new TypeError('The "ipc: true" option cannot be used with synchronous methods.');36 }37};3839const spawnSubprocessSync = ({file, args, options, command, escapedCommand, stdioStreamsGroups, startTime}) => {39const 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 }4647 const {error, exitCode, signal} = getSyncExitResult(syncResult);48 pipeOutputSync(stdioStreamsGroups, syncResult);48 pipeOutputSync(fileDescriptors, syncResult);4950 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