Skip to content
Myr

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

32 files+342 added−35 removed

modified:lib/arguments/options.js+29 added
modified:lib/arguments/specific.js+22 added-3 removed
1import {debuglog} from 'node:util';2import isPlainObject from 'is-plain-obj';3import {STANDARD_STREAMS_ALIASES} from '../utils/standard-stream.js';4import {checkBooleanOption} from '../utils/options.js';56// 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 lines
27const getStdioLength = ({stdio}) => Array.isArray(stdio)28 ? Math.max(stdio.length, STANDARD_STREAMS_ALIASES.length)29 : STANDARD_STREAMS_ALIASES.length;3030const normalizeFdSpecificValue = (optionValue, optionArray, optionName, stdioLength) => isPlainObject(optionValue)31 ? normalizeOptionObject(optionValue, optionArray, optionName, stdioLength)32 : optionArray.fill(optionValue);31const normalizeFdSpecificValue = (optionValue, optionArray, optionName, stdioLength) => {32 if (isPlainObject(optionValue)) {33 return normalizeOptionObject(optionValue, optionArray, optionName, stdioLength);34 }3536 validateFdSpecificValue(optionValue, optionName);37 return optionArray.fill(optionValue);38};3940const 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 lines
99const addDefaultValue = (optionArray, optionName) => optionArray.map(optionValue => optionValue === undefined100 ? DEFAULT_OPTIONS[optionName]101 : optionValue);102103const BOOLEAN_FD_SPECIFIC_OPTIONS = new Set(['lines', 'buffer', 'stripFinalNewline']);104105// 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.107const 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};114115// Default value for the `verbose` option116const verboseDefault = debuglog('execa').enabled ? 'full' : 'none';117118const DEFAULT_OPTIONS = {
14 unmodified lines
modified:lib/convert/duplex.js+3 added-1 removed
1import {Duplex} from 'node:stream';2import {callbackify} from 'node:util';3import {BINARY_ENCODINGS} from '../arguments/encoding-option.js';4import {copyOptions} from '../utils/options.js';4import {copyOptions, checkBooleanOption} from '../utils/options.js';5import {6 getSubprocessStdout,7 getReadableOptions,8 getReadableMethods,
9 unmodified lines
1819// Create a `Duplex` stream combining both `subprocess.readable()` and `subprocess.writable()`20export 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 lines
modified:lib/convert/iterable.js+3 added-1 removed
modified:lib/convert/readable.js+3 added-1 removed
2 unmodified lines
3import {BINARY_ENCODINGS} from '../arguments/encoding-option.js';4import {getFromStream} from '../arguments/fd-options.js';5import {iterateOnSubprocessStream, DEFAULT_OBJECT_HIGH_WATER_MARK} from '../io/iterate.js';6import {createDeferred} from '../utils/deferred.js';7import {copyOptions} from '../utils/options.js';7import {copyOptions, checkBooleanOption} from '../utils/options.js';8import {addConcurrentStream, waitForConcurrentStreams} from './concurrent.js';9import {10 safeWaitForSubprocessStdin,11 waitForSubprocessStdout,
3 unmodified lines
1516// Create a `Readable` stream that forwards from `stdout` and awaits the subprocess17export 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 lines
modified:lib/ipc/send.js+2 added-1 removed
1import {promisify} from 'node:util';2import {copyOptions} from '../utils/options.js';2import {copyOptions, checkBooleanOption} from '../utils/options.js';3import {4 validateIpcMethod,5 handleEpipeError,6 handleSerializationError,
7 unmodified lines
14// 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.16export 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 lines
modified:lib/methods/node.js+4 added
47 unmodified lines
48 if (formerNodePath !== undefined) {49 throw new TypeError('The "execPath" option has been removed. Please use the "nodePath" option instead.');50 }5152 if (!Array.isArray(nodeOptions) || nodeOptions.some(nodeOption => typeof nodeOption !== 'string')) {53 throw new TypeError('The "nodeOptions" option must be an array of strings.');54 }5556 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 lines
modified:lib/methods/parameters.js+10 added-2 removed
1 unmodified line
2import {safeNormalizeFileUrl} from '../arguments/file-url.js';34// The command `arguments` and `options` are both optional.5// This also does basic validation on them and on the command file.6export const normalizeParameters = (rawFile, rawArguments = [], rawOptions = {}) => {6export 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 }1011 if (rawOptions !== undefined && isPlainObject(rawArguments)) {12 throw new TypeError('Execa accepts at most one options object. Please merge the second and third arguments.');13 }1415 const filePath = safeNormalizeFileUrl(rawFile, 'First argument');8 const [commandArguments, options] = isPlainObject(rawArguments)16 const [commandArguments, options = {}] = isPlainObject(rawArguments)17 ? [[], rawArguments]18 : [rawArguments, rawOptions];1920 if (!Array.isArray(commandArguments)) {
20 unmodified lines
modified:lib/methods/template.js+3 added-2 removed
1 unmodified line
2import isPlainObject from 'is-plain-obj';3import {ASTRAL_START} from '../arguments/escape.js';4import {isUint8Array, uint8ArrayToString} from '../utils/uint-array.js';5import {isExecaError} from '../return/final-error.js';6import {getTypeName} from '../utils/type-name.js';78// Check whether the template string syntax is being used9export const isTemplateString = templates => Array.isArray(templates) && Array.isArray(templates.raw);10
128 unmodified lines
139 ];140141// Handle `${expression}` inside the template string syntax142const parseExpression = expression => {142 const typeOfExpression = typeof expression;143 const typeOfExpression = getTypeName(expression);144145 if (typeOfExpression === 'string') {146 return expression;147 }
30 unmodified lines
178 if (stdout === undefined) {179 throw new TypeError('Missing result.stdout in template expression. This is probably due to the previous subprocess\' "stdout" option.');180 }181181 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 line
2import {getStartTime} from '../return/duration.js';3import {SUBPROCESS_OPTIONS, getToStream, getFromStream} from '../arguments/fd-options.js';4import {isDenoExecPath} from '../arguments/file-url.js';5import {copyOptions} from '../utils/options.js';6import {validateAbortSignal} from '../utils/abort-signal.js';78// Normalize and validate arguments passed to `source.pipe(destination)`9export const normalizePipeArguments = ({source, sourcePromise, boundOptions, createNested}, ...pipeArguments) => {10 const startTime = getStartTime();
33 unmodified lines
44 const {destination, pipeOptions} = destinationInfo;4546 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 lines
modified:lib/stdio/handle.js+29 added-3 removed
1import {isStream as isNodeStream} from 'is-stream';2import {getStreamName, isStandardStream} from '../utils/standard-stream.js';3import {checkBooleanOption} from '../utils/options.js';4import {normalizeTransforms} from '../transform/normalize.js';5import {getFdObjectMode} from '../transform/object-mode.js';6import {7 getStdioItemType,8 isRegularUrl,9 isUnknownStdioString,10 isStdioValueObject,9 checkBooleanOption,11 FILE_TYPES,12} from './type.js';13import {getStreamDirection} from './direction.js';14import {normalizeStdioOption} from './stdio-option.js';
62 unmodified lines
7778 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};8485const omitInheritedStdin = (stdioItems, inputStdioItems) => inputStdioItems.length > 0 && isInheritedStdinOnly(stdioItems)
47 unmodified lines
133// 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.135const INVALID_STDIO_ARRAY_OPTIONS = new Set(['ignore']);136136const validateStreams = stdioItems => {137const validateStreams = (stdioItems, isStdioArray) => {138 for (const stdioItem of stdioItems) {139 validateFileStdio(stdioItem);140 validateFileDescriptorStdio(stdioItem);141 validateNativeStdio(stdioItem, isStdioArray);142 }143};144145// 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 lines
151152// `node:child_process` converts file descriptors to a 32-bit signed integer, and aborts the process when it cannot153const MAX_FILE_DESCRIPTOR = (2 ** 31) - 1;154155// 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});178179const 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.`);
111 unmodified lines
modified:lib/stdio/stdio-option.js+2 added-1 removed
1import {STANDARD_STREAMS_ALIASES} from '../utils/standard-stream.js';2import {normalizeIpcStdioArray} from '../ipc/array.js';3import {isFullVerbose} from '../verbose/values.js';4import {getTypeName} from '../utils/type-name.js';5import {isStdioValueObject} from './type.js';67// Add support for `stdin`/`stdout`/`stderr` as an alias for `stdio`.8// Also normalize the `stdio` option.
31 unmodified lines
40 return [stdio, stdio, stdio];41 }4243 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 }4647 const length = Math.max(stdio.length, STANDARD_STREAMS_ALIASES.length);48 return Array.from({length}, (_, fdNumber) => stdio[fdNumber]);
43 unmodified lines
modified:lib/stdio/type.js+1 added-6 removed
1import {isStream as isNodeStream, isDuplexStream} from 'is-stream';2import isPlainObj from 'is-plain-obj';3import {isUint8Array} from '../utils/uint-array.js';4import {checkBooleanOption} from '../utils/options.js';56// The `stdin`/`stdout`/`stderr` option can be of many types. This detects it.7export const getStdioItemType = (value, optionName) => {8 if (isAsyncGenerator(value)) {
91 unmodified lines
100101 return isAsyncGenerator(transform) || isAsyncGenerator(final) ? 'asyncGenerator' : 'generator';102};103103export const checkBooleanOption = (value, optionName) => {104 if (value !== undefined && typeof value !== 'boolean') {105 throw new TypeError(`The \`${optionName}\` option must use a boolean.`);106 }107};108104const isGenerator = value => isAsyncGenerator(value) || isSyncGenerator(value);105export const isAsyncGenerator = value => Object.prototype.toString.call(value) === '[object AsyncGeneratorFunction]';106const isSyncGenerator = value => Object.prototype.toString.call(value) === '[object GeneratorFunction]';107const isTransformOptions = value => isPlainObj(value)
61 unmodified lines
modified:lib/terminate/cancel.js+2 added-4 removed
1import {onAbortedSignal} from '../utils/abort-signal.js';1import {onAbortedSignal, validateAbortSignal} from '../utils/abort-signal.js';23// Validate the `cancelSignal` option4export 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};78// 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.9export const validateRenamedSignalOption = ({signal}) => {
16 unmodified lines
modified:lib/terminate/kill.js+2 added-5 removed
1import {setTimeout} from 'node:timers/promises';2import {isErrorInstance} from '../return/final-error.js';3import {normalizeSignalArgument} from './signal.js';4import {isValidDelay, MAX_DELAY} from './timeout.js';4import {validateDelay} from './timeout.js';56// Normalize the `forceKillAfterDelay` option7export const normalizeForceKillAfterDelay = forceKillAfterDelay => {8 if (forceKillAfterDelay === false) {
3 unmodified lines
12 if (forceKillAfterDelay === true) {13 return DEFAULT_FORCE_KILL_TIMEOUT;14 }1516 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 }1916 validateDelay(forceKillAfterDelay, 'forceKillAfterDelay');17 return forceKillAfterDelay;18};1920const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5;
71 unmodified lines
modified:lib/terminate/timeout.js+11 added-5 removed
1import {setTimeout} from 'node:timers/promises';2import {DiscardedError} from '../return/final-error.js';3import {getTypeName} from '../utils/type-name.js';45// Validate `timeout` option6export 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};1112// Used by the `timeout` and `forceKillAfterDelay` options.11// Fractional numbers are excluded since `spawnSync()` requires an integer `timeout`12export const isValidDelay = delay => Number.isInteger(delay) && delay >= 0 && delay <= MAX_DELAY;13// Fractional numbers are excluded since `spawnSync()` requires an integer `timeout`.14export 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};1920// Timers fire right away when their delay is larger than this15export const MAX_DELAY = (2 ** 31) - 1;21const MAX_DELAY = (2 ** 31) - 1;2223// Fails when the `timeout` option is exceeded24export const throwOnTimeout = (kill, timeout, context, controller) => timeout === 0 || timeout === undefined25 ? []
8 unmodified lines
modified:lib/utils/abort-signal.js+7 added
4 unmodified lines
5 if (!mainSignal.aborted) {6 await once(mainSignal, 'abort', {signal: stopSignal});7 }8};910// Validate the `cancelSignal` and `unpipeSignal` options, so a wrong type fails right away instead of failing later with an unrelated error11export 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 lines
6 }78 return {__proto__: null, ...options};9};1011export 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 value2export const getTypeName = value => value === null ? 'null' : typeof value;
modified:test/convert/duplex.js+4 added
207 unmodified lines
208 assert.equal(stream.writableHighWaterMark, defaultHighWaterMark);209 stream.end();210 await text(stream);211});212213test('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 lines
153154test('Propagate stdout abort', () => testStdoutError(subprocessStdout => subprocessStdout.destroy(), true));155test('Propagate stdout error', () => testStdoutError((subprocessStdout, cause) => subprocessStdout.destroy(cause), false, new Error(foobarString)));156test('Propagate stdout "error" event', () => testStdoutError((subprocessStdout, cause) => subprocessStdout.emit('error', cause), true, new Error(foobarString)));157158test('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});161162test('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 lines
492};493494test('.readable() with big output', () => testBigOutput('readable'));495test('.duplex() with big output', () => testBigOutput('duplex'));496497test('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});500501test('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 lines
152 assert.equal(isTerminated, false);153 assert.ok(message.includes(`Error: ${foobarString}`));154 assert.deepEqual(ipcOutput, []);155});156157test('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 lines
202test('The "nodeOptions" option can be used - execaNode()', () => testNodeOptions(execaNode));203test('The "nodeOptions" option can be used - "node" option', () => testNodeOptions(runWithNodeOption));204test('The "nodeOptions" option can be used - "node" option sync', () => testNodeOptions(runWithNodeOptionSync));205206test('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});209210test('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});213214const 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 lines
modified:test/methods/parameters-options.js+85 added
64 unmodified lines
65 execaMethod('echo', [], new Map());66 }, {message: /Last argument must be an options object/});67};6869const testTwoOptionsObjects = execaMethod => {70 assertThrows(() => {71 execaMethod('echo', {all: true}, {timeout: 1});72 }, {message: /Please merge the second and third arguments/});73};7475test('execa() rejects two options objects', () => testTwoOptionsObjects(execa));76test('execaSync() rejects two options objects', () => testTwoOptionsObjects(execaSync));77test('execaNode() rejects two options objects', () => testTwoOptionsObjects(execaNode));78test('$ rejects two options objects', () => testTwoOptionsObjects($));79test('$.sync rejects two options objects', () => testTwoOptionsObjects($.sync));8081const testFourthArgument = execaMethod => {82 assertThrows(() => {83 execaMethod('echo', ['foo'], {}, {});84 }, {message: /at most three arguments/});85};8687test('execa() rejects a fourth argument', () => testFourthArgument(execa));88test('execaSync() rejects a fourth argument', () => testFourthArgument(execaSync));8990test('execa()\'s third argument must be a plain object', () => testInvalidOptions(execa));91test('execaSync()\'s third argument must be a plain object', () => testInvalidOptions(execaSync));92test('execaNode()\'s third argument must be a plain object', () => testInvalidOptions(execaNode));93test('$\'s third argument must be a plain object', () => testInvalidOptions($));94test('$.sync\'s third argument must be a plain object', () => testInvalidOptions($.sync));9596const 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};101102test('The "lines.stdout" option must be a boolean', () => testInvalidFdSpecificOption(execa, 'lines', 'true'));103test('The "buffer.stdout" option must be a boolean', () => testInvalidFdSpecificOption(execa, 'buffer', 'false'));104test('The "stripFinalNewline.stdout" option must be a boolean', () => testInvalidFdSpecificOption(execa, 'stripFinalNewline', 1));105test('The "maxBuffer.stdout" option must be a number', () => testInvalidFdSpecificOption(execa, 'maxBuffer', '1024'));106test('The "maxBuffer.stdout" option must not be NaN', () => testInvalidFdSpecificOption(execa, 'maxBuffer', NaN));107test('The "maxBuffer.stderr" option must be a number - sync', () => testInvalidFdSpecificOption(execaSync, 'maxBuffer', '1024', 'stderr'));108test('The "lines.all" option is reported as "lines.all"', () => testInvalidFdSpecificOption(execa, 'lines', 'true', 'all'));109test('The "buffer.ipc" option is reported as "buffer.ipc"', () => testInvalidFdSpecificOption(execaNode, 'buffer', 'false', 'ipc'));110111const testInfiniteMaxBuffer = async (execaMethod, maxBuffer) => {112 const {stdout} = await execaMethod('noop.js', ['.'.repeat(10)], {maxBuffer});113 assert.equal(stdout, '.'.repeat(10));114};115116test('The "maxBuffer" option can be Infinity', () => testInfiniteMaxBuffer(execa, Infinity));117test('The "maxBuffer" option can be Infinity - sync', () => testInfiniteMaxBuffer(execaSync, Infinity));118test('The "maxBuffer.stdout" option can be Infinity', () => testInfiniteMaxBuffer(execa, {stdout: Infinity}));119120const testInvalidBooleanOption = (execaMethod, optionName, optionValue) => {121 assertThrows(() => {122 execaMethod('noop.js', {[optionName]: optionValue});123 }, {instanceOf: TypeError, message: `The \`${optionName}\` option must use a boolean.`});124};125126test('The "all" option must use a boolean', () => testInvalidBooleanOption(execa, 'all', 'false'));127test('The "reject" option must use a boolean', () => testInvalidBooleanOption(execa, 'reject', 'no'));128test('The "cleanup" option must use a boolean', () => testInvalidBooleanOption(execa, 'cleanup', 'false'));129test('The "ipc" option must use a boolean', () => testInvalidBooleanOption(execa, 'ipc', 'yes'));130test('The "extendEnv" option must use a boolean', () => testInvalidBooleanOption(execa, 'extendEnv', 'false'));131test('The "preferLocal" option must use a boolean', () => testInvalidBooleanOption(execa, 'preferLocal', 1));132test('The "node" option must use a boolean', () => testInvalidBooleanOption(execa, 'node', 'yes'));133test('The "gracefulCancel" option must use a boolean', () => testInvalidBooleanOption(execa, 'gracefulCancel', 'yes'));134test('The "node" option must use a boolean - sync', () => testInvalidBooleanOption(execaSync, 'node', 'yes'));135136const testInvalidEnv = (execaMethod, env) => {137 assertThrows(() => {138 execaMethod('noop.js', {env});139 }, {instanceOf: TypeError, message: `The \`env\` option must be an object: ${String(env)}.`});140};141142test('The "env" option must be an object', () => testInvalidEnv(execa, 'PATH=/bin'));143test('The "env" option must be an object - sync', () => testInvalidEnv(execaSync, 'PATH=/bin'));144test('The "env" option must not be null', () => testInvalidEnv(execa, null));145test('The "env" option must not be an array', () => testInvalidEnv(execa, ['PATH=/bin']));146test('The "env" option must not be a symbol', () => testInvalidEnv(execa, Symbol('env')));147148test('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});153154test('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 lines
385 );386};387388test('$ throws on invalid expression - undefined', () => testInvalidExpression(undefined));389test('$ throws on invalid expression - null mentions null', () => {390 assertThrows(391 () => $`echo.js ${null}`,392 {message: 'Unexpected "null" in template expression'},393 );394});395test('$ throws on invalid expression - null', () => testInvalidExpression(null));396test('$ throws on invalid expression - true', () => testInvalidExpression(true));397test('$ throws on invalid expression - {}', () => testInvalidExpression({}));398test('$ throws on invalid expression - {foo: "bar"}', () => testInvalidExpression({foo: 'bar'}));
35 unmodified lines
modified:test/pipe/abort.js+30 added
1import assert from 'node:assert/strict';2import {once} from 'node:events';3import {setTimeout} from 'node:timers/promises';4import test from 'node:test';5import {assertRejects, assertLike} from '../helpers/assert.js';6import {execa} from '../../index.js';7import {setFixtureDirectory} from '../helpers/fixtures-directory.js';
159 unmodified lines
167168 destination.stdin.end(foobarString);169 assertLike(await destination, {stdout: foobarString});170});171172test('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});178179// The unpiped destination ending later must not abort the source, which is still piped to the other destination180test('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(() => {});187188 controller.abort();189 await assertRejects(pipePromise);190 unpipedDestination.stdin.end();191 await unpipedDestination;192 await setTimeout(100);193 source.kill();194195 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 lines
23test('pass `stdout` to a file descriptor - sync', () => testFileDescriptorOption(1, execaSync));24test('pass `stderr` to a file descriptor - sync', () => testFileDescriptorOption(2, execaSync));25test('pass `stdio[*]` to a file descriptor - sync', () => testFileDescriptorOption(3, execaSync));2627test('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});3536const 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 lines
modified:test/stdio/handle-invalid.js+24 added
1import assert from 'node:assert/strict';2import {open, rm} from 'node:fs/promises';3import test from 'node:test';4import tempfile from 'tempfile';5import {assertThrows} from '../helpers/assert.js';6import {execa, execaSync} from '../../index.js';7import {getStdio} from '../helpers/stdio.js';8import {setFixtureDirectory} from '../helpers/fixtures-directory.js';
92 unmodified lines
101test('Cannot pass a too large file descriptor to stderr', () => testInvalidFileDescriptor(2, 'stderr', 2 ** 32, execa));102test('Cannot pass a negative file descriptor to stdio[*]', () => testInvalidFileDescriptor(3, 'stdio[3]', -1, execa));103test('Cannot pass a fractional file descriptor to stdout', () => testInvalidFileDescriptor(1, 'stdout', 1.5, execaSync));104test('Cannot pass a negative file descriptor to stdin', () => testInvalidFileDescriptor(0, 'stdin', -1, execaSync));105106const 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};112113test('Cannot pass "true" and another value to stdout', () => testUnknownNativeValue(true, 1, execa));114test('Cannot pass a plain object and another value to stdout', () => testUnknownNativeValue({}, 1, execa));115test('Cannot pass "false" and another value to stdin', () => testUnknownNativeValue(false, 0, execa));116test('Cannot pass "true" and another value to stdout - sync', () => testUnknownNativeValue(true, 1, execaSync));117118test('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 lines
47 [{stdin: 0, stderr: 2}, [0, 'pipe', 2]],48 [{stdout: 1, stderr: 2}, ['pipe', 1, 2]],4950 [{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`')],5253 [{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 lines
modified:test/terminate/kill-force.js+5 added
46 unmodified lines
47 }, {instanceOf: TypeError, message: /non-negative integer/});48};4950test('`forceKillAfterDelay` should not be fractional', () => testInvalidForceKill(5000.5));51test('`forceKillAfterDelay` should not be null', () => {52 assertThrows(() => {53 execa('empty.js', {forceKillAfterDelay: null});54 }, {instanceOf: TypeError, message: /got `null` \(null\)/});55});56test('`forceKillAfterDelay` should not be NaN', () => testInvalidForceKill(NaN));57test('`forceKillAfterDelay` should not be negative', () => testInvalidForceKill(-1));58// Larger delays make timers fire right away59test('`forceKillAfterDelay` should not be larger than the maximum timer delay', () => testInvalidForceKill(2 ** 31));
170 unmodified lines
modified:test/terminate/timeout.js+5 added
56 unmodified lines
57test('timeout must be a number - sync', () => testTimeoutValidation(false, execaSync));58// Larger delays make timers fire right away59test('timeout must not be larger than the maximum timer delay', () => testTimeoutValidation(2 ** 31, execa));60test('timeout must not be larger than the maximum timer delay - sync', () => testTimeoutValidation(2 ** 31, execaSync));61test('timeout must not be null', () => {62 assertThrows(() => {63 execa('empty.js', {timeout: null});64 }, {message: /got `null` \(null\)/});65});6667const testMaxTimeout = async execaMethod => {68 const {timedOut} = await execaMethod('noop.js', {timeout: (2 ** 31) - 1});69 assert.equal(timedOut, false);
28 unmodified lines