Fix wrong-typed options and arguments being silently ignored or coerced
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Sindre Sorhus · committed by Sindre Sorhus · parent 74b854a · Browse files · 32 files·+342 added−35 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
32 files+342 added−35 removed
- tests:+199 added−0 removed
- other:+143 added−35 removed
Provenance
- Commit
b57d643- Tree
d009655- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
74b854a
32 files changed+342 added−35 removed
modified:lib/arguments/options.js+29 added
6 unmodified lines7891011121314159 unmodified lines2526272829303132333416 unmodified lines5152535455565758596061626364656667686970717273747576777879808182838460 unmodified lines6 unmodified linesimport {validateGracefulCancel} from '../terminate/graceful.js';import {validateTimeout} from '../terminate/timeout.js';import {handleNodeOption} from '../methods/node.js';import {validateIpcInputOption} from '../ipc/ipc-input.js';import {checkBooleanOption} from '../utils/options.js';import {validateEncoding, BINARY_ENCODINGS} from './encoding-option.js';import {parseCommandFile} from './command-file.js';import {normalizeCwd} from './cwd.js';import {normalizeFileUrl} from './file-url.js';9 unmodified lines sanitizedOptions.cwd = normalizeCwd(sanitizedOptions.cwd); const [processedFile, processedArguments, processedOptions] = handleNodeOption(filePath, rawArguments, sanitizedOptions); const fdOptions = normalizeFdSpecificOptions(processedOptions); const options = addDefaultOptions(fdOptions); validateBooleanOptions(options); validateEnv(options); options.env = getEnv(options);
const {file, commandArguments} = parseCommandFile(processedFile, processedArguments, options);
16 unmodified lines
return {file, commandArguments, options};};
const BOOLEAN_OPTIONS = [ 'extendEnv', 'preferLocal', 'reject', 'cleanup', 'killDescendants', 'all', 'gracefulCancel', 'ipc', 'node',];
// Wrong types must be reported instead of being silently coerced, e.g. the string 'false' enabling an optionconst validateBooleanOptions = options => { for (const optionName of BOOLEAN_OPTIONS) { checkBooleanOption(options[optionName], optionName); }};
// A non-object `env` would be spread into unrelated properties, e.g. its characters when a stringconst validateEnv = ({env}) => { if (env !== undefined && (typeof env !== 'object' || env === null || Array.isArray(env))) { throw new TypeError(`The \`env\` option must be an object: ${String(env)}.`); }};
// Use null prototype to prevent prototype pollution from leaking throughconst addDefaultOptions = ({ extendEnv = true, preferLocal = false,60 unmodified linesmodified:lib/arguments/specific.js+22 added-3 removed
1 import {debuglog} from 'node:util';2 import isPlainObject from 'is-plain-obj';3 import {STANDARD_STREAMS_ALIASES} from '../utils/standard-stream.js';4+import {checkBooleanOption} from '../utils/options.js';5 6 // Some options can have different values for `stdout`/`stderr`/`fd3`.7 // This normalizes those to array of values.8 // For example, `{verbose: {stdout: 'none', stderr: 'full'}}` becomes `{verbose: ['none', 'none', 'full']}`18 unmodified lines27 const getStdioLength = ({stdio}) => Array.isArray(stdio)28 ? Math.max(stdio.length, STANDARD_STREAMS_ALIASES.length)29 : STANDARD_STREAMS_ALIASES.length;30 30-const normalizeFdSpecificValue = (optionValue, optionArray, optionName, stdioLength) => isPlainObject(optionValue)31- ? normalizeOptionObject(optionValue, optionArray, optionName, stdioLength)32- : optionArray.fill(optionValue);31+const normalizeFdSpecificValue = (optionValue, optionArray, optionName, stdioLength) => {32+ if (isPlainObject(optionValue)) {33+ return normalizeOptionObject(optionValue, optionArray, optionName, stdioLength);34+ }35 36+ validateFdSpecificValue(optionValue, optionName);37+ return optionArray.fill(optionValue);38+};39+40 const normalizeOptionObject = (optionValue, optionArray, optionName, stdioLength) => {41 for (const fdName of Object.keys(optionValue).sort(compareFdName)) {42+ validateFdSpecificValue(optionValue[fdName], optionName, `${optionName}.${fdName}`);43 for (const fdNumber of parseFdName(fdName, optionName, stdioLength)) {44 optionArray[fdNumber] = optionValue[fdName];45 }46 }52 unmodified lines99 const addDefaultValue = (optionArray, optionName) => optionArray.map(optionValue => optionValue === undefined100 ? DEFAULT_OPTIONS[optionName]101 : optionValue);102 103+const BOOLEAN_FD_SPECIFIC_OPTIONS = new Set(['lines', 'buffer', 'stripFinalNewline']);104+105+// Wrong types must be reported instead of being silently coerced, e.g. a truthy string enabling the `buffer` option.106+// `undefined` uses the default value.107+const validateFdSpecificValue = (optionValue, optionName, fullOptionName = optionName) => {108+ if (BOOLEAN_FD_SPECIFIC_OPTIONS.has(optionName)) {109+ checkBooleanOption(optionValue, fullOptionName);110+ } else if (optionName === 'maxBuffer' && optionValue !== undefined && (typeof optionValue !== 'number' || Number.isNaN(optionValue))) {111+ throw new TypeError(`The \`${fullOptionName}\` option must use a number.`);112+ }113+};114+115 // Default value for the `verbose` option116 const verboseDefault = debuglog('execa').enabled ? 'full' : 'none';117 118 const DEFAULT_OPTIONS = {14 unmodified linesmodified:lib/convert/duplex.js+3 added-1 removed
1 import {Duplex} from 'node:stream';2 import {callbackify} from 'node:util';3 import {BINARY_ENCODINGS} from '../arguments/encoding-option.js';4-import {copyOptions} from '../utils/options.js';4+import {copyOptions, checkBooleanOption} from '../utils/options.js';5 import {6 getSubprocessStdout,7 getReadableOptions,8 getReadableMethods,9 unmodified lines18 19 // Create a `Duplex` stream combining both `subprocess.readable()` and `subprocess.writable()`20 export const createDuplex = ({subprocess, concurrentStreams, encoding}, options) => {21 const {from, to, binary: binaryOption = true, preserveNewlines = true} = copyOptions(options);22+ checkBooleanOption(binaryOption, 'binary');23+ checkBooleanOption(preserveNewlines, 'preserveNewlines');24 const binary = binaryOption || BINARY_ENCODINGS.has(encoding);25 const {subprocessStdout, waitReadableDestroy} = getSubprocessStdout(subprocess, from, concurrentStreams);26 const {subprocessStdin, waitWritableFinal, waitWritableDestroy} = getSubprocessStdin(subprocess, to, concurrentStreams);27 const {readableEncoding, readableObjectMode, readableHighWaterMark} = getReadableOptions(subprocessStdout, binary);46 unmodified linesmodified:lib/convert/iterable.js+3 added-1 removed
1234456789101112131420 unmodified linesimport {BINARY_ENCODINGS} from '../arguments/encoding-option.js';import {getFromStream} from '../arguments/fd-options.js';import {iterateOnSubprocessStream} from '../io/iterate.js';import {copyOptions} from '../utils/options.js';import {copyOptions, checkBooleanOption} from '../utils/options.js';
// Convert the subprocess to an async iterableexport const createIterable = (subprocess, encoding, options) => { const {from, binary: binaryOption = false, preserveNewlines = false} = copyOptions(options); checkBooleanOption(binaryOption, 'binary'); checkBooleanOption(preserveNewlines, 'preserveNewlines'); const binary = binaryOption || BINARY_ENCODINGS.has(encoding); const subprocessStdout = getFromStream(subprocess, from); const onStdoutData = iterateOnSubprocessStream({ subprocessStdout,20 unmodified linesmodified:lib/convert/readable.js+3 added-1 removed
2 unmodified lines3 import {BINARY_ENCODINGS} from '../arguments/encoding-option.js';4 import {getFromStream} from '../arguments/fd-options.js';5 import {iterateOnSubprocessStream, DEFAULT_OBJECT_HIGH_WATER_MARK} from '../io/iterate.js';6 import {createDeferred} from '../utils/deferred.js';7-import {copyOptions} from '../utils/options.js';7+import {copyOptions, checkBooleanOption} from '../utils/options.js';8 import {addConcurrentStream, waitForConcurrentStreams} from './concurrent.js';9 import {10 safeWaitForSubprocessStdin,11 waitForSubprocessStdout,3 unmodified lines15 16 // Create a `Readable` stream that forwards from `stdout` and awaits the subprocess17 export const createReadable = ({subprocess, concurrentStreams, encoding}, options) => {18 const {from, binary: binaryOption = true, preserveNewlines = true} = copyOptions(options);19+ checkBooleanOption(binaryOption, 'binary');20+ checkBooleanOption(preserveNewlines, 'preserveNewlines');21 const binary = binaryOption || BINARY_ENCODINGS.has(encoding);22 const {subprocessStdout, waitReadableDestroy} = getSubprocessStdout(subprocess, from, concurrentStreams);23 const {readableEncoding, readableObjectMode, readableHighWaterMark} = getReadableOptions(subprocessStdout, binary);24 const {read, onStdoutDataDone} = getReadableMethods({110 unmodified linesmodified:lib/ipc/send.js+2 added-1 removed
1 import {promisify} from 'node:util';2-import {copyOptions} from '../utils/options.js';2+import {copyOptions, checkBooleanOption} from '../utils/options.js';3 import {4 validateIpcMethod,5 handleEpipeError,6 handleSerializationError,7 unmodified lines14 // Users would still need to `await subprocess` after the method is done.15 // Also, this would prevent `unhandledRejection` event from being emitted, making it silent.16 export const sendMessage = ({anyProcess, channel, isSubprocess, ipc}, message, options) => {17 const {strict = false} = copyOptions(options);18+ checkBooleanOption(strict, 'strict');19 const methodName = 'sendMessage';20 validateIpcMethod({21 methodName,22 isSubprocess,74 unmodified linesmodified:lib/methods/node.js+4 added
47 unmodified lines48 if (formerNodePath !== undefined) {49 throw new TypeError('The "execPath" option has been removed. Please use the "nodePath" option instead.');50 }51 52+ if (!Array.isArray(nodeOptions) || nodeOptions.some(nodeOption => typeof nodeOption !== 'string')) {53+ throw new TypeError('The "nodeOptions" option must be an array of strings.');54+ }55+56 const normalizedNodePath = safeNormalizeFileUrl(nodePath, 'The "nodePath" option');57 const resolvedNodePath = path.resolve(cwd, normalizedNodePath);58 // Use spread (which only copies own properties) to safely get shell without reading polluted prototype59 const newOptions = {31 unmodified linesmodified:lib/methods/parameters.js+10 added-2 removed
1 unmodified line2 import {safeNormalizeFileUrl} from '../arguments/file-url.js';3 4 // The command `arguments` and `options` are both optional.5 // This also does basic validation on them and on the command file.6-export const normalizeParameters = (rawFile, rawArguments = [], rawOptions = {}) => {6+export const normalizeParameters = (rawFile, rawArguments = [], rawOptions, ...rawExtraArguments) => {7+ if (rawExtraArguments.length > 0) {8+ throw new TypeError('Execa accepts at most three arguments: file, arguments, options.');9+ }10+11+ if (rawOptions !== undefined && isPlainObject(rawArguments)) {12+ throw new TypeError('Execa accepts at most one options object. Please merge the second and third arguments.');13+ }14+15 const filePath = safeNormalizeFileUrl(rawFile, 'First argument');8- const [commandArguments, options] = isPlainObject(rawArguments)16+ const [commandArguments, options = {}] = isPlainObject(rawArguments)17 ? [[], rawArguments]18 : [rawArguments, rawOptions];19 20 if (!Array.isArray(commandArguments)) {20 unmodified linesmodified:lib/methods/template.js+3 added-2 removed
1 unmodified line2 import isPlainObject from 'is-plain-obj';3 import {ASTRAL_START} from '../arguments/escape.js';4 import {isUint8Array, uint8ArrayToString} from '../utils/uint-array.js';5 import {isExecaError} from '../return/final-error.js';6+import {getTypeName} from '../utils/type-name.js';7 8 // Check whether the template string syntax is being used9 export const isTemplateString = templates => Array.isArray(templates) && Array.isArray(templates.raw);10 128 unmodified lines139 ];140 141 // Handle `${expression}` inside the template string syntax142 const parseExpression = expression => {142- const typeOfExpression = typeof expression;143+ const typeOfExpression = getTypeName(expression);144 145 if (typeOfExpression === 'string') {146 return expression;147 }30 unmodified lines178 if (stdout === undefined) {179 throw new TypeError('Missing result.stdout in template expression. This is probably due to the previous subprocess\' "stdout" option.');180 }181 181- throw new TypeError(`Unexpected "${typeof stdout}" stdout in template expression`);182+ throw new TypeError(`Unexpected "${getTypeName(stdout)}" stdout in template expression`);183 };modified:lib/pipe/pipe-arguments.js+2 added
1 unmodified line2 import {getStartTime} from '../return/duration.js';3 import {SUBPROCESS_OPTIONS, getToStream, getFromStream} from '../arguments/fd-options.js';4 import {isDenoExecPath} from '../arguments/file-url.js';5 import {copyOptions} from '../utils/options.js';6+import {validateAbortSignal} from '../utils/abort-signal.js';7 8 // Normalize and validate arguments passed to `source.pipe(destination)`9 export const normalizePipeArguments = ({source, sourcePromise, boundOptions, createNested}, ...pipeArguments) => {10 const startTime = getStartTime();33 unmodified lines44 const {destination, pipeOptions} = destinationInfo;45 46 try {47 const {from, to, unpipeSignal} = copyOptions(pipeOptions);48+ validateAbortSignal(unpipeSignal, 'unpipeSignal');49 const destinationStream = getToStream(destination, to);50 return {51 destination,52 destinationStream,73 unmodified linesmodified:lib/stdio/handle.js+29 added-3 removed
1+import {isStream as isNodeStream} from 'is-stream';2 import {getStreamName, isStandardStream} from '../utils/standard-stream.js';3+import {checkBooleanOption} from '../utils/options.js';4 import {normalizeTransforms} from '../transform/normalize.js';5 import {getFdObjectMode} from '../transform/object-mode.js';6 import {7 getStdioItemType,8 isRegularUrl,9 isUnknownStdioString,10 isStdioValueObject,9- checkBooleanOption,11 FILE_TYPES,12 } from './type.js';13 import {getStreamDirection} from './direction.js';14 import {normalizeStdioOption} from './stdio-option.js';62 unmodified lines77 78 const stdioItems = filterDuplicates(initialStdioItems);79 const isStdioArray = stdioItems.length > 1;80 validateStdioArray(stdioItems, isStdioArray, optionName);80- validateStreams(stdioItems);81+ validateStreams(stdioItems, isStdioArray);82 return {stdioItems, isStdioArray};83 };84 85 const omitInheritedStdin = (stdioItems, inputStdioItems) => inputStdioItems.length > 0 && isInheritedStdinOnly(stdioItems)47 unmodified lines133 // Using the `ignore` value together with others for the same stream does not make sense, so we make it fail.134 // However, we do allow it if the array has a single item.135 const INVALID_STDIO_ARRAY_OPTIONS = new Set(['ignore']);136 136-const validateStreams = stdioItems => {137+const validateStreams = (stdioItems, isStdioArray) => {138 for (const stdioItem of stdioItems) {139 validateFileStdio(stdioItem);140 validateFileDescriptorStdio(stdioItem);141+ validateNativeStdio(stdioItem, isStdioArray);142 }143 };144 145 // 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.5 unmodified lines151 152 // `node:child_process` converts file descriptors to a 32-bit signed integer, and aborts the process when it cannot153 const MAX_FILE_DESCRIPTOR = (2 ** 31) - 1;154 155+// 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.159+const validateNativeStdio = ({type, value, optionName}, isStdioArray) => {160+ if (type !== 'native') {161+ return;162+ }163+164+ if (isFileHandle(value)) {165+ if (isStdioArray) {166+ throw new TypeError(`The \`${optionName}\` option cannot combine file handles with other values.`);167+ }168+169+ return;170+ }171+172+ 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+};176+177+const isFileHandle = value => typeof value?.fd === 'number' && !isNodeStream(value, {checkOpen: false});178+179 const validateFileStdio = ({type, value, optionName}) => {180 if (isRegularUrl(value)) {181 throw new TypeError(`The \`${optionName}: URL\` option must use the \`file:\` scheme.182 For example, you can use the \`pathToFileURL()\` method of the \`url\` core module.`);111 unmodified linesmodified:lib/stdio/stdio-option.js+2 added-1 removed
1 import {STANDARD_STREAMS_ALIASES} from '../utils/standard-stream.js';2 import {normalizeIpcStdioArray} from '../ipc/array.js';3 import {isFullVerbose} from '../verbose/values.js';4+import {getTypeName} from '../utils/type-name.js';5 import {isStdioValueObject} from './type.js';6 7 // Add support for `stdin`/`stdout`/`stderr` as an alias for `stdio`.8 // Also normalize the `stdio` option.31 unmodified lines40 return [stdio, stdio, stdio];41 }42 43 if (!Array.isArray(stdio)) {43- throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``);44+ throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${getTypeName(stdio)}\``);45 }46 47 const length = Math.max(stdio.length, STANDARD_STREAMS_ALIASES.length);48 return Array.from({length}, (_, fdNumber) => stdio[fdNumber]);43 unmodified linesmodified:lib/stdio/type.js+1 added-6 removed
1 import {isStream as isNodeStream, isDuplexStream} from 'is-stream';2 import isPlainObj from 'is-plain-obj';3 import {isUint8Array} from '../utils/uint-array.js';4+import {checkBooleanOption} from '../utils/options.js';5 6 // The `stdin`/`stdout`/`stderr` option can be of many types. This detects it.7 export const getStdioItemType = (value, optionName) => {8 if (isAsyncGenerator(value)) {91 unmodified lines100 101 return isAsyncGenerator(transform) || isAsyncGenerator(final) ? 'asyncGenerator' : 'generator';102 };103 103-export const checkBooleanOption = (value, optionName) => {104- if (value !== undefined && typeof value !== 'boolean') {105- throw new TypeError(`The \`${optionName}\` option must use a boolean.`);106- }107-};108-104 const isGenerator = value => isAsyncGenerator(value) || isSyncGenerator(value);105 export const isAsyncGenerator = value => Object.prototype.toString.call(value) === '[object AsyncGeneratorFunction]';106 const isSyncGenerator = value => Object.prototype.toString.call(value) === '[object GeneratorFunction]';107 const isTransformOptions = value => isPlainObj(value)61 unmodified linesmodified:lib/terminate/cancel.js+2 added-4 removed
1-import {onAbortedSignal} from '../utils/abort-signal.js';1+import {onAbortedSignal, validateAbortSignal} from '../utils/abort-signal.js';2 3 // Validate the `cancelSignal` option4 export const validateCancelSignal = ({cancelSignal}) => {5- if (cancelSignal !== undefined && Object.prototype.toString.call(cancelSignal) !== '[object AbortSignal]') {6- throw new Error(`The \`cancelSignal\` option must be an AbortSignal: ${String(cancelSignal)}`);7- }5+ validateAbortSignal(cancelSignal, 'cancelSignal');6 };7 8 // The `signal` option was renamed to `cancelSignal`. Validated for every method, otherwise synchronous methods would silently ignore it, since `child_process.spawnSync()` does not support that option either.9 export const validateRenamedSignalOption = ({signal}) => {16 unmodified linesmodified:lib/terminate/kill.js+2 added-5 removed
1 import {setTimeout} from 'node:timers/promises';2 import {isErrorInstance} from '../return/final-error.js';3 import {normalizeSignalArgument} from './signal.js';4-import {isValidDelay, MAX_DELAY} from './timeout.js';4+import {validateDelay} from './timeout.js';5 6 // Normalize the `forceKillAfterDelay` option7 export const normalizeForceKillAfterDelay = forceKillAfterDelay => {8 if (forceKillAfterDelay === false) {3 unmodified lines12 if (forceKillAfterDelay === true) {13 return DEFAULT_FORCE_KILL_TIMEOUT;14 }15 16- if (!isValidDelay(forceKillAfterDelay)) {17- throw new TypeError(`Expected the \`forceKillAfterDelay\` option to be a non-negative integer up to ${MAX_DELAY}, got \`${forceKillAfterDelay}\` (${typeof forceKillAfterDelay})`);18- }19-16+ validateDelay(forceKillAfterDelay, 'forceKillAfterDelay');17 return forceKillAfterDelay;18 };19 20 const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5;71 unmodified linesmodified:lib/terminate/timeout.js+11 added-5 removed
1 import {setTimeout} from 'node:timers/promises';2 import {DiscardedError} from '../return/final-error.js';3+import {getTypeName} from '../utils/type-name.js';4 5 // Validate `timeout` option6 export const validateTimeout = ({timeout}) => {6- if (timeout !== undefined && !isValidDelay(timeout)) {7- throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer up to ${MAX_DELAY}, got \`${timeout}\` (${typeof timeout})`);7+ if (timeout !== undefined) {8+ validateDelay(timeout, 'timeout');9 }10 };11 12+// Used by the `timeout` and `forceKillAfterDelay` options.11-// Fractional numbers are excluded since `spawnSync()` requires an integer `timeout`12-export const isValidDelay = delay => Number.isInteger(delay) && delay >= 0 && delay <= MAX_DELAY;13+// Fractional numbers are excluded since `spawnSync()` requires an integer `timeout`.14+export const validateDelay = (delay, optionName) => {15+ if (!Number.isInteger(delay) || delay < 0 || delay > MAX_DELAY) {16+ throw new TypeError(`Expected the \`${optionName}\` option to be a non-negative integer up to ${MAX_DELAY}, got \`${delay}\` (${getTypeName(delay)})`);17+ }18+};19 20 // Timers fire right away when their delay is larger than this15-export const MAX_DELAY = (2 ** 31) - 1;21+const MAX_DELAY = (2 ** 31) - 1;22 23 // Fails when the `timeout` option is exceeded24 export const throwOnTimeout = (kill, timeout, context, controller) => timeout === 0 || timeout === undefined25 ? []8 unmodified linesmodified:lib/utils/abort-signal.js+7 added
4 unmodified lines5 if (!mainSignal.aborted) {6 await once(mainSignal, 'abort', {signal: stopSignal});7 }8 };9+10+// Validate the `cancelSignal` and `unpipeSignal` options, so a wrong type fails right away instead of failing later with an unrelated error11+export const validateAbortSignal = (signal, optionName) => {12+ if (signal !== undefined && Object.prototype.toString.call(signal) !== '[object AbortSignal]') {13+ throw new TypeError(`The \`${optionName}\` option must be an AbortSignal: ${String(signal)}.`);14+ }15+};modified:lib/utils/options.js+6 added
5 unmodified lines6 }7 8 return {__proto__: null, ...options};9 };10+11+export const checkBooleanOption = (value, optionName) => {12+ if (value !== undefined && typeof value !== 'boolean') {13+ throw new TypeError(`The \`${optionName}\` option must use a boolean.`);14+ }15+};added:lib/utils/type-name.js+2 added
1+// Like `typeof`, but `null` is reported as `null` instead of `object`, so error messages name the actual value2+export const getTypeName = value => value === null ? 'null' : typeof value;modified:test/convert/duplex.js+4 added
207 unmodified lines208 assert.equal(stream.writableHighWaterMark, defaultHighWaterMark);209 stream.end();210 await text(stream);211 });212+213+test('The "binary" duplex option must use a boolean', () => {214+ assert.throws(() => execa('noop.js').duplex({binary: 'true'}), {message: /`binary` option must use a boolean/});215+});modified:test/convert/iterable.js+8 added
152 unmodified lines153 154 test('Propagate stdout abort', () => testStdoutError(subprocessStdout => subprocessStdout.destroy(), true));155 test('Propagate stdout error', () => testStdoutError((subprocessStdout, cause) => subprocessStdout.destroy(cause), false, new Error(foobarString)));156 test('Propagate stdout "error" event', () => testStdoutError((subprocessStdout, cause) => subprocessStdout.emit('error', cause), true, new Error(foobarString)));157+158+test('The "binary" iterable option must use a boolean', () => {159+ assert.throws(() => execa('noop.js').iterable({binary: 'true'}), {message: /`binary` option must use a boolean/});160+});161+162+test('The "preserveNewlines" iterable option must use a boolean', () => {163+ assert.throws(() => execa('noop.js').iterable({preserveNewlines: 'true'}), {message: /`preserveNewlines` option must use a boolean/});164+});modified:test/convert/readable.js+8 added
491 unmodified lines492 };493 494 test('.readable() with big output', () => testBigOutput('readable'));495 test('.duplex() with big output', () => testBigOutput('duplex'));496+497+test('The "binary" readable option must use a boolean', () => {498+ assert.throws(() => execa('noop.js').readable({binary: 'true'}), {message: /`binary` option must use a boolean/});499+});500+501+test('The "preserveNewlines" readable option must use a boolean', () => {502+ assert.throws(() => execa('noop.js').readable({preserveNewlines: 'true'}), {message: /`preserveNewlines` option must use a boolean/});503+});modified:test/ipc/send.js+6 added
151 unmodified lines152 assert.equal(isTerminated, false);153 assert.ok(message.includes(`Error: ${foobarString}`));154 assert.deepEqual(ipcOutput, []);155 });156+157+test('The "strict" sendMessage() option must use a boolean', async () => {158+ const subprocess = execa('empty.js', {ipc: true});159+ assert.throws(() => subprocess.sendMessage(foobarString, {strict: 'true'}), {message: /`strict` option must use a boolean/});160+ await subprocess;161+});modified:test/methods/node.js+8 added
201 unmodified lines202 test('The "nodeOptions" option can be used - execaNode()', () => testNodeOptions(execaNode));203 test('The "nodeOptions" option can be used - "node" option', () => testNodeOptions(runWithNodeOption));204 test('The "nodeOptions" option can be used - "node" option sync', () => testNodeOptions(runWithNodeOptionSync));205 206+test('The "nodeOptions" option must be an array of strings', () => {207+ assertThrows(() => execaNode('empty.js', {nodeOptions: '--version'}), {instanceOf: TypeError, message: /The "nodeOptions" option must be an array of strings/});208+});209+210+test('The "nodeOptions" option items must be strings', () => {211+ assertThrows(() => execaNode('empty.js', {nodeOptions: ['--version', 5]}), {instanceOf: TypeError, message: /The "nodeOptions" option must be an array of strings/});212+});213+214 const spawnNestedExecaNode = (realExecArgv, fakeExecArgv, execaMethod, nodeOptions) => execa(215 'node',216 [...realExecArgv, 'nested-node.js', fakeExecArgv, execaMethod, nodeOptions, 'noop.js', foobarString],217 {...fullStdio, cwd: FIXTURES_DIRECTORY},148 unmodified linesmodified:test/methods/parameters-options.js+85 added
64 unmodified lines65 execaMethod('echo', [], new Map());66 }, {message: /Last argument must be an options object/});67 };68 69+const testTwoOptionsObjects = execaMethod => {70+ assertThrows(() => {71+ execaMethod('echo', {all: true}, {timeout: 1});72+ }, {message: /Please merge the second and third arguments/});73+};74+75+test('execa() rejects two options objects', () => testTwoOptionsObjects(execa));76+test('execaSync() rejects two options objects', () => testTwoOptionsObjects(execaSync));77+test('execaNode() rejects two options objects', () => testTwoOptionsObjects(execaNode));78+test('$ rejects two options objects', () => testTwoOptionsObjects($));79+test('$.sync rejects two options objects', () => testTwoOptionsObjects($.sync));80+81+const testFourthArgument = execaMethod => {82+ assertThrows(() => {83+ execaMethod('echo', ['foo'], {}, {});84+ }, {message: /at most three arguments/});85+};86+87+test('execa() rejects a fourth argument', () => testFourthArgument(execa));88+test('execaSync() rejects a fourth argument', () => testFourthArgument(execaSync));89+90 test('execa()\'s third argument must be a plain object', () => testInvalidOptions(execa));91 test('execaSync()\'s third argument must be a plain object', () => testInvalidOptions(execaSync));92 test('execaNode()\'s third argument must be a plain object', () => testInvalidOptions(execaNode));93 test('$\'s third argument must be a plain object', () => testInvalidOptions($));94 test('$.sync\'s third argument must be a plain object', () => testInvalidOptions($.sync));95+96+const testInvalidFdSpecificOption = (execaMethod, optionName, optionValue, fdName = 'stdout') => {97+ assertThrows(() => {98+ execaMethod('noop.js', {[optionName]: {[fdName]: optionValue}});99+ }, {instanceOf: TypeError, message: `The \`${optionName}.${fdName}\` option must use ${optionName === 'maxBuffer' ? 'a number' : 'a boolean'}.`});100+};101+102+test('The "lines.stdout" option must be a boolean', () => testInvalidFdSpecificOption(execa, 'lines', 'true'));103+test('The "buffer.stdout" option must be a boolean', () => testInvalidFdSpecificOption(execa, 'buffer', 'false'));104+test('The "stripFinalNewline.stdout" option must be a boolean', () => testInvalidFdSpecificOption(execa, 'stripFinalNewline', 1));105+test('The "maxBuffer.stdout" option must be a number', () => testInvalidFdSpecificOption(execa, 'maxBuffer', '1024'));106+test('The "maxBuffer.stdout" option must not be NaN', () => testInvalidFdSpecificOption(execa, 'maxBuffer', NaN));107+test('The "maxBuffer.stderr" option must be a number - sync', () => testInvalidFdSpecificOption(execaSync, 'maxBuffer', '1024', 'stderr'));108+test('The "lines.all" option is reported as "lines.all"', () => testInvalidFdSpecificOption(execa, 'lines', 'true', 'all'));109+test('The "buffer.ipc" option is reported as "buffer.ipc"', () => testInvalidFdSpecificOption(execaNode, 'buffer', 'false', 'ipc'));110+111+const testInfiniteMaxBuffer = async (execaMethod, maxBuffer) => {112+ const {stdout} = await execaMethod('noop.js', ['.'.repeat(10)], {maxBuffer});113+ assert.equal(stdout, '.'.repeat(10));114+};115+116+test('The "maxBuffer" option can be Infinity', () => testInfiniteMaxBuffer(execa, Infinity));117+test('The "maxBuffer" option can be Infinity - sync', () => testInfiniteMaxBuffer(execaSync, Infinity));118+test('The "maxBuffer.stdout" option can be Infinity', () => testInfiniteMaxBuffer(execa, {stdout: Infinity}));119+120+const testInvalidBooleanOption = (execaMethod, optionName, optionValue) => {121+ assertThrows(() => {122+ execaMethod('noop.js', {[optionName]: optionValue});123+ }, {instanceOf: TypeError, message: `The \`${optionName}\` option must use a boolean.`});124+};125+126+test('The "all" option must use a boolean', () => testInvalidBooleanOption(execa, 'all', 'false'));127+test('The "reject" option must use a boolean', () => testInvalidBooleanOption(execa, 'reject', 'no'));128+test('The "cleanup" option must use a boolean', () => testInvalidBooleanOption(execa, 'cleanup', 'false'));129+test('The "ipc" option must use a boolean', () => testInvalidBooleanOption(execa, 'ipc', 'yes'));130+test('The "extendEnv" option must use a boolean', () => testInvalidBooleanOption(execa, 'extendEnv', 'false'));131+test('The "preferLocal" option must use a boolean', () => testInvalidBooleanOption(execa, 'preferLocal', 1));132+test('The "node" option must use a boolean', () => testInvalidBooleanOption(execa, 'node', 'yes'));133+test('The "gracefulCancel" option must use a boolean', () => testInvalidBooleanOption(execa, 'gracefulCancel', 'yes'));134+test('The "node" option must use a boolean - sync', () => testInvalidBooleanOption(execaSync, 'node', 'yes'));135+136+const testInvalidEnv = (execaMethod, env) => {137+ assertThrows(() => {138+ execaMethod('noop.js', {env});139+ }, {instanceOf: TypeError, message: `The \`env\` option must be an object: ${String(env)}.`});140+};141+142+test('The "env" option must be an object', () => testInvalidEnv(execa, 'PATH=/bin'));143+test('The "env" option must be an object - sync', () => testInvalidEnv(execaSync, 'PATH=/bin'));144+test('The "env" option must not be null', () => testInvalidEnv(execa, null));145+test('The "env" option must not be an array', () => testInvalidEnv(execa, ['PATH=/bin']));146+test('The "env" option must not be a symbol', () => testInvalidEnv(execa, Symbol('env')));147+148+test('Wrong-typed scalar "maxBuffer" values are reported without a file descriptor', () => {149+ assertThrows(() => {150+ execa('noop.js', {maxBuffer: '1024'});151+ }, {instanceOf: TypeError, message: /^The `maxBuffer` option must use a number\.$/});152+});153+154+test('Wrong-typed scalar "lines" values are reported without a file descriptor', () => {155+ assertThrows(() => {156+ execa('noop.js', {lines: 'true'});157+ }, {instanceOf: TypeError, message: /^The `lines` option must use a boolean\.$/});158+});modified:test/methods/template.js+6 added
384 unmodified lines385 );386 };387 388 test('$ throws on invalid expression - undefined', () => testInvalidExpression(undefined));389+test('$ throws on invalid expression - null mentions null', () => {390+ assertThrows(391+ () => $`echo.js ${null}`,392+ {message: 'Unexpected "null" in template expression'},393+ );394+});395 test('$ throws on invalid expression - null', () => testInvalidExpression(null));396 test('$ throws on invalid expression - true', () => testInvalidExpression(true));397 test('$ throws on invalid expression - {}', () => testInvalidExpression({}));398 test('$ throws on invalid expression - {foo: "bar"}', () => testInvalidExpression({foo: 'bar'}));35 unmodified linesmodified:test/pipe/abort.js+30 added
1 import assert from 'node:assert/strict';2 import {once} from 'node:events';3+import {setTimeout} from 'node:timers/promises';4 import test from 'node:test';5 import {assertRejects, assertLike} from '../helpers/assert.js';6 import {execa} from '../../index.js';7 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';159 unmodified lines167 168 destination.stdin.end(foobarString);169 assertLike(await destination, {stdout: foobarString});170 });171+172+test('The "unpipeSignal" option must be an AbortSignal', async () => {173+ const source = execa('noop.js', [foobarString]);174+ const {cause} = await assertRejects(source.pipe('stdin.js', {unpipeSignal: foobarString}));175+ assert.equal(cause.message, `The \`unpipeSignal\` option must be an AbortSignal: ${foobarString}.`);176+ await source;177+});178+179+// The unpiped destination ending later must not abort the source, which is still piped to the other destination180+test('Unpiping one destination does not affect the other destinations of the same source', async () => {181+ const source = execa('noop-repeat.js', ['1', `${foobarString}\n`]);182+ const unpipedDestination = execa('stdin.js');183+ const receivingDestination = execa('stdin.js');184+ const controller = new AbortController();185+ const pipePromise = source.pipe(unpipedDestination, {unpipeSignal: controller.signal});186+ source.pipe(receivingDestination).catch(() => {});187+188+ controller.abort();189+ await assertRejects(pipePromise);190+ unpipedDestination.stdin.end();191+ await unpipedDestination;192+ await setTimeout(100);193+ source.kill();194+195+ const {isTerminated} = await assertRejects(source);196+ assert.ok(isTerminated);197+ const {stdout} = await receivingDestination;198+ assert.ok(stdout.split('\n').length > 2);199+});modified:test/stdio/file-descriptor.js+9 added
22 unmodified lines23 test('pass `stdout` to a file descriptor - sync', () => testFileDescriptorOption(1, execaSync));24 test('pass `stderr` to a file descriptor - sync', () => testFileDescriptorOption(2, execaSync));25 test('pass `stdio[*]` to a file descriptor - sync', () => testFileDescriptorOption(3, execaSync));26 27+test('pass `stdout` to a file descriptor in a single-item array', async () => {28+ const filePath = tempfile();29+ const fileDescriptor = await open(filePath, 'w');30+ await execa('noop-fd.js', ['1', 'foobar'], {stdout: [fileDescriptor]});31+ assert.equal(await readFile(filePath, 'utf8'), 'foobar');32+ await rm(filePath);33+ await fileDescriptor.close();34+});35+36 const testStdinWrite = async fdNumber => {37 const subprocess = execa('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, 'pipe'));38 subprocess.stdio[fdNumber].end('unicorns');39 const {stdout} = await subprocess;5 unmodified linesmodified:test/stdio/handle-invalid.js+24 added
1 import assert from 'node:assert/strict';2+import {open, rm} from 'node:fs/promises';3 import test from 'node:test';4+import tempfile from 'tempfile';5 import {assertThrows} from '../helpers/assert.js';6 import {execa, execaSync} from '../../index.js';7 import {getStdio} from '../helpers/stdio.js';8 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';92 unmodified lines101 test('Cannot pass a too large file descriptor to stderr', () => testInvalidFileDescriptor(2, 'stderr', 2 ** 32, execa));102 test('Cannot pass a negative file descriptor to stdio[*]', () => testInvalidFileDescriptor(3, 'stdio[3]', -1, execa));103 test('Cannot pass a fractional file descriptor to stdout', () => testInvalidFileDescriptor(1, 'stdout', 1.5, execaSync));104 test('Cannot pass a negative file descriptor to stdin', () => testInvalidFileDescriptor(0, 'stdin', -1, execaSync));105+106+const testUnknownNativeValue = (invalidStdio, fdNumber, execaMethod) => {107+ const {message} = assertThrows(() => {108+ execaMethod('empty.js', getStdio(fdNumber, ['pipe', invalidStdio]));109+ }, {instanceOf: TypeError});110+ assert.ok(message.includes(`option is invalid: ${String(invalidStdio)} (${typeof invalidStdio})`));111+};112+113+test('Cannot pass "true" and another value to stdout', () => testUnknownNativeValue(true, 1, execa));114+test('Cannot pass a plain object and another value to stdout', () => testUnknownNativeValue({}, 1, execa));115+test('Cannot pass "false" and another value to stdin', () => testUnknownNativeValue(false, 0, execa));116+test('Cannot pass "true" and another value to stdout - sync', () => testUnknownNativeValue(true, 1, execaSync));117+118+test('Cannot pass a file handle and another value to stdout', async () => {119+ const filePath = tempfile();120+ const fileHandle = await open(filePath, 'w');121+ assertThrows(() => {122+ execa('empty.js', getStdio(1, ['pipe', fileHandle]));123+ }, {instanceOf: TypeError, message: /`stdout` option cannot combine file handles with other values/});124+ await fileHandle.close();125+ await rm(filePath);126+});modified:test/stdio/stdio-option.js+1 added
46 unmodified lines47 [{stdin: 0, stderr: 2}, [0, 'pipe', 2]],48 [{stdout: 1, stderr: 2}, ['pipe', 1, 2]],49 50 [{stdio: {foo: 'bar'}}, new TypeError('Expected `stdio` to be of type `string` or `Array`, got `object`')],51+ [{stdio: null}, new TypeError('Expected `stdio` to be of type `string` or `Array`, got `null`')],52 53 [{stdin: 'inherit', stdio: 'pipe'}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`')],54 [{stdin: 'inherit', stdio: ['pipe']}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`')],55 [{stdin: 'inherit', stdio: [undefined, 'pipe']}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`')],6 unmodified linesmodified:test/terminate/kill-force.js+5 added
46 unmodified lines47 }, {instanceOf: TypeError, message: /non-negative integer/});48 };49 50 test('`forceKillAfterDelay` should not be fractional', () => testInvalidForceKill(5000.5));51+test('`forceKillAfterDelay` should not be null', () => {52+ assertThrows(() => {53+ execa('empty.js', {forceKillAfterDelay: null});54+ }, {instanceOf: TypeError, message: /got `null` \(null\)/});55+});56 test('`forceKillAfterDelay` should not be NaN', () => testInvalidForceKill(NaN));57 test('`forceKillAfterDelay` should not be negative', () => testInvalidForceKill(-1));58 // Larger delays make timers fire right away59 test('`forceKillAfterDelay` should not be larger than the maximum timer delay', () => testInvalidForceKill(2 ** 31));170 unmodified linesmodified:test/terminate/timeout.js+5 added
56 unmodified lines57 test('timeout must be a number - sync', () => testTimeoutValidation(false, execaSync));58 // Larger delays make timers fire right away59 test('timeout must not be larger than the maximum timer delay', () => testTimeoutValidation(2 ** 31, execa));60 test('timeout must not be larger than the maximum timer delay - sync', () => testTimeoutValidation(2 ** 31, execaSync));61+test('timeout must not be null', () => {62+ assertThrows(() => {63+ execa('empty.js', {timeout: null});64+ }, {message: /got `null` \(null\)/});65+});66 67 const testMaxTimeout = async execaMethod => {68 const {timedOut} = await execaMethod('noop.js', {timeout: (2 ** 31) - 1});69 assert.equal(timedOut, false);28 unmodified lines