handle.js
This file
Path
lib/stdio/handle.js
293 lines · 10.7 KiB · JavaScript
Last changed by
Fix wrong-typed options and arguments being silently ignored or coercedSindre Sorhusbefore adoptionb57d643
History of this fileTake it
The walk stopped after 200 commits: lines older than 9f65b86 point at it.
Fix wrong-typed options and arguments being silently ignored or coercedSindre Sorhusbefore adoptionb57d643
line 1why, one step back1import {isStream as isNodeStream} from 'is-stream';100% test coverage (#1018)ehmickybefore adoption9f65b86
line 2why, one step back2import {getStreamName, isStandardStream} from '../utils/standard-stream.js';Fix wrong-typed options and arguments being silently ignored or coercedSindre Sorhusbefore adoptionb57d643
line 3why, one step back3import {checkBooleanOption} from '../utils/options.js';100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 4–9why, one step back4import {normalizeTransforms} from '../transform/normalize.js';5import {getFdObjectMode} from '../transform/object-mode.js';6import {7 getStdioItemType,8 isRegularUrl,9 isUnknownStdioString,Generalize `{value, input}` to any direction-ambiguous stdio value (#1249)Sindre Sorhusbefore adoption9fbf5ba
line 10why, one step back10 isStdioValueObject,100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 11–22why, one step back11 FILE_TYPES,12} from './type.js';13import {getStreamDirection} from './direction.js';14import {normalizeStdioOption} from './stdio-option.js';15import {handleNativeStream} from './native.js';16import {handleInputOptions} from './input-option.js';17import {filterDuplicates, getDuplicateStream} from './duplicate.js';1819// Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in async/sync mode20// They are converted into an array of `fileDescriptors`.21// Each `fileDescriptor` is normalized, validated and contains all information necessary for further handling.22export const handleStdio = (addProperties, options, verboseInfo, isSync) => {Refactor `verbose` logic (#1126)ehmickybefore adoptionf9f1199
line 23why, one step back23 const stdio = normalizeStdioOption(options, verboseInfo, isSync);100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 24–47why, one step back24 const initialFileDescriptors = stdio.map((stdioOption, fdNumber) => getFileDescriptor({25 stdioOption,26 fdNumber,27 options,28 isSync,29 }));30 const fileDescriptors = getFinalFileDescriptors({31 initialFileDescriptors,32 addProperties,33 options,34 isSync,35 });36 options.stdio = fileDescriptors.map(({stdioItems}) => forwardStdio(stdioItems));37 return fileDescriptors;38};3940const getFileDescriptor = ({stdioOption, fdNumber, options, isSync}) => {41 const optionName = getStreamName(fdNumber);42 const {stdioItems: initialStdioItems, isStdioArray} = initializeStdioItems({43 stdioOption,44 fdNumber,45 options,46 optionName,47 });TweaksSindre Sorhusbefore adoption698a1b8
lines 48–53why, one step back48 const direction = getStreamDirection({49 stdioItems: initialStdioItems,50 isStdioArray,51 fdNumber,52 optionName,53 });100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 54–71why, one step back54 const stdioItems = initialStdioItems.map(stdioItem => handleNativeStream({55 stdioItem,56 isStdioArray,57 fdNumber,58 direction,59 isSync,60 }));61 const normalizedStdioItems = normalizeTransforms(stdioItems, optionName, direction, options);62 const objectMode = getFdObjectMode(normalizedStdioItems, direction);63 validateFileObjectMode(normalizedStdioItems, objectMode);64 return {direction, objectMode, stdioItems: normalizedStdioItems};65};6667// We make sure passing an array with a single item behaves the same as passing that item without an array.68// This is what users would expect.69// For example, `stdout: ['ignore']` behaves the same as `stdout: 'ignore'`.70const initializeStdioItems = ({stdioOption, fdNumber, options, optionName}) => {71 const values = Array.isArray(stdioOption) ? stdioOption : [stdioOption];Fix input with inherited stdin (#1232)Puneet Dixitbefore adoption3ed0544
line 72why, one step back72 const inputStdioItems = handleInputOptions(options, fdNumber);100% test coverage (#1018)ehmickybefore adoption9f65b86
line 73why, one step back73 const initialStdioItems = [Fix input with inherited stdin (#1232)Puneet Dixitbefore adoption3ed0544
lines 74–75why, one step back74 ...omitInheritedStdin(values.map(value => initializeStdioItem(value, optionName)), inputStdioItems),75 ...inputStdioItems,100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 76–80why, one step back76 ];7778 const stdioItems = filterDuplicates(initialStdioItems);79 const isStdioArray = stdioItems.length > 1;80 validateStdioArray(stdioItems, isStdioArray, optionName);Fix wrong-typed options and arguments being silently ignored or coercedSindre Sorhusbefore adoptionb57d643
line 81why, one step back81 validateStreams(stdioItems, isStdioArray);100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 82–83why, one step back82 return {stdioItems, isStdioArray};83};Fix input with inherited stdin (#1232)Puneet Dixitbefore adoption3ed0544
lines 84–91why, one step back8485const omitInheritedStdin = (stdioItems, inputStdioItems) => inputStdioItems.length > 0 && isInheritedStdinOnly(stdioItems)86 ? []87 : stdioItems;8889const isInheritedStdinOnly = stdioItems => stdioItems.length === 190 && stdioItems[0].type === 'native'91 && stdioItems[0].value === 'inherit';100% test coverage (#1018)ehmickybefore adoption9f65b86
line 92why, one step back92Add `{value: 'pipe', input: true}` to use an additional file descriptor as input (#1246)Sindre Sorhusbefore adoption487a3a4
line 93why, one step back93const initializeStdioItem = (value, optionName) => {Generalize `{value, input}` to any direction-ambiguous stdio value (#1249)Sindre Sorhusbefore adoption9fbf5ba
lines 94–95why, one step back94 if (isStdioValueObject(value)) {95 return initializeStdioValueObject(value, optionName);Add `{value: 'pipe', input: true}` to use an additional file descriptor as input (#1246)Sindre Sorhusbefore adoption487a3a4
lines 96–104why, one step back96 }9798 return {99 type: getStdioItemType(value, optionName),100 value,101 optionName,102 };103};104Generalize `{value, input}` to any direction-ambiguous stdio value (#1249)Sindre Sorhusbefore adoption9fbf5ba
lines 105–106why, one step back105// The `{value, input}` object form wraps any stdio value with an explicit direction.106const initializeStdioValueObject = ({value, input}, optionName) => {Add `{value: 'pipe', input: true}` to use an additional file descriptor as input (#1246)Sindre Sorhusbefore adoption487a3a4
lines 107–109why, one step back107 checkBooleanOption(input, `${optionName}.input`);108109 return {Generalize `{value, input}` to any direction-ambiguous stdio value (#1249)Sindre Sorhusbefore adoption9fbf5ba
line 110why, one step back110 type: getStdioItemType(value, optionName),Add `{value: 'pipe', input: true}` to use an additional file descriptor as input (#1246)Sindre Sorhusbefore adoption487a3a4
lines 111–115why, one step back111 value,112 direction: input ? 'input' : undefined,113 optionName,114 };115};100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 116–132why, one step back116117const validateStdioArray = (stdioItems, isStdioArray, optionName) => {118 if (stdioItems.length === 0) {119 throw new TypeError(`The \`${optionName}\` option must not be an empty array.`);120 }121122 if (!isStdioArray) {123 return;124 }125126 for (const {value, optionName} of stdioItems) {127 if (INVALID_STDIO_ARRAY_OPTIONS.has(value)) {128 throw new Error(`The \`${optionName}\` option must not include \`${value}\`.`);129 }130 }131};132Remove the old `stdio: [..., 'ipc']` syntax (#1245)Sindre Sorhusbefore adoptiondcf611c
line 133why, one step back133// Using the `ignore` value together with others for the same stream does not make sense, so we make it fail.100% test coverage (#1018)ehmickybefore adoption9f65b86
line 134why, one step back134// However, we do allow it if the array has a single item.Remove the old `stdio: [..., 'ipc']` syntax (#1245)Sindre Sorhusbefore adoptiondcf611c
line 135why, one step back135const INVALID_STDIO_ARRAY_OPTIONS = new Set(['ignore']);100% test coverage (#1018)ehmickybefore adoption9f65b86
line 136why, one step back136Fix wrong-typed options and arguments being silently ignored or coercedSindre Sorhusbefore adoptionb57d643
line 137why, one step back137const validateStreams = (stdioItems, isStdioArray) => {100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 138–139why, one step back138 for (const stdioItem of stdioItems) {139 validateFileStdio(stdioItem);Fix invalid `stdio` values being acceptedSindre Sorhusbefore adoptionc6bd387
line 140why, one step back140 validateFileDescriptorStdio(stdioItem);Fix wrong-typed options and arguments being silently ignored or coercedSindre Sorhusbefore adoptionb57d643
line 141why, one step back141 validateNativeStdio(stdioItem, isStdioArray);100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 142–143why, one step back142 }143};Fix invalid `stdio` values being acceptedSindre Sorhusbefore adoptionc6bd387
lines 144–152why, one step back144145// A number is a file descriptor. Anything else is not a valid one, and passing it to `node:child_process` aborts the current process with a fatal assertion instead of throwing.146const validateFileDescriptorStdio = ({type, value, optionName}) => {147 if (type === 'native' && typeof value === 'number' && (!Number.isInteger(value) || value < 0 || value > MAX_FILE_DESCRIPTOR)) {148 throw new TypeError(`The \`${optionName}\` option must be a non-negative 32-bit integer: got ${value}.`);149 }150};151152// `node:child_process` converts file descriptors to a 32-bit signed integer, and aborts the process when it cannotTweaksSindre Sorhusbefore adoption698a1b8
line 153why, one step back153const MAX_FILE_DESCRIPTOR = (2 ** 31) - 1;Fix wrong-typed options and arguments being silently ignored or coercedSindre Sorhusbefore adoptionb57d643
lines 154–177why, one step back154155// When passed alone, any unknown value fails when calling `node:child_process`.156// However, when an array is used, Execa only forwards `pipe` to `node:child_process`, so unknown values would be silently ignored.157// Valid values are the ones `node:child_process` accepts: known strings, file descriptor integers, Node.js streams and file handles.158// File handles are the exception: they are valid alone, but Execa's array emulation cannot handle them, so they would be silently ignored.159const validateNativeStdio = ({type, value, optionName}, isStdioArray) => {160 if (type !== 'native') {161 return;162 }163164 if (isFileHandle(value)) {165 if (isStdioArray) {166 throw new TypeError(`The \`${optionName}\` option cannot combine file handles with other values.`);167 }168169 return;170 }171172 if (typeof value !== 'string' && typeof value !== 'number' && !isNodeStream(value, {checkOpen: false})) {173 throw new TypeError(`The \`${optionName}\` option is invalid: ${String(value)} (${typeof value}).`);174 }175};176177const isFileHandle = value => typeof value?.fd === 'number' && !isNodeStream(value, {checkOpen: false});100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 178–208why, one step back178179const validateFileStdio = ({type, value, optionName}) => {180 if (isRegularUrl(value)) {181 throw new TypeError(`The \`${optionName}: URL\` option must use the \`file:\` scheme.182For example, you can use the \`pathToFileURL()\` method of the \`url\` core module.`);183 }184185 if (isUnknownStdioString(type, value)) {186 throw new TypeError(`The \`${optionName}: { file: '...' }\` option must be used instead of \`${optionName}: '...'\`.`);187 }188};189190const validateFileObjectMode = (stdioItems, objectMode) => {191 if (!objectMode) {192 return;193 }194195 const fileStdioItem = stdioItems.find(({type}) => FILE_TYPES.has(type));196 if (fileStdioItem !== undefined) {197 throw new TypeError(`The \`${fileStdioItem.optionName}\` option cannot use both files and transforms in objectMode.`);198 }199};200201// Some `stdio` values require Execa to create streams.202// For example, file paths create file read/write streams.203// Those transformations are specified in `addProperties`, which is both direction-specific and type-specific.204const getFinalFileDescriptors = ({initialFileDescriptors, addProperties, options, isSync}) => {205 const fileDescriptors = [];206207 try {208 for (const fileDescriptor of initialFileDescriptors) {Fix duplicated or conflicting file descriptor targetsSindre Sorhusbefore adoption587045a
line 209why, one step back209 addFinalFileDescriptor({100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 210–214why, one step back210 fileDescriptor,211 fileDescriptors,212 addProperties,213 options,214 isSync,Fix duplicated or conflicting file descriptor targetsSindre Sorhusbefore adoption587045a
line 215why, one step back215 });100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 216–224why, one step back216 }217218 return fileDescriptors;219 } catch (error) {220 cleanupCustomStreams(fileDescriptors);221 throw error;222 }223};224Fix duplicated or conflicting file descriptor targetsSindre Sorhusbefore adoption587045a
lines 225–239why, one step back225/*226The file descriptor is added to `fileDescriptors` before its items are, for two reasons:227 - its items are added one at a time, so that each one knows about the previous ones, to detect duplicates within the same file descriptor228 - if an item throws, the streams created by the previous ones are cleaned up too229*/230const addFinalFileDescriptor = ({fileDescriptor, fileDescriptors, addProperties, options, isSync}) => {231 const {direction, objectMode, stdioItems} = fileDescriptor;232 const finalFileDescriptor = {direction, objectMode, stdioItems: []};233 fileDescriptors.push(finalFileDescriptor);234235 for (const stdioItem of stdioItems) {236 finalFileDescriptor.stdioItems.push(addStreamProperties({237 stdioItem,238 addProperties,239 direction,Fix `stdin` iterables and input transforms edge casesSindre Sorhusbefore adoption6925cc3
line 240why, one step back240 objectMode,Fix duplicated or conflicting file descriptor targetsSindre Sorhusbefore adoption587045a
lines 241–245why, one step back241 options,242 fileDescriptors,243 isSync,244 }));245 }100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 246–247why, one step back246};247Fix `stdin` iterables and input transforms edge casesSindre Sorhusbefore adoption6925cc3
line 248why, one step back248const addStreamProperties = ({stdioItem, addProperties, direction, objectMode, options, fileDescriptors, isSync}) => {100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 249–261why, one step back249 const duplicateStream = getDuplicateStream({250 stdioItem,251 direction,252 fileDescriptors,253 isSync,254 });255256 if (duplicateStream !== undefined) {257 return {...stdioItem, stream: duplicateStream};258 }259260 return {261 ...stdioItem,Fix `stdin` iterables and input transforms edge casesSindre Sorhusbefore adoption6925cc3
line 262why, one step back262 ...addProperties[direction][stdioItem.type](stdioItem, options, objectMode),100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 263–270why, one step back263 };264};265266// The stream error handling is performed by the piping logic above, which cannot be performed before subprocess spawning.267// If the subprocess spawning fails (e.g. due to an invalid command), the streams need to be manually destroyed.268// We need to create those streams before subprocess spawning, in case their creation fails, e.g. when passing an invalid generator as argument.269// Like this, an exception would be thrown, which would prevent spawning a subprocess.270export const cleanupCustomStreams = fileDescriptors => {Fix an uncaught error when a file target cannot be opened and the subprocess fails to spawnSindre Sorhusbefore adoption1cee524
lines 271–273why, one step back271 for (const {stream} of fileDescriptors.flatMap(({stdioItems}) => stdioItems)) {272 if (stream === undefined || isStandardStream(stream)) {273 continue;100% test coverage (#1018)ehmickybefore adoption9f65b86
line 274why, one step back274 }Fix an uncaught error when a file target cannot be opened and the subprocess fails to spawnSindre Sorhusbefore adoption1cee524
lines 275–279why, one step back275276 // The stream can still error after being destroyed, e.g. when its file cannot be opened.277 // That error would be uncaught and crash the current process, although it is irrelevant since execa already fails with its own error.278 stream.on('error', () => {});279 stream.destroy();100% test coverage (#1018)ehmickybefore adoption9f65b86
lines 280–293why, one step back280 }281};282283// When the `std*: Iterable | WebStream | URL | filePath`, `input` or `inputFile` option is used, we pipe to `subprocess.std*`.284// 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*`.285// Therefore the `std*` options must be either `pipe` or `overlapped`. Other values do not set `subprocess.std*`.286const forwardStdio = stdioItems => {287 if (stdioItems.length > 1) {288 return stdioItems.some(({value}) => value === 'overlapped') ? 'overlapped' : 'pipe';289 }290291 const [{type, value}] = stdioItems;292 return type === 'native' ? value : 'pipe';293};