Rename files (#977)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent d7c6853 · Browse files · 229 files·+9834 added−9835 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
229 files+9834 added−9835 removed
- tests:+7087 added−7088 removed
- other:+2747 added−2747 removed
Provenance
- Commit
4b2e316- Tree
6e98292- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
d7c6853
229 files changed+9834 added−9835 removed
deleted:lib/arguments/create.js-64 removed
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364import isPlainObject from 'is-plain-obj';import {execaCoreAsync} from '../async.js';import {execaCoreSync} from '../sync.js';import {normalizeArguments} from './normalize.js';import {isTemplateString, parseTemplates} from './template.js';import {FD_SPECIFIC_OPTIONS} from './specific.js';
export const createExeca = (mapArguments, boundOptions, deepOptions, setBoundExeca) => { const createNested = (mapArguments, boundOptions, setBoundExeca) => createExeca(mapArguments, boundOptions, deepOptions, setBoundExeca); const boundExeca = (...args) => callBoundExeca({mapArguments, deepOptions, boundOptions, setBoundExeca, createNested}, ...args);
if (setBoundExeca !== undefined) { setBoundExeca(boundExeca, createNested, boundOptions); }
return boundExeca;};
const callBoundExeca = ({mapArguments, deepOptions = {}, boundOptions = {}, setBoundExeca, createNested}, firstArgument, ...nextArguments) => { if (isPlainObject(firstArgument)) { return createNested(mapArguments, mergeOptions(boundOptions, firstArgument), setBoundExeca); }
const {file, args, options, isSync} = parseArguments({mapArguments, firstArgument, nextArguments, deepOptions, boundOptions}); return isSync ? execaCoreSync(file, args, options) : execaCoreAsync(file, args, options, createNested);};
const parseArguments = ({mapArguments, firstArgument, nextArguments, deepOptions, boundOptions}) => { const callArguments = isTemplateString(firstArgument) ? parseTemplates(firstArgument, nextArguments) : [firstArgument, ...nextArguments]; const [rawFile, rawArgs, rawOptions] = normalizeArguments(...callArguments); const mergedOptions = mergeOptions(mergeOptions(deepOptions, boundOptions), rawOptions); const { file = rawFile, args = rawArgs, options = mergedOptions, isSync = false, } = mapArguments({file: rawFile, args: rawArgs, options: mergedOptions}); return {file, args, options, isSync};};
// Deep merge specific options like `env`. Shallow merge the other ones.const mergeOptions = (boundOptions, options) => { const newOptions = Object.fromEntries( Object.entries(options).map(([optionName, optionValue]) => [ optionName, mergeOption(optionName, boundOptions[optionName], optionValue), ]), ); return {...boundOptions, ...newOptions};};
const mergeOption = (optionName, boundOptionValue, optionValue) => { if (DEEP_OPTIONS.has(optionName) && isPlainObject(boundOptionValue) && isPlainObject(optionValue)) { return {...boundOptionValue, ...optionValue}; }
return optionValue;};
const DEEP_OPTIONS = new Set(['env', ...FD_SPECIFIC_OPTIONS]);added:lib/arguments/encoding-option.js+49 added
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849export const validateEncoding = ({encoding}) => { if (ENCODINGS.has(encoding)) { return; }
const correctEncoding = getCorrectEncoding(encoding); if (correctEncoding !== undefined) { throw new TypeError(`Invalid option \`encoding: ${serializeEncoding(encoding)}\`.Please rename it to ${serializeEncoding(correctEncoding)}.`); }
const correctEncodings = [...ENCODINGS].map(correctEncoding => serializeEncoding(correctEncoding)).join(', '); throw new TypeError(`Invalid option \`encoding: ${serializeEncoding(encoding)}\`.Please rename it to one of: ${correctEncodings}.`);};
const TEXT_ENCODINGS = new Set(['utf8', 'utf16le']);export const BINARY_ENCODINGS = new Set(['buffer', 'hex', 'base64', 'base64url', 'latin1', 'ascii']);const ENCODINGS = new Set([...TEXT_ENCODINGS, ...BINARY_ENCODINGS]);
const getCorrectEncoding = encoding => { if (encoding === null) { return 'buffer'; }
if (typeof encoding !== 'string') { return; }
const lowerEncoding = encoding.toLowerCase(); if (lowerEncoding in ENCODING_ALIASES) { return ENCODING_ALIASES[lowerEncoding]; }
if (ENCODINGS.has(lowerEncoding)) { return lowerEncoding; }};
const ENCODING_ALIASES = { // eslint-disable-next-line unicorn/text-encoding-identifier-case 'utf-8': 'utf8', 'utf-16le': 'utf16le', 'ucs-2': 'utf16le', ucs2: 'utf16le', binary: 'latin1',};
const serializeEncoding = encoding => typeof encoding === 'string' ? `"${encoding}"` : String(encoding);deleted:lib/arguments/encoding.js-49 removed
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849export const validateEncoding = ({encoding}) => { if (ENCODINGS.has(encoding)) { return; }
const correctEncoding = getCorrectEncoding(encoding); if (correctEncoding !== undefined) { throw new TypeError(`Invalid option \`encoding: ${serializeEncoding(encoding)}\`.Please rename it to ${serializeEncoding(correctEncoding)}.`); }
const correctEncodings = [...ENCODINGS].map(correctEncoding => serializeEncoding(correctEncoding)).join(', '); throw new TypeError(`Invalid option \`encoding: ${serializeEncoding(encoding)}\`.Please rename it to one of: ${correctEncodings}.`);};
const TEXT_ENCODINGS = new Set(['utf8', 'utf16le']);export const BINARY_ENCODINGS = new Set(['buffer', 'hex', 'base64', 'base64url', 'latin1', 'ascii']);const ENCODINGS = new Set([...TEXT_ENCODINGS, ...BINARY_ENCODINGS]);
const getCorrectEncoding = encoding => { if (encoding === null) { return 'buffer'; }
if (typeof encoding !== 'string') { return; }
const lowerEncoding = encoding.toLowerCase(); if (lowerEncoding in ENCODING_ALIASES) { return ENCODING_ALIASES[lowerEncoding]; }
if (ENCODINGS.has(lowerEncoding)) { return lowerEncoding; }};
const ENCODING_ALIASES = { // eslint-disable-next-line unicorn/text-encoding-identifier-case 'utf-8': 'utf8', 'utf-16le': 'utf16le', 'ucs-2': 'utf16le', ucs2: 'utf16le', binary: 'latin1',};
const serializeEncoding = encoding => typeof encoding === 'string' ? `"${encoding}"` : String(encoding);added:lib/arguments/fd-options.js+105 added
1+import {parseFd} from './specific.js';2+3+export const getWritable = (destination, to = 'stdin') => {4+ const isWritable = true;5+ const {options, fileDescriptors} = SUBPROCESS_OPTIONS.get(destination);6+ const fdNumber = getFdNumber(fileDescriptors, to, isWritable);7+ const destinationStream = destination.stdio[fdNumber];8+9+ if (destinationStream === null) {10+ throw new TypeError(getInvalidStdioOptionMessage(fdNumber, to, options, isWritable));11+ }12+13+ return destinationStream;14+};15+16+export const getReadable = (source, from = 'stdout') => {17+ const isWritable = false;18+ const {options, fileDescriptors} = SUBPROCESS_OPTIONS.get(source);19+ const fdNumber = getFdNumber(fileDescriptors, from, isWritable);20+ const sourceStream = fdNumber === 'all' ? source.all : source.stdio[fdNumber];21+22+ if (sourceStream === null || sourceStream === undefined) {23+ throw new TypeError(getInvalidStdioOptionMessage(fdNumber, from, options, isWritable));24+ }25+26+ return sourceStream;27+};28+29+export const SUBPROCESS_OPTIONS = new WeakMap();30+31+const getFdNumber = (fileDescriptors, fdName, isWritable) => {32+ const fdNumber = parseFdNumber(fdName, isWritable);33+ validateFdNumber(fdNumber, fdName, isWritable, fileDescriptors);34+ return fdNumber;35+};36+37+const parseFdNumber = (fdName, isWritable) => {38+ const fdNumber = parseFd(fdName);39+ if (fdNumber !== undefined) {40+ return fdNumber;41+ }42+43+ const {validOptions, defaultValue} = isWritable44+ ? {validOptions: '"stdin"', defaultValue: 'stdin'}45+ : {validOptions: '"stdout", "stderr", "all"', defaultValue: 'stdout'};46+ throw new TypeError(`"${getOptionName(isWritable)}" must not be "${fdName}".47+It must be ${validOptions} or "fd3", "fd4" (and so on).48+It is optional and defaults to "${defaultValue}".`);49+};50+51+const validateFdNumber = (fdNumber, fdName, isWritable, fileDescriptors) => {52+ const fileDescriptor = fileDescriptors[getUsedDescriptor(fdNumber)];53+ if (fileDescriptor === undefined) {54+ throw new TypeError(`"${getOptionName(isWritable)}" must not be ${fdName}. That file descriptor does not exist.55+Please set the "stdio" option to ensure that file descriptor exists.`);56+ }57+58+ if (fileDescriptor.direction === 'input' && !isWritable) {59+ throw new TypeError(`"${getOptionName(isWritable)}" must not be ${fdName}. It must be a readable stream, not writable.`);60+ }61+62+ if (fileDescriptor.direction !== 'input' && isWritable) {63+ throw new TypeError(`"${getOptionName(isWritable)}" must not be ${fdName}. It must be a writable stream, not readable.`);64+ }65+};66+67+const getInvalidStdioOptionMessage = (fdNumber, fdName, options, isWritable) => {68+ if (fdNumber === 'all' && !options.all) {69+ return 'The "all" option must be true to use "from: \'all\'".';70+ }71+72+ const {optionName, optionValue} = getInvalidStdioOption(fdNumber, options);73+ return `The "${optionName}: ${serializeOptionValue(optionValue)}" option is incompatible with using "${getOptionName(isWritable)}: ${serializeOptionValue(fdName)}".74+Please set this option with "pipe" instead.`;75+};76+77+const getInvalidStdioOption = (fdNumber, {stdin, stdout, stderr, stdio}) => {78+ const usedDescriptor = getUsedDescriptor(fdNumber);79+80+ if (usedDescriptor === 0 && stdin !== undefined) {81+ return {optionName: 'stdin', optionValue: stdin};82+ }83+84+ if (usedDescriptor === 1 && stdout !== undefined) {85+ return {optionName: 'stdout', optionValue: stdout};86+ }87+88+ if (usedDescriptor === 2 && stderr !== undefined) {89+ return {optionName: 'stderr', optionValue: stderr};90+ }91+92+ return {optionName: `stdio[${usedDescriptor}]`, optionValue: stdio[usedDescriptor]};93+};94+95+const getUsedDescriptor = fdNumber => fdNumber === 'all' ? 1 : fdNumber;96+97+const getOptionName = isWritable => isWritable ? 'to' : 'from';98+99+export const serializeOptionValue = value => {100+ if (typeof value === 'string') {101+ return `'${value}'`;102+ }103+104+ return typeof value === 'number' ? `${value}` : 'Stream';105+};deleted:lib/arguments/node.js-42 removed
123456789101112131415161718192021222324252627282930313233343536373839404142import {execPath, execArgv} from 'node:process';import {basename, resolve} from 'node:path';import {safeNormalizeFileUrl} from './file-url.js';
export const mapNode = ({options}) => { if (options.node === false) { throw new TypeError('The "node" option cannot be false with `execaNode()`.'); }
return {options: {...options, node: true}};};
export const handleNodeOption = (file, args, { node: shouldHandleNode = false, nodePath = execPath, nodeOptions = execArgv.filter(arg => !arg.startsWith('--inspect')), cwd, execPath: formerNodePath, ...options}) => { if (formerNodePath !== undefined) { throw new TypeError('The "execPath" option has been removed. Please use the "nodePath" option instead.'); }
const normalizedNodePath = safeNormalizeFileUrl(nodePath, 'The "nodePath" option'); const resolvedNodePath = resolve(cwd, normalizedNodePath); const newOptions = {...options, nodePath: resolvedNodePath, node: shouldHandleNode, cwd};
if (!shouldHandleNode) { return [file, args, newOptions]; }
if (basename(file, '.exe') === 'node') { throw new TypeError('When the "node" option is true, the first argument does not need to be "node".'); }
return [ resolvedNodePath, [...nodeOptions, file, ...args], {ipc: true, ...newOptions, shell: false}, ];};deleted:lib/arguments/normalize.js-29 removed
1234567891011121314151617181920212223242526272829import isPlainObject from 'is-plain-obj';import {safeNormalizeFileUrl} from './file-url.js';
export const normalizeArguments = (rawFile, rawArgs = [], rawOptions = {}) => { const filePath = safeNormalizeFileUrl(rawFile, 'First argument'); const [args, options] = isPlainObject(rawArgs) ? [[], rawArgs] : [rawArgs, rawOptions];
if (!Array.isArray(args)) { throw new TypeError(`Second argument must be either an array of arguments or an options object: ${args}`); }
if (args.some(arg => typeof arg === 'object' && arg !== null)) { throw new TypeError(`Second argument must be an array of strings: ${args}`); }
const normalizedArgs = args.map(String); const nullByteArg = normalizedArgs.find(arg => arg.includes('\0')); if (nullByteArg !== undefined) { throw new TypeError(`Arguments cannot contain null bytes ("\\0"): ${nullByteArg}`); }
if (!isPlainObject(options)) { throw new TypeError(`Last argument must be an options object: ${options}`); }
return [filePath, normalizedArgs, options];};modified:lib/arguments/options.js+4 added-4 removed
123456785678910111264 unmodified linesimport {basename} from 'node:path';import process from 'node:process';import crossSpawn from 'cross-spawn';import {npmRunPathEnv} from 'npm-run-path';import {normalizeForceKillAfterDelay} from '../exit/kill.js';import {validateTimeout} from '../exit/timeout.js';import {validateEncoding, BINARY_ENCODINGS} from './encoding.js';import {handleNodeOption} from './node.js';import {normalizeForceKillAfterDelay} from '../terminate/kill.js';import {validateTimeout} from '../terminate/timeout.js';import {handleNodeOption} from '../methods/node.js';import {validateEncoding, BINARY_ENCODINGS} from './encoding-option.js';import {normalizeCwd} from './cwd.js';import {normalizeFileUrl} from './file-url.js';import {normalizeFdSpecificOptions} from './specific.js';
64 unmodified linesmodified:lib/arguments/specific.js+1 added-1 removed
1 import isPlainObject from 'is-plain-obj';2-import {STANDARD_STREAMS_ALIASES} from '../utils.js';2+import {STANDARD_STREAMS_ALIASES} from '../utils/standard-stream.js';3 import {verboseDefault} from '../verbose/info.js';4 5 export const normalizeFdSpecificOptions = options => {6 const optionsCopy = {...options};88 unmodified linesdeleted:lib/arguments/template.js-135 removed
1-import {ChildProcess} from 'node:child_process';2-import {isUint8Array, uint8ArrayToString} from '../stdio/uint-array.js';3-4-export const isTemplateString = templates => Array.isArray(templates) && Array.isArray(templates.raw);5-6-export const parseTemplates = (templates, expressions) => {7- let tokens = [];8-9- for (const [index, template] of templates.entries()) {10- tokens = parseTemplate({templates, expressions, tokens, index, template});11- }12-13- if (tokens.length === 0) {14- throw new TypeError('Template script must not be empty');15- }16-17- const [file, ...args] = tokens;18- return [file, args, {}];19-};20-21-const parseTemplate = ({templates, expressions, tokens, index, template}) => {22- if (template === undefined) {23- throw new TypeError(`Invalid backslash sequence: ${templates.raw[index]}`);24- }25-26- const {nextTokens, leadingWhitespaces, trailingWhitespaces} = splitByWhitespaces(template, templates.raw[index]);27- const newTokens = concatTokens(tokens, nextTokens, leadingWhitespaces);28-29- if (index === expressions.length) {30- return newTokens;31- }32-33- const expression = expressions[index];34- const expressionTokens = Array.isArray(expression)35- ? expression.map(expression => parseExpression(expression))36- : [parseExpression(expression)];37- return concatTokens(newTokens, expressionTokens, trailingWhitespaces);38-};39-40-// Like `string.split(/[ \t\r\n]+/)` except newlines and tabs are:41-// - ignored when input as a backslash sequence like: `echo foo\n bar`42-// - not ignored when input directly43-// The only way to distinguish those in JavaScript is to use a tagged template and compare:44-// - the first array argument, which does not escape backslash sequences45-// - its `raw` property, which escapes them46-const splitByWhitespaces = (template, rawTemplate) => {47- if (rawTemplate.length === 0) {48- return {nextTokens: [], leadingWhitespaces: false, trailingWhitespaces: false};49- }50-51- const nextTokens = [];52- let templateStart = 0;53- const leadingWhitespaces = DELIMITERS.has(rawTemplate[0]);54-55- for (56- let templateIndex = 0, rawIndex = 0;57- templateIndex < template.length;58- templateIndex += 1, rawIndex += 159- ) {60- const rawCharacter = rawTemplate[rawIndex];61- if (DELIMITERS.has(rawCharacter)) {62- if (templateStart !== templateIndex) {63- nextTokens.push(template.slice(templateStart, templateIndex));64- }65-66- templateStart = templateIndex + 1;67- } else if (rawCharacter === '\\') {68- const nextRawCharacter = rawTemplate[rawIndex + 1];69- if (nextRawCharacter === 'u' && rawTemplate[rawIndex + 2] === '{') {70- rawIndex = rawTemplate.indexOf('}', rawIndex + 3);71- } else {72- rawIndex += ESCAPE_LENGTH[nextRawCharacter] ?? 1;73- }74- }75- }76-77- const trailingWhitespaces = templateStart === template.length;78- if (!trailingWhitespaces) {79- nextTokens.push(template.slice(templateStart));80- }81-82- return {nextTokens, leadingWhitespaces, trailingWhitespaces};83-};84-85-const DELIMITERS = new Set([' ', '\t', '\r', '\n']);86-87-// Number of characters in backslash escape sequences: \0 \xXX or \uXXXX88-// \cX is allowed in RegExps but not in strings89-// Octal sequences are not allowed in strict mode90-const ESCAPE_LENGTH = {x: 3, u: 5};91-92-const concatTokens = (tokens, nextTokens, isSeparated) => isSeparated93- || tokens.length === 094- || nextTokens.length === 095- ? [...tokens, ...nextTokens]96- : [97- ...tokens.slice(0, -1),98- `${tokens.at(-1)}${nextTokens[0]}`,99- ...nextTokens.slice(1),100- ];101-102-const parseExpression = expression => {103- const typeOfExpression = typeof expression;104-105- if (typeOfExpression === 'string') {106- return expression;107- }108-109- if (typeOfExpression === 'number') {110- return String(expression);111- }112-113- if (114- typeOfExpression === 'object'115- && expression !== null116- && !isSubprocess(expression)117- && 'stdout' in expression118- ) {119- const typeOfStdout = typeof expression.stdout;120-121- if (typeOfStdout === 'string') {122- return expression.stdout;123- }124-125- if (isUint8Array(expression.stdout)) {126- return uint8ArrayToString(expression.stdout);127- }128-129- throw new TypeError(`Unexpected "${typeOfStdout}" stdout in template expression`);130- }131-132- throw new TypeError(`Unexpected "${typeOfExpression}" in template expression`);133-};134-135-const isSubprocess = value => value instanceof ChildProcess;modified:lib/convert/duplex.js+1 added-1 removed
1 import {Duplex} from 'node:stream';2 import {callbackify} from 'node:util';3-import {BINARY_ENCODINGS} from '../arguments/encoding.js';3+import {BINARY_ENCODINGS} from '../arguments/encoding-option.js';4 import {5 getSubprocessStdout,6 getReadableOptions,7 getReadableMethods,38 unmodified linesdeleted:lib/convert/fd-options.js-105 removed
1-import {parseFd} from '../arguments/specific.js';2-3-export const getWritable = (destination, to = 'stdin') => {4- const isWritable = true;5- const {options, fileDescriptors} = SUBPROCESS_OPTIONS.get(destination);6- const fdNumber = getFdNumber(fileDescriptors, to, isWritable);7- const destinationStream = destination.stdio[fdNumber];8-9- if (destinationStream === null) {10- throw new TypeError(getInvalidStdioOptionMessage(fdNumber, to, options, isWritable));11- }12-13- return destinationStream;14-};15-16-export const getReadable = (source, from = 'stdout') => {17- const isWritable = false;18- const {options, fileDescriptors} = SUBPROCESS_OPTIONS.get(source);19- const fdNumber = getFdNumber(fileDescriptors, from, isWritable);20- const sourceStream = fdNumber === 'all' ? source.all : source.stdio[fdNumber];21-22- if (sourceStream === null || sourceStream === undefined) {23- throw new TypeError(getInvalidStdioOptionMessage(fdNumber, from, options, isWritable));24- }25-26- return sourceStream;27-};28-29-export const SUBPROCESS_OPTIONS = new WeakMap();30-31-const getFdNumber = (fileDescriptors, fdName, isWritable) => {32- const fdNumber = parseFdNumber(fdName, isWritable);33- validateFdNumber(fdNumber, fdName, isWritable, fileDescriptors);34- return fdNumber;35-};36-37-const parseFdNumber = (fdName, isWritable) => {38- const fdNumber = parseFd(fdName);39- if (fdNumber !== undefined) {40- return fdNumber;41- }42-43- const {validOptions, defaultValue} = isWritable44- ? {validOptions: '"stdin"', defaultValue: 'stdin'}45- : {validOptions: '"stdout", "stderr", "all"', defaultValue: 'stdout'};46- throw new TypeError(`"${getOptionName(isWritable)}" must not be "${fdName}".47-It must be ${validOptions} or "fd3", "fd4" (and so on).48-It is optional and defaults to "${defaultValue}".`);49-};50-51-const validateFdNumber = (fdNumber, fdName, isWritable, fileDescriptors) => {52- const fileDescriptor = fileDescriptors[getUsedDescriptor(fdNumber)];53- if (fileDescriptor === undefined) {54- throw new TypeError(`"${getOptionName(isWritable)}" must not be ${fdName}. That file descriptor does not exist.55-Please set the "stdio" option to ensure that file descriptor exists.`);56- }57-58- if (fileDescriptor.direction === 'input' && !isWritable) {59- throw new TypeError(`"${getOptionName(isWritable)}" must not be ${fdName}. It must be a readable stream, not writable.`);60- }61-62- if (fileDescriptor.direction !== 'input' && isWritable) {63- throw new TypeError(`"${getOptionName(isWritable)}" must not be ${fdName}. It must be a writable stream, not readable.`);64- }65-};66-67-const getInvalidStdioOptionMessage = (fdNumber, fdName, options, isWritable) => {68- if (fdNumber === 'all' && !options.all) {69- return 'The "all" option must be true to use "from: \'all\'".';70- }71-72- const {optionName, optionValue} = getInvalidStdioOption(fdNumber, options);73- return `The "${optionName}: ${serializeOptionValue(optionValue)}" option is incompatible with using "${getOptionName(isWritable)}: ${serializeOptionValue(fdName)}".74-Please set this option with "pipe" instead.`;75-};76-77-const getInvalidStdioOption = (fdNumber, {stdin, stdout, stderr, stdio}) => {78- const usedDescriptor = getUsedDescriptor(fdNumber);79-80- if (usedDescriptor === 0 && stdin !== undefined) {81- return {optionName: 'stdin', optionValue: stdin};82- }83-84- if (usedDescriptor === 1 && stdout !== undefined) {85- return {optionName: 'stdout', optionValue: stdout};86- }87-88- if (usedDescriptor === 2 && stderr !== undefined) {89- return {optionName: 'stderr', optionValue: stderr};90- }91-92- return {optionName: `stdio[${usedDescriptor}]`, optionValue: stdio[usedDescriptor]};93-};94-95-const getUsedDescriptor = fdNumber => fdNumber === 'all' ? 1 : fdNumber;96-97-const getOptionName = isWritable => isWritable ? 'to' : 'from';98-99-export const serializeOptionValue = value => {100- if (typeof value === 'string') {101- return `'${value}'`;102- }103-104- return typeof value === 'number' ? `${value}` : 'Stream';105-};modified:lib/convert/iterable.js+3 added-3 removed
1-import {BINARY_ENCODINGS} from '../arguments/encoding.js';2-import {getReadable} from './fd-options.js';3-import {iterateOnSubprocessStream} from './loop.js';1+import {BINARY_ENCODINGS} from '../arguments/encoding-option.js';2+import {getReadable} from '../arguments/fd-options.js';3+import {iterateOnSubprocessStream} from '../io/iterate.js';4 5 export const createIterable = (subprocess, encoding, {6 from,7 binary: binaryOption = false,19 unmodified linesdeleted:lib/convert/loop.js-96 removed
1-import {on} from 'node:events';2-import {getEncodingTransformGenerator} from '../stdio/encoding-transform.js';3-import {getSplitLinesGenerator} from '../stdio/split.js';4-import {transformChunkSync, finalChunksSync} from '../stdio/transform-sync.js';5-6-// Iterate over lines of `subprocess.stdout`, used by `subprocess.readable|duplex|iterable()`7-export const iterateOnSubprocessStream = ({subprocessStdout, subprocess, binary, shouldEncode, encoding, preserveNewlines}) => {8- const controller = new AbortController();9- stopReadingOnExit(subprocess, controller);10- return iterateOnStream({11- stream: subprocessStdout,12- controller,13- binary,14- shouldEncode: !subprocessStdout.readableObjectMode && shouldEncode,15- encoding,16- shouldSplit: !subprocessStdout.readableObjectMode,17- preserveNewlines,18- });19-};20-21-const stopReadingOnExit = async (subprocess, controller) => {22- try {23- await subprocess;24- } catch {} finally {25- controller.abort();26- }27-};28-29-// Iterate over lines of `subprocess.stdout`, used by `result.stdout` and the `verbose: 'full'` option.30-// Applies the `lines` and `encoding` options.31-export const iterateForResult = ({stream, onStreamEnd, lines, encoding, stripFinalNewline, allMixed}) => {32- const controller = new AbortController();33- stopReadingOnStreamEnd(onStreamEnd, controller, stream);34- const objectMode = stream.readableObjectMode && !allMixed;35- return iterateOnStream({36- stream,37- controller,38- binary: encoding === 'buffer',39- shouldEncode: !objectMode,40- encoding,41- shouldSplit: !objectMode && lines,42- preserveNewlines: !stripFinalNewline,43- });44-};45-46-const stopReadingOnStreamEnd = async (onStreamEnd, controller, stream) => {47- try {48- await onStreamEnd;49- } catch {50- stream.destroy();51- } finally {52- controller.abort();53- }54-};55-56-const iterateOnStream = ({stream, controller, binary, shouldEncode, encoding, shouldSplit, preserveNewlines}) => {57- const onStdoutChunk = on(stream, 'data', {58- signal: controller.signal,59- highWaterMark: HIGH_WATER_MARK,60- // Backward compatibility with older name for this option61- // See https://github.com/nodejs/node/pull/52080#discussion_r152522786162- // @todo Remove after removing support for Node 2163- highWatermark: HIGH_WATER_MARK,64- });65- return iterateOnData({onStdoutChunk, controller, binary, shouldEncode, encoding, shouldSplit, preserveNewlines});66-};67-68-// @todo: replace with `getDefaultHighWaterMark(true)` after dropping support for Node <18.17.069-export const DEFAULT_OBJECT_HIGH_WATER_MARK = 16;70-71-// The `highWaterMark` of `events.on()` is measured in number of events, not in bytes.72-// Not knowing the average amount of bytes per `data` event, we use the same heuristic as streams in objectMode, since they have the same issue.73-// Therefore, we use the value of `getDefaultHighWaterMark(true)`.74-// Note: this option does not exist on Node 18, but this is ok since the logic works without it. It just consumes more memory.75-const HIGH_WATER_MARK = DEFAULT_OBJECT_HIGH_WATER_MARK;76-77-const iterateOnData = async function * ({onStdoutChunk, controller, binary, shouldEncode, encoding, shouldSplit, preserveNewlines}) {78- const generators = getGenerators({binary, shouldEncode, encoding, shouldSplit, preserveNewlines});79-80- try {81- for await (const [chunk] of onStdoutChunk) {82- yield * transformChunkSync(chunk, generators, 0);83- }84- } catch (error) {85- if (!controller.signal.aborted) {86- throw error;87- }88- } finally {89- yield * finalChunksSync(generators);90- }91-};92-93-const getGenerators = ({binary, shouldEncode, encoding, shouldSplit, preserveNewlines}) => [94- getEncodingTransformGenerator(binary, encoding, !shouldEncode),95- getSplitLinesGenerator(binary, preserveNewlines, !shouldSplit, {}),96-].filter(Boolean);modified:lib/convert/readable.js+3 added-3 removed
1 import {Readable} from 'node:stream';2 import {callbackify} from 'node:util';3-import {BINARY_ENCODINGS} from '../arguments/encoding.js';4-import {getReadable} from './fd-options.js';3+import {BINARY_ENCODINGS} from '../arguments/encoding-option.js';4+import {getReadable} from '../arguments/fd-options.js';5+import {iterateOnSubprocessStream, DEFAULT_OBJECT_HIGH_WATER_MARK} from '../io/iterate.js';6 import {addConcurrentStream, waitForConcurrentStreams} from './concurrent.js';7 import {8 createDeferred,9 safeWaitForSubprocessStdin,10 waitForSubprocessStdout,11 waitForSubprocess,12 destroyOtherStream,13 } from './shared.js';13-import {iterateOnSubprocessStream, DEFAULT_OBJECT_HIGH_WATER_MARK} from './loop.js';14 15 // Create a `Readable` stream that forwards from `stdout` and awaits the subprocess16 export const createReadable = ({subprocess, concurrentStreams, encoding}, {from, binary: binaryOption = true, preserveNewlines = true} = {}) => {17 const binary = binaryOption || BINARY_ENCODINGS.has(encoding);78 unmodified linesmodified:lib/convert/shared.js+1 added-1 removed
1 import {finished} from 'node:stream/promises';2-import {isStreamAbort} from '../stream/wait.js';2+import {isStreamAbort} from '../resolve/wait-stream.js';3 4 export const safeWaitForSubprocessStdin = async subprocessStdin => {5 if (subprocessStdin === undefined) {6 return;48 unmodified linesmodified:lib/convert/writable.js+1 added-1 removed
1 import {Writable} from 'node:stream';2 import {callbackify} from 'node:util';3-import {getWritable} from './fd-options.js';3+import {getWritable} from '../arguments/fd-options.js';4 import {addConcurrentStream, waitForConcurrentStreams} from './concurrent.js';5 import {6 safeWaitForSubprocessStdout,7 waitForSubprocessStdin,78 unmodified linesdeleted:lib/exit/cleanup.js-16 removed
1-import {addAbortListener} from 'node:events';2-import {onExit} from 'signal-exit';3-4-// `cleanup` option handling5-export const cleanupOnExit = (subprocess, {cleanup, detached}, {signal}) => {6- if (!cleanup || detached) {7- return;8- }9-10- const removeExitHandler = onExit(() => {11- subprocess.kill();12- });13- addAbortListener(signal, () => {14- removeExitHandler();15- });16-};deleted:lib/exit/kill.js-76 removed
1-import os from 'node:os';2-import {setTimeout} from 'node:timers/promises';3-import {isErrorInstance} from '../return/cause.js';4-5-export const normalizeForceKillAfterDelay = forceKillAfterDelay => {6- if (forceKillAfterDelay === false) {7- return forceKillAfterDelay;8- }9-10- if (forceKillAfterDelay === true) {11- return DEFAULT_FORCE_KILL_TIMEOUT;12- }13-14- if (!Number.isFinite(forceKillAfterDelay) || forceKillAfterDelay < 0) {15- throw new TypeError(`Expected the \`forceKillAfterDelay\` option to be a non-negative integer, got \`${forceKillAfterDelay}\` (${typeof forceKillAfterDelay})`);16- }17-18- return forceKillAfterDelay;19-};20-21-const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5;22-23-// Monkey-patches `subprocess.kill()` to add `forceKillAfterDelay` behavior and `.kill(error)`24-export const subprocessKill = ({kill, subprocess, options: {forceKillAfterDelay, killSignal}, controller}, signalOrError, errorArgument) => {25- const {signal, error} = parseKillArguments(signalOrError, errorArgument, killSignal);26- emitKillError(subprocess, error);27- const killResult = kill(signal);28- setKillTimeout({kill, signal, forceKillAfterDelay, killSignal, killResult, controller});29- return killResult;30-};31-32-const parseKillArguments = (signalOrError, errorArgument, killSignal) => {33- const [signal = killSignal, error] = isErrorInstance(signalOrError)34- ? [undefined, signalOrError]35- : [signalOrError, errorArgument];36-37- if (typeof signal !== 'string' && typeof signal !== 'number') {38- throw new TypeError(`The first argument must be an error instance or a signal name string/number: ${signal}`);39- }40-41- if (error !== undefined && !isErrorInstance(error)) {42- throw new TypeError(`The second argument is optional. If specified, it must be an error instance: ${error}`);43- }44-45- return {signal, error};46-};47-48-const emitKillError = (subprocess, error) => {49- if (error !== undefined) {50- subprocess.emit(errorSignal, error);51- }52-};53-54-// Like `error` signal but internal to Execa.55-// E.g. does not make subprocess crash when no `error` listener is set.56-export const errorSignal = Symbol('error');57-58-const setKillTimeout = async ({kill, signal, forceKillAfterDelay, killSignal, killResult, controller}) => {59- if (!shouldForceKill(signal, forceKillAfterDelay, killSignal, killResult)) {60- return;61- }62-63- try {64- await setTimeout(forceKillAfterDelay, undefined, {signal: controller.signal});65- kill('SIGKILL');66- } catch {}67-};68-69-const shouldForceKill = (signal, forceKillAfterDelay, killSignal, killResult) =>70- normalizeSignal(signal) === normalizeSignal(killSignal)71- && forceKillAfterDelay !== false72- && killResult;73-74-const normalizeSignal = signal => typeof signal === 'string'75- ? os.constants.signals[signal.toUpperCase()]76- : signal;deleted:lib/exit/timeout.js-20 removed
1-import {setTimeout} from 'node:timers/promises';2-import {DiscardedError} from '../return/cause.js';3-4-export const validateTimeout = ({timeout}) => {5- if (timeout !== undefined && (!Number.isFinite(timeout) || timeout < 0)) {6- throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`);7- }8-};9-10-// `timeout` option handling11-export const throwOnTimeout = (subprocess, timeout, context, controller) => timeout === 0 || timeout === undefined12- ? []13- : [killAfterTimeout(subprocess, timeout, context, controller)];14-15-const killAfterTimeout = async (subprocess, timeout, context, {signal}) => {16- await setTimeout(timeout, undefined, {signal});17- context.timedOut = true;18- subprocess.kill();19- throw new DiscardedError();20-};added:lib/io/contents.js+63 added
1+import {setImmediate} from 'node:timers/promises';2+import getStream, {getStreamAsArrayBuffer, getStreamAsArray} from 'get-stream';3+import {isArrayBuffer} from '../utils/uint-array.js';4+import {shouldLogOutput, logLines} from '../verbose/output.js';5+import {iterateForResult} from './iterate.js';6+import {handleMaxBuffer} from './max-buffer.js';7+import {getStripFinalNewline} from './strip-newline.js';8+9+export const getStreamOutput = async ({stream, onStreamEnd, fdNumber, encoding, buffer, maxBuffer, lines, allMixed, stripFinalNewline, verboseInfo, streamInfo: {fileDescriptors}}) => {10+ if (shouldLogOutput({stdioItems: fileDescriptors[fdNumber]?.stdioItems, encoding, verboseInfo, fdNumber})) {11+ const linesIterable = iterateForResult({stream, onStreamEnd, lines: true, encoding, stripFinalNewline: true, allMixed});12+ logLines(linesIterable, stream, verboseInfo);13+ }14+15+ if (!buffer) {16+ await resumeStream(stream);17+ return;18+ }19+20+ const stripFinalNewlineValue = getStripFinalNewline(stripFinalNewline, fdNumber);21+ const iterable = iterateForResult({stream, onStreamEnd, lines, encoding, stripFinalNewline: stripFinalNewlineValue, allMixed});22+ return getStreamContents({stream, iterable, fdNumber, encoding, maxBuffer, lines});23+};24+25+// When using `buffer: false`, users need to read `subprocess.stdout|stderr|all` right away26+// See https://github.com/sindresorhus/execa/issues/730 and https://github.com/sindresorhus/execa/pull/729#discussion_r146549631027+const resumeStream = async stream => {28+ await setImmediate();29+ if (stream.readableFlowing === null) {30+ stream.resume();31+ }32+};33+34+const getStreamContents = async ({stream, stream: {readableObjectMode}, iterable, fdNumber, encoding, maxBuffer, lines}) => {35+ try {36+ if (readableObjectMode || lines) {37+ return await getStreamAsArray(iterable, {maxBuffer});38+ }39+40+ if (encoding === 'buffer') {41+ return new Uint8Array(await getStreamAsArrayBuffer(iterable, {maxBuffer}));42+ }43+44+ return await getStream(iterable, {maxBuffer});45+ } catch (error) {46+ return handleBufferedData(handleMaxBuffer({error, stream, readableObjectMode, lines, encoding, fdNumber}));47+ }48+};49+50+// On failure, `result.stdout|stderr|all` should contain the currently buffered stream51+// They are automatically closed and flushed by Node.js when the subprocess exits52+// When `buffer` is `false`, `streamPromise` is `undefined` and there is no buffered data to retrieve53+export const getBufferedData = async streamPromise => {54+ try {55+ return await streamPromise;56+ } catch (error) {57+ return handleBufferedData(error);58+ }59+};60+61+const handleBufferedData = ({bufferedData}) => isArrayBuffer(bufferedData)62+ ? new Uint8Array(bufferedData)63+ : bufferedData;added:lib/io/input-sync.js+44 added
1+import {runGeneratorsSync} from '../transform/generator.js';2+import {joinToUint8Array, isUint8Array} from '../utils/uint-array.js';3+import {TYPE_TO_MESSAGE} from '../stdio/type.js';4+5+// Apply `stdin`/`input`/`inputFile` options, before spawning, in sync mode, by converting it to the `input` option6+export const addInputOptionsSync = (fileDescriptors, options) => {7+ for (const fdNumber of getInputFdNumbers(fileDescriptors)) {8+ addInputOptionSync(fileDescriptors, fdNumber, options);9+ }10+};11+12+const getInputFdNumbers = fileDescriptors => new Set(Object.entries(fileDescriptors)13+ .filter(([, {direction}]) => direction === 'input')14+ .map(([fdNumber]) => Number(fdNumber)));15+16+const addInputOptionSync = (fileDescriptors, fdNumber, options) => {17+ const {stdioItems} = fileDescriptors[fdNumber];18+ const allStdioItems = stdioItems.filter(({contents}) => contents !== undefined);19+ if (allStdioItems.length === 0) {20+ return;21+ }22+23+ if (fdNumber !== 0) {24+ const [{type, optionName}] = allStdioItems;25+ throw new TypeError(`Only the \`stdin\` option, not \`${optionName}\`, can be ${TYPE_TO_MESSAGE[type]} with synchronous methods.`);26+ }27+28+ const allContents = allStdioItems.map(({contents}) => contents);29+ const transformedContents = allContents.map(contents => applySingleInputGeneratorsSync(contents, stdioItems));30+ options.input = joinToUint8Array(transformedContents);31+};32+33+const applySingleInputGeneratorsSync = (contents, stdioItems) => {34+ const newContents = runGeneratorsSync(contents, stdioItems, 'utf8', true);35+ validateSerializable(newContents);36+ return joinToUint8Array(newContents);37+};38+39+const validateSerializable = newContents => {40+ const invalidItem = newContents.find(item => typeof item !== 'string' && !isUint8Array(item));41+ if (invalidItem !== undefined) {42+ throw new TypeError(`The \`stdin\` option is invalid: when passing objects as input, a transform must be used to serialize them to strings or Uint8Arrays: ${invalidItem}.`);43+ }44+};added:lib/io/iterate.js+96 added
1+import {on} from 'node:events';2+import {getEncodingTransformGenerator} from '../transform/encoding-transform.js';3+import {getSplitLinesGenerator} from '../transform/split.js';4+import {transformChunkSync, finalChunksSync} from '../transform/run-sync.js';5+6+// Iterate over lines of `subprocess.stdout`, used by `subprocess.readable|duplex|iterable()`7+export const iterateOnSubprocessStream = ({subprocessStdout, subprocess, binary, shouldEncode, encoding, preserveNewlines}) => {8+ const controller = new AbortController();9+ stopReadingOnExit(subprocess, controller);10+ return iterateOnStream({11+ stream: subprocessStdout,12+ controller,13+ binary,14+ shouldEncode: !subprocessStdout.readableObjectMode && shouldEncode,15+ encoding,16+ shouldSplit: !subprocessStdout.readableObjectMode,17+ preserveNewlines,18+ });19+};20+21+const stopReadingOnExit = async (subprocess, controller) => {22+ try {23+ await subprocess;24+ } catch {} finally {25+ controller.abort();26+ }27+};28+29+// Iterate over lines of `subprocess.stdout`, used by `result.stdout` and the `verbose: 'full'` option.30+// Applies the `lines` and `encoding` options.31+export const iterateForResult = ({stream, onStreamEnd, lines, encoding, stripFinalNewline, allMixed}) => {32+ const controller = new AbortController();33+ stopReadingOnStreamEnd(onStreamEnd, controller, stream);34+ const objectMode = stream.readableObjectMode && !allMixed;35+ return iterateOnStream({36+ stream,37+ controller,38+ binary: encoding === 'buffer',39+ shouldEncode: !objectMode,40+ encoding,41+ shouldSplit: !objectMode && lines,42+ preserveNewlines: !stripFinalNewline,43+ });44+};45+46+const stopReadingOnStreamEnd = async (onStreamEnd, controller, stream) => {47+ try {48+ await onStreamEnd;49+ } catch {50+ stream.destroy();51+ } finally {52+ controller.abort();53+ }54+};55+56+const iterateOnStream = ({stream, controller, binary, shouldEncode, encoding, shouldSplit, preserveNewlines}) => {57+ const onStdoutChunk = on(stream, 'data', {58+ signal: controller.signal,59+ highWaterMark: HIGH_WATER_MARK,60+ // Backward compatibility with older name for this option61+ // See https://github.com/nodejs/node/pull/52080#discussion_r152522786162+ // @todo Remove after removing support for Node 2163+ highWatermark: HIGH_WATER_MARK,64+ });65+ return iterateOnData({onStdoutChunk, controller, binary, shouldEncode, encoding, shouldSplit, preserveNewlines});66+};67+68+// @todo: replace with `getDefaultHighWaterMark(true)` after dropping support for Node <18.17.069+export const DEFAULT_OBJECT_HIGH_WATER_MARK = 16;70+71+// The `highWaterMark` of `events.on()` is measured in number of events, not in bytes.72+// Not knowing the average amount of bytes per `data` event, we use the same heuristic as streams in objectMode, since they have the same issue.73+// Therefore, we use the value of `getDefaultHighWaterMark(true)`.74+// Note: this option does not exist on Node 18, but this is ok since the logic works without it. It just consumes more memory.75+const HIGH_WATER_MARK = DEFAULT_OBJECT_HIGH_WATER_MARK;76+77+const iterateOnData = async function * ({onStdoutChunk, controller, binary, shouldEncode, encoding, shouldSplit, preserveNewlines}) {78+ const generators = getGenerators({binary, shouldEncode, encoding, shouldSplit, preserveNewlines});79+80+ try {81+ for await (const [chunk] of onStdoutChunk) {82+ yield * transformChunkSync(chunk, generators, 0);83+ }84+ } catch (error) {85+ if (!controller.signal.aborted) {86+ throw error;87+ }88+ } finally {89+ yield * finalChunksSync(generators);90+ }91+};92+93+const getGenerators = ({binary, shouldEncode, encoding, shouldSplit, preserveNewlines}) => [94+ getEncodingTransformGenerator(binary, encoding, !shouldEncode),95+ getSplitLinesGenerator(binary, preserveNewlines, !shouldSplit, {}),96+].filter(Boolean);added:lib/io/max-buffer.js+55 added
1+import {MaxBufferError} from 'get-stream';2+import {getStreamName} from '../utils/standard-stream.js';3+4+export const handleMaxBuffer = ({error, stream, readableObjectMode, lines, encoding, fdNumber}) => {5+ if (!(error instanceof MaxBufferError)) {6+ throw error;7+ }8+9+ if (fdNumber === 'all') {10+ return error;11+ }12+13+ const unit = getMaxBufferUnit(readableObjectMode, lines, encoding);14+ error.maxBufferInfo = {fdNumber, unit};15+ stream.destroy();16+ throw error;17+};18+19+const getMaxBufferUnit = (readableObjectMode, lines, encoding) => {20+ if (readableObjectMode) {21+ return 'objects';22+ }23+24+ if (lines) {25+ return 'lines';26+ }27+28+ if (encoding === 'buffer') {29+ return 'bytes';30+ }31+32+ return 'characters';33+};34+35+export const getMaxBufferMessage = (error, maxBuffer) => {36+ const {streamName, threshold, unit} = getMaxBufferInfo(error, maxBuffer);37+ return `Command's ${streamName} was larger than ${threshold} ${unit}`;38+};39+40+const getMaxBufferInfo = (error, maxBuffer) => {41+ if (error?.maxBufferInfo === undefined) {42+ return {streamName: 'output', threshold: maxBuffer[1], unit: 'bytes'};43+ }44+45+ const {maxBufferInfo: {fdNumber, unit}} = error;46+ delete error.maxBufferInfo;47+ return {streamName: getStreamName(fdNumber), threshold: maxBuffer[fdNumber], unit};48+};49+50+export const isMaxBufferSync = (resultError, output, maxBuffer) => resultError?.code === 'ENOBUFS'51+ && output !== null52+ && output.some(result => result !== null && result.length > getMaxBufferSync(maxBuffer));53+54+// `spawnSync()` does not allow differentiating `maxBuffer` per file descriptor, so we always use `stdout`55+export const getMaxBufferSync = maxBuffer => maxBuffer[1];added:lib/io/output-async.js+71 added
1+import mergeStreams from '@sindresorhus/merge-streams';2+import {isStandardStream} from '../utils/standard-stream.js';3+import {incrementMaxListeners} from '../utils/max-listeners.js';4+import {TRANSFORM_TYPES} from '../stdio/type.js';5+import {pipeStreams} from './pipeline.js';6+7+// Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, after spawning, in async mode8+// When multiple input streams are used, we merge them to ensure the output stream ends only once each input stream has ended9+export const pipeOutputAsync = (subprocess, fileDescriptors, controller) => {10+ const inputStreamsGroups = {};11+12+ for (const [fdNumber, {stdioItems, direction}] of Object.entries(fileDescriptors)) {13+ for (const {stream} of stdioItems.filter(({type}) => TRANSFORM_TYPES.has(type))) {14+ pipeTransform(subprocess, stream, direction, fdNumber);15+ }16+17+ for (const {stream} of stdioItems.filter(({type}) => !TRANSFORM_TYPES.has(type))) {18+ pipeStdioItem({subprocess, stream, direction, fdNumber, inputStreamsGroups, controller});19+ }20+ }21+22+ for (const [fdNumber, inputStreams] of Object.entries(inputStreamsGroups)) {23+ const inputStream = inputStreams.length === 1 ? inputStreams[0] : mergeStreams(inputStreams);24+ pipeStreams(inputStream, subprocess.stdio[fdNumber]);25+ }26+};27+28+// `subprocess.stdin|stdout|stderr|stdio` is directly mutated.29+const pipeTransform = (subprocess, stream, direction, fdNumber) => {30+ if (direction === 'output') {31+ pipeStreams(subprocess.stdio[fdNumber], stream);32+ } else {33+ pipeStreams(stream, subprocess.stdio[fdNumber]);34+ }35+36+ const streamProperty = SUBPROCESS_STREAM_PROPERTIES[fdNumber];37+ if (streamProperty !== undefined) {38+ subprocess[streamProperty] = stream;39+ }40+41+ subprocess.stdio[fdNumber] = stream;42+};43+44+const SUBPROCESS_STREAM_PROPERTIES = ['stdin', 'stdout', 'stderr'];45+46+const pipeStdioItem = ({subprocess, stream, direction, fdNumber, inputStreamsGroups, controller}) => {47+ if (stream === undefined) {48+ return;49+ }50+51+ setStandardStreamMaxListeners(stream, controller);52+53+ if (direction === 'output') {54+ pipeStreams(subprocess.stdio[fdNumber], stream);55+ } else {56+ inputStreamsGroups[fdNumber] = [...(inputStreamsGroups[fdNumber] ?? []), stream];57+ }58+};59+60+// Multiple subprocesses might be piping from/to `process.std*` at the same time.61+// This is not necessarily an error and should not print a `maxListeners` warning.62+const setStandardStreamMaxListeners = (stream, {signal}) => {63+ if (isStandardStream(stream)) {64+ incrementMaxListeners(stream, MAX_LISTENERS_INCREMENT, signal);65+ }66+};67+68+// `source.pipe(destination)` adds at most 1 listener for each event.69+// If `stdin` option is an array, the values might be combined with `merge-streams`.70+// That library also listens for `source` end, which adds 1 more listener.71+const MAX_LISTENERS_INCREMENT = 2;added:lib/io/output-sync.js+90 added
1+import {writeFileSync} from 'node:fs';2+import {shouldLogOutput, logLinesSync} from '../verbose/output.js';3+import {runGeneratorsSync} from '../transform/generator.js';4+import {splitLinesSync} from '../transform/split.js';5+import {joinToString, joinToUint8Array, bufferToUint8Array} from '../utils/uint-array.js';6+import {FILE_TYPES} from '../stdio/type.js';7+import {getMaxBufferSync} from './max-buffer.js';8+9+// Apply `stdout`/`stderr` options, after spawning, in sync mode10+export const transformOutputSync = ({fileDescriptors, syncResult: {output}, options, isMaxBuffer, verboseInfo}) => {11+ if (output === null) {12+ return {output: Array.from({length: 3})};13+ }14+15+ const state = {};16+ const transformedOutput = output.map((result, fdNumber) =>17+ transformOutputResultSync({result, fileDescriptors, fdNumber, state, isMaxBuffer, verboseInfo}, options));18+ return {output: transformedOutput, ...state};19+};20+21+const transformOutputResultSync = ({result, fileDescriptors, fdNumber, state, isMaxBuffer, verboseInfo}, {buffer, encoding, lines, stripFinalNewline, maxBuffer}) => {22+ if (result === null) {23+ return;24+ }25+26+ const truncatedResult = truncateResult(result, isMaxBuffer, getMaxBufferSync(maxBuffer));27+ const uint8ArrayResult = bufferToUint8Array(truncatedResult);28+ const {stdioItems, objectMode} = fileDescriptors[fdNumber];29+ const chunks = runOutputGeneratorsSync([uint8ArrayResult], stdioItems, encoding, state);30+ const {31+ serializedResult,32+ finalResult = serializedResult,33+ } = serializeChunks({chunks, objectMode, encoding, lines, stripFinalNewline, fdNumber});34+35+ if (shouldLogOutput({stdioItems, encoding, verboseInfo, fdNumber})) {36+ const linesArray = splitLinesSync(serializedResult, false, objectMode);37+ logLinesSync(linesArray, verboseInfo);38+ }39+40+ const returnedResult = buffer[fdNumber] ? finalResult : undefined;41+42+ try {43+ if (state.error === undefined) {44+ writeToFiles(serializedResult, stdioItems);45+ }46+47+ return returnedResult;48+ } catch (error) {49+ state.error = error;50+ return returnedResult;51+ }52+};53+54+const truncateResult = (result, isMaxBuffer, maxBuffer) => isMaxBuffer && result.length > maxBuffer55+ ? result.slice(0, maxBuffer)56+ : result;57+58+const runOutputGeneratorsSync = (chunks, stdioItems, encoding, state) => {59+ try {60+ return runGeneratorsSync(chunks, stdioItems, encoding, false);61+ } catch (error) {62+ state.error = error;63+ return chunks;64+ }65+};66+67+const serializeChunks = ({chunks, objectMode, encoding, lines, stripFinalNewline, fdNumber}) => {68+ if (objectMode) {69+ return {serializedResult: chunks};70+ }71+72+ if (encoding === 'buffer') {73+ return {serializedResult: joinToUint8Array(chunks)};74+ }75+76+ const serializedResult = joinToString(chunks, encoding);77+ if (lines[fdNumber]) {78+ return {serializedResult, finalResult: splitLinesSync(serializedResult, !stripFinalNewline[fdNumber], objectMode)};79+ }80+81+ return {serializedResult};82+};83+84+const writeToFiles = (serializedResult, stdioItems) => {85+ for (const {type, path} of stdioItems) {86+ if (FILE_TYPES.has(type)) {87+ writeFileSync(path, serializedResult);88+ }89+ }90+};added:lib/io/pipeline.js+48 added
1+import {finished} from 'node:stream/promises';2+import {isStandardStream} from '../utils/standard-stream.js';3+4+// Like `Stream.pipeline(source, destination)`, but does not destroy standard streams.5+export const pipeStreams = (source, destination) => {6+ source.pipe(destination);7+ onSourceFinish(source, destination);8+ onDestinationFinish(source, destination);9+};10+11+// `source.pipe(destination)` makes `destination` end when `source` ends.12+// But it does not propagate aborts or errors. This function does it.13+const onSourceFinish = async (source, destination) => {14+ if (isStandardStream(source) || isStandardStream(destination)) {15+ return;16+ }17+18+ try {19+ await finished(source, {cleanup: true, readable: true, writable: false});20+ } catch {}21+22+ endDestinationStream(destination);23+};24+25+export const endDestinationStream = destination => {26+ if (destination.writable) {27+ destination.end();28+ }29+};30+31+// We do the same thing in the other direction as well.32+const onDestinationFinish = async (source, destination) => {33+ if (isStandardStream(source) || isStandardStream(destination)) {34+ return;35+ }36+37+ try {38+ await finished(destination, {cleanup: true, readable: false, writable: true});39+ } catch {}40+41+ abortSourceStream(source);42+};43+44+export const abortSourceStream = source => {45+ if (source.readable) {46+ source.destroy();47+ }48+};added:lib/io/strip-newline.js+9 added
1+import stripFinalNewlineFunction from 'strip-final-newline';2+3+export const stripNewline = (value, {stripFinalNewline}, fdNumber) => getStripFinalNewline(stripFinalNewline, fdNumber) && value !== undefined && !Array.isArray(value)4+ ? stripFinalNewlineFunction(value)5+ : value;6+7+export const getStripFinalNewline = (stripFinalNewline, fdNumber) => fdNumber === 'all'8+ ? stripFinalNewline[1] || stripFinalNewline[2]9+ : stripFinalNewline[fdNumber];added:lib/methods/command.js+25 added
1+export const mapCommandAsync = ({file, args}) => parseCommand(file, args);2+export const mapCommandSync = ({file, args}) => ({...parseCommand(file, args), isSync: true});3+4+const parseCommand = (command, unusedArgs) => {5+ if (unusedArgs.length > 0) {6+ throw new TypeError(`The command and its arguments must be passed as a single string: ${command} ${unusedArgs}.`);7+ }8+9+ const tokens = [];10+ for (const token of command.trim().split(SPACES_REGEXP)) {11+ // Allow spaces to be escaped by a backslash if not meant as a delimiter12+ const previousToken = tokens.at(-1);13+ if (previousToken && previousToken.endsWith('\\')) {14+ // Merge previous token with current one15+ tokens[tokens.length - 1] = `${previousToken.slice(0, -1)} ${token}`;16+ } else {17+ tokens.push(token);18+ }19+ }20+21+ const [file, ...args] = tokens;22+ return {file, args};23+};24+25+const SPACES_REGEXP = / +/g;added:lib/methods/create.js+64 added
1+import isPlainObject from 'is-plain-obj';2+import {FD_SPECIFIC_OPTIONS} from '../arguments/specific.js';3+import {normalizeParameters} from './parameters.js';4+import {isTemplateString, parseTemplates} from './template.js';5+import {execaCoreSync} from './main-sync.js';6+import {execaCoreAsync} from './main-async.js';7+8+export const createExeca = (mapArguments, boundOptions, deepOptions, setBoundExeca) => {9+ const createNested = (mapArguments, boundOptions, setBoundExeca) => createExeca(mapArguments, boundOptions, deepOptions, setBoundExeca);10+ const boundExeca = (...args) => callBoundExeca({mapArguments, deepOptions, boundOptions, setBoundExeca, createNested}, ...args);11+12+ if (setBoundExeca !== undefined) {13+ setBoundExeca(boundExeca, createNested, boundOptions);14+ }15+16+ return boundExeca;17+};18+19+const callBoundExeca = ({mapArguments, deepOptions = {}, boundOptions = {}, setBoundExeca, createNested}, firstArgument, ...nextArguments) => {20+ if (isPlainObject(firstArgument)) {21+ return createNested(mapArguments, mergeOptions(boundOptions, firstArgument), setBoundExeca);22+ }23+24+ const {file, args, options, isSync} = parseArguments({mapArguments, firstArgument, nextArguments, deepOptions, boundOptions});25+ return isSync26+ ? execaCoreSync(file, args, options)27+ : execaCoreAsync(file, args, options, createNested);28+};29+30+const parseArguments = ({mapArguments, firstArgument, nextArguments, deepOptions, boundOptions}) => {31+ const callArguments = isTemplateString(firstArgument)32+ ? parseTemplates(firstArgument, nextArguments)33+ : [firstArgument, ...nextArguments];34+ const [rawFile, rawArgs, rawOptions] = normalizeParameters(...callArguments);35+ const mergedOptions = mergeOptions(mergeOptions(deepOptions, boundOptions), rawOptions);36+ const {37+ file = rawFile,38+ args = rawArgs,39+ options = mergedOptions,40+ isSync = false,41+ } = mapArguments({file: rawFile, args: rawArgs, options: mergedOptions});42+ return {file, args, options, isSync};43+};44+45+// Deep merge specific options like `env`. Shallow merge the other ones.46+const mergeOptions = (boundOptions, options) => {47+ const newOptions = Object.fromEntries(48+ Object.entries(options).map(([optionName, optionValue]) => [49+ optionName,50+ mergeOption(optionName, boundOptions[optionName], optionValue),51+ ]),52+ );53+ return {...boundOptions, ...newOptions};54+};55+56+const mergeOption = (optionName, boundOptionValue, optionValue) => {57+ if (DEEP_OPTIONS.has(optionName) && isPlainObject(boundOptionValue) && isPlainObject(optionValue)) {58+ return {...boundOptionValue, ...optionValue};59+ }60+61+ return optionValue;62+};63+64+const DEEP_OPTIONS = new Set(['env', ...FD_SPECIFIC_OPTIONS]);added:lib/methods/main-async.js+110 added
1+import {setMaxListeners} from 'node:events';2+import {spawn} from 'node:child_process';3+import {MaxBufferError} from 'get-stream';4+import {handleCommand} from '../arguments/command.js';5+import {handleOptions} from '../arguments/options.js';6+import {SUBPROCESS_OPTIONS} from '../arguments/fd-options.js';7+import {makeError, makeSuccessResult} from '../return/result.js';8+import {handleResult} from '../return/reject.js';9+import {handleEarlyError} from '../return/early-error.js';10+import {handleStdioAsync} from '../stdio/handle-async.js';11+import {stripNewline} from '../io/strip-newline.js';12+import {pipeOutputAsync} from '../io/output-async.js';13+import {subprocessKill} from '../terminate/kill.js';14+import {cleanupOnExit} from '../terminate/cleanup.js';15+import {pipeToSubprocess} from '../pipe/setup.js';16+import {logEarlyResult} from '../verbose/complete.js';17+import {makeAllStream} from '../resolve/all-async.js';18+import {waitForSubprocessResult} from '../resolve/wait-subprocess.js';19+import {addConvertedStreams} from '../convert/add.js';20+import {mergePromise} from './promise.js';21+22+export const execaCoreAsync = (rawFile, rawArgs, rawOptions, createNested) => {23+ const {file, args, command, escapedCommand, startTime, verboseInfo, options, fileDescriptors} = handleAsyncArguments(rawFile, rawArgs, rawOptions);24+ const {subprocess, promise} = spawnSubprocessAsync({file, args, options, startTime, verboseInfo, command, escapedCommand, fileDescriptors});25+ subprocess.pipe = pipeToSubprocess.bind(undefined, {source: subprocess, sourcePromise: promise, boundOptions: {}, createNested});26+ mergePromise(subprocess, promise);27+ SUBPROCESS_OPTIONS.set(subprocess, {options, fileDescriptors});28+ return subprocess;29+};30+31+const handleAsyncArguments = (rawFile, rawArgs, rawOptions) => {32+ const {command, escapedCommand, startTime, verboseInfo} = handleCommand(rawFile, rawArgs, rawOptions);33+34+ try {35+ const {file, args, options: normalizedOptions} = handleOptions(rawFile, rawArgs, rawOptions);36+ const options = handleAsyncOptions(normalizedOptions);37+ const fileDescriptors = handleStdioAsync(options, verboseInfo);38+ return {file, args, command, escapedCommand, startTime, verboseInfo, options, fileDescriptors};39+ } catch (error) {40+ logEarlyResult(error, startTime, verboseInfo);41+ throw error;42+ }43+};44+45+// Prevent passing the `timeout` option directly to `child_process.spawn()`46+const handleAsyncOptions = ({timeout, signal, cancelSignal, ...options}) => {47+ if (signal !== undefined) {48+ throw new TypeError('The "signal" option has been renamed to "cancelSignal" instead.');49+ }50+51+ return {...options, timeoutDuration: timeout, signal: cancelSignal};52+};53+54+const spawnSubprocessAsync = ({file, args, options, startTime, verboseInfo, command, escapedCommand, fileDescriptors}) => {55+ let subprocess;56+ try {57+ subprocess = spawn(file, args, options);58+ } catch (error) {59+ return handleEarlyError({error, command, escapedCommand, fileDescriptors, options, startTime, verboseInfo});60+ }61+62+ const controller = new AbortController();63+ setMaxListeners(Number.POSITIVE_INFINITY, controller.signal);64+65+ const originalStreams = [...subprocess.stdio];66+ pipeOutputAsync(subprocess, fileDescriptors, controller);67+ cleanupOnExit(subprocess, options, controller);68+69+ subprocess.kill = subprocessKill.bind(undefined, {kill: subprocess.kill.bind(subprocess), subprocess, options, controller});70+ subprocess.all = makeAllStream(subprocess, options);71+ addConvertedStreams(subprocess, options);72+73+ const promise = handlePromise({subprocess, options, startTime, verboseInfo, fileDescriptors, originalStreams, command, escapedCommand, controller});74+ return {subprocess, promise};75+};76+77+const handlePromise = async ({subprocess, options, startTime, verboseInfo, fileDescriptors, originalStreams, command, escapedCommand, controller}) => {78+ const context = {timedOut: false};79+80+ const [81+ errorInfo,82+ [exitCode, signal],83+ stdioResults,84+ allResult,85+ ] = await waitForSubprocessResult({subprocess, options, context, verboseInfo, fileDescriptors, originalStreams, controller});86+ controller.abort();87+88+ const stdio = stdioResults.map((stdioResult, fdNumber) => stripNewline(stdioResult, options, fdNumber));89+ const all = stripNewline(allResult, options, 'all');90+ const result = getAsyncResult({errorInfo, exitCode, signal, stdio, all, context, options, command, escapedCommand, startTime});91+ return handleResult(result, verboseInfo, options);92+};93+94+const getAsyncResult = ({errorInfo, exitCode, signal, stdio, all, context, options, command, escapedCommand, startTime}) => 'error' in errorInfo95+ ? makeError({96+ error: errorInfo.error,97+ command,98+ escapedCommand,99+ timedOut: context.timedOut,100+ isCanceled: options.signal?.aborted === true,101+ isMaxBuffer: errorInfo.error instanceof MaxBufferError,102+ exitCode,103+ signal,104+ stdio,105+ all,106+ options,107+ startTime,108+ isSync: false,109+ })110+ : makeSuccessResult({command, escapedCommand, stdio, all, options, startTime});added:lib/methods/main-sync.js+97 added
1+import {spawnSync} from 'node:child_process';2+import {handleCommand} from '../arguments/command.js';3+import {handleOptions} from '../arguments/options.js';4+import {makeError, makeEarlyError, makeSuccessResult} from '../return/result.js';5+import {handleResult} from '../return/reject.js';6+import {handleStdioSync} from '../stdio/handle-sync.js';7+import {stripNewline} from '../io/strip-newline.js';8+import {addInputOptionsSync} from '../io/input-sync.js';9+import {transformOutputSync} from '../io/output-sync.js';10+import {getMaxBufferSync} from '../io/max-buffer.js';11+import {logEarlyResult} from '../verbose/complete.js';12+import {getAllSync} from '../resolve/all-sync.js';13+import {getExitResultSync} from '../resolve/exit-sync.js';14+15+export const execaCoreSync = (rawFile, rawArgs, rawOptions) => {16+ const {file, args, command, escapedCommand, startTime, verboseInfo, options, fileDescriptors} = handleSyncArguments(rawFile, rawArgs, rawOptions);17+ const result = spawnSubprocessSync({file, args, options, command, escapedCommand, verboseInfo, fileDescriptors, startTime});18+ return handleResult(result, verboseInfo, options);19+};20+21+const handleSyncArguments = (rawFile, rawArgs, rawOptions) => {22+ const {command, escapedCommand, startTime, verboseInfo} = handleCommand(rawFile, rawArgs, rawOptions);23+24+ try {25+ const syncOptions = normalizeSyncOptions(rawOptions);26+ const {file, args, options} = handleOptions(rawFile, rawArgs, syncOptions);27+ validateSyncOptions(options);28+ const fileDescriptors = handleStdioSync(options, verboseInfo);29+ return {file, args, command, escapedCommand, startTime, verboseInfo, options, fileDescriptors};30+ } catch (error) {31+ logEarlyResult(error, startTime, verboseInfo);32+ throw error;33+ }34+};35+36+const normalizeSyncOptions = options => options.node && !options.ipc ? {...options, ipc: false} : options;37+38+const validateSyncOptions = ({ipc, detached, cancelSignal}) => {39+ if (ipc) {40+ throwInvalidSyncOption('ipc: true');41+ }42+43+ if (detached) {44+ throwInvalidSyncOption('detached: true');45+ }46+47+ if (cancelSignal) {48+ throwInvalidSyncOption('cancelSignal');49+ }50+};51+52+const throwInvalidSyncOption = value => {53+ throw new TypeError(`The "${value}" option cannot be used with synchronous methods.`);54+};55+56+const spawnSubprocessSync = ({file, args, options, command, escapedCommand, verboseInfo, fileDescriptors, startTime}) => {57+ const syncResult = runSubprocessSync({file, args, options, command, escapedCommand, fileDescriptors, startTime});58+ if (syncResult.failed) {59+ return syncResult;60+ }61+62+ const {resultError, exitCode, signal, timedOut, isMaxBuffer} = getExitResultSync(syncResult, options);63+ const {output, error = resultError} = transformOutputSync({fileDescriptors, syncResult, options, isMaxBuffer, verboseInfo});64+ const stdio = output.map((stdioOutput, fdNumber) => stripNewline(stdioOutput, options, fdNumber));65+ const all = stripNewline(getAllSync(output, options), options, 'all');66+ return getSyncResult({error, exitCode, signal, timedOut, isMaxBuffer, stdio, all, options, command, escapedCommand, startTime});67+};68+69+const runSubprocessSync = ({file, args, options, command, escapedCommand, fileDescriptors, startTime}) => {70+ try {71+ addInputOptionsSync(fileDescriptors, options);72+ const normalizedOptions = normalizeSpawnSyncOptions(options);73+ return spawnSync(file, args, normalizedOptions);74+ } catch (error) {75+ return makeEarlyError({error, command, escapedCommand, fileDescriptors, options, startTime, isSync: true});76+ }77+};78+79+const normalizeSpawnSyncOptions = ({encoding, maxBuffer, ...options}) => ({...options, encoding: 'buffer', maxBuffer: getMaxBufferSync(maxBuffer)});80+81+const getSyncResult = ({error, exitCode, signal, timedOut, isMaxBuffer, stdio, all, options, command, escapedCommand, startTime}) => error === undefined82+ ? makeSuccessResult({command, escapedCommand, stdio, all, options, startTime})83+ : makeError({84+ error,85+ command,86+ escapedCommand,87+ timedOut,88+ isCanceled: false,89+ isMaxBuffer,90+ exitCode,91+ signal,92+ stdio,93+ all,94+ options,95+ startTime,96+ isSync: true,97+ });added:lib/methods/node.js+42 added
1+import {execPath, execArgv} from 'node:process';2+import {basename, resolve} from 'node:path';3+import {safeNormalizeFileUrl} from '../arguments/file-url.js';4+5+export const mapNode = ({options}) => {6+ if (options.node === false) {7+ throw new TypeError('The "node" option cannot be false with `execaNode()`.');8+ }9+10+ return {options: {...options, node: true}};11+};12+13+export const handleNodeOption = (file, args, {14+ node: shouldHandleNode = false,15+ nodePath = execPath,16+ nodeOptions = execArgv.filter(arg => !arg.startsWith('--inspect')),17+ cwd,18+ execPath: formerNodePath,19+ ...options20+}) => {21+ if (formerNodePath !== undefined) {22+ throw new TypeError('The "execPath" option has been removed. Please use the "nodePath" option instead.');23+ }24+25+ const normalizedNodePath = safeNormalizeFileUrl(nodePath, 'The "nodePath" option');26+ const resolvedNodePath = resolve(cwd, normalizedNodePath);27+ const newOptions = {...options, nodePath: resolvedNodePath, node: shouldHandleNode, cwd};28+29+ if (!shouldHandleNode) {30+ return [file, args, newOptions];31+ }32+33+ if (basename(file, '.exe') === 'node') {34+ throw new TypeError('When the "node" option is true, the first argument does not need to be "node".');35+ }36+37+ return [38+ resolvedNodePath,39+ [...nodeOptions, file, ...args],40+ {ipc: true, ...newOptions, shell: false},41+ ];42+};added:lib/methods/parameters.js+29 added
1+import isPlainObject from 'is-plain-obj';2+import {safeNormalizeFileUrl} from '../arguments/file-url.js';3+4+export const normalizeParameters = (rawFile, rawArgs = [], rawOptions = {}) => {5+ const filePath = safeNormalizeFileUrl(rawFile, 'First argument');6+ const [args, options] = isPlainObject(rawArgs)7+ ? [[], rawArgs]8+ : [rawArgs, rawOptions];9+10+ if (!Array.isArray(args)) {11+ throw new TypeError(`Second argument must be either an array of arguments or an options object: ${args}`);12+ }13+14+ if (args.some(arg => typeof arg === 'object' && arg !== null)) {15+ throw new TypeError(`Second argument must be an array of strings: ${args}`);16+ }17+18+ const normalizedArgs = args.map(String);19+ const nullByteArg = normalizedArgs.find(arg => arg.includes('\0'));20+ if (nullByteArg !== undefined) {21+ throw new TypeError(`Arguments cannot contain null bytes ("\\0"): ${nullByteArg}`);22+ }23+24+ if (!isPlainObject(options)) {25+ throw new TypeError(`Last argument must be an options object: ${options}`);26+ }27+28+ return [filePath, normalizedArgs, options];29+};added:lib/methods/promise.js+15 added
1+// The return value is a mixin of `subprocess` and `Promise`2+export const mergePromise = (subprocess, promise) => {3+ for (const [property, descriptor] of descriptors) {4+ const value = descriptor.value.bind(promise);5+ Reflect.defineProperty(subprocess, property, {...descriptor, value});6+ }7+};8+9+// eslint-disable-next-line unicorn/prefer-top-level-await10+const nativePromisePrototype = (async () => {})().constructor.prototype;11+12+const descriptors = ['then', 'catch', 'finally'].map(property => [13+ property,14+ Reflect.getOwnPropertyDescriptor(nativePromisePrototype, property),15+]);added:lib/methods/script.js+15 added
1+export const setScriptSync = (boundExeca, createNested, boundOptions) => {2+ boundExeca.sync = createNested(mapScriptSync, boundOptions);3+ boundExeca.s = boundExeca.sync;4+};5+6+export const mapScriptAsync = ({options}) => getScriptOptions(options);7+const mapScriptSync = ({options}) => ({...getScriptOptions(options), isSync: true});8+9+const getScriptOptions = options => ({options: {...getScriptStdinOption(options), ...options}});10+11+const getScriptStdinOption = ({input, inputFile, stdio}) => input === undefined && inputFile === undefined && stdio === undefined12+ ? {stdin: 'inherit'}13+ : {};14+15+export const deepScriptOptions = {preferLocal: true};added:lib/methods/template.js+135 added
1+import {ChildProcess} from 'node:child_process';2+import {isUint8Array, uint8ArrayToString} from '../utils/uint-array.js';3+4+export const isTemplateString = templates => Array.isArray(templates) && Array.isArray(templates.raw);5+6+export const parseTemplates = (templates, expressions) => {7+ let tokens = [];8+9+ for (const [index, template] of templates.entries()) {10+ tokens = parseTemplate({templates, expressions, tokens, index, template});11+ }12+13+ if (tokens.length === 0) {14+ throw new TypeError('Template script must not be empty');15+ }16+17+ const [file, ...args] = tokens;18+ return [file, args, {}];19+};20+21+const parseTemplate = ({templates, expressions, tokens, index, template}) => {22+ if (template === undefined) {23+ throw new TypeError(`Invalid backslash sequence: ${templates.raw[index]}`);24+ }25+26+ const {nextTokens, leadingWhitespaces, trailingWhitespaces} = splitByWhitespaces(template, templates.raw[index]);27+ const newTokens = concatTokens(tokens, nextTokens, leadingWhitespaces);28+29+ if (index === expressions.length) {30+ return newTokens;31+ }32+33+ const expression = expressions[index];34+ const expressionTokens = Array.isArray(expression)35+ ? expression.map(expression => parseExpression(expression))36+ : [parseExpression(expression)];37+ return concatTokens(newTokens, expressionTokens, trailingWhitespaces);38+};39+40+// Like `string.split(/[ \t\r\n]+/)` except newlines and tabs are:41+// - ignored when input as a backslash sequence like: `echo foo\n bar`42+// - not ignored when input directly43+// The only way to distinguish those in JavaScript is to use a tagged template and compare:44+// - the first array argument, which does not escape backslash sequences45+// - its `raw` property, which escapes them46+const splitByWhitespaces = (template, rawTemplate) => {47+ if (rawTemplate.length === 0) {48+ return {nextTokens: [], leadingWhitespaces: false, trailingWhitespaces: false};49+ }50+51+ const nextTokens = [];52+ let templateStart = 0;53+ const leadingWhitespaces = DELIMITERS.has(rawTemplate[0]);54+55+ for (56+ let templateIndex = 0, rawIndex = 0;57+ templateIndex < template.length;58+ templateIndex += 1, rawIndex += 159+ ) {60+ const rawCharacter = rawTemplate[rawIndex];61+ if (DELIMITERS.has(rawCharacter)) {62+ if (templateStart !== templateIndex) {63+ nextTokens.push(template.slice(templateStart, templateIndex));64+ }65+66+ templateStart = templateIndex + 1;67+ } else if (rawCharacter === '\\') {68+ const nextRawCharacter = rawTemplate[rawIndex + 1];69+ if (nextRawCharacter === 'u' && rawTemplate[rawIndex + 2] === '{') {70+ rawIndex = rawTemplate.indexOf('}', rawIndex + 3);71+ } else {72+ rawIndex += ESCAPE_LENGTH[nextRawCharacter] ?? 1;73+ }74+ }75+ }76+77+ const trailingWhitespaces = templateStart === template.length;78+ if (!trailingWhitespaces) {79+ nextTokens.push(template.slice(templateStart));80+ }81+82+ return {nextTokens, leadingWhitespaces, trailingWhitespaces};83+};84+85+const DELIMITERS = new Set([' ', '\t', '\r', '\n']);86+87+// Number of characters in backslash escape sequences: \0 \xXX or \uXXXX88+// \cX is allowed in RegExps but not in strings89+// Octal sequences are not allowed in strict mode90+const ESCAPE_LENGTH = {x: 3, u: 5};91+92+const concatTokens = (tokens, nextTokens, isSeparated) => isSeparated93+ || tokens.length === 094+ || nextTokens.length === 095+ ? [...tokens, ...nextTokens]96+ : [97+ ...tokens.slice(0, -1),98+ `${tokens.at(-1)}${nextTokens[0]}`,99+ ...nextTokens.slice(1),100+ ];101+102+const parseExpression = expression => {103+ const typeOfExpression = typeof expression;104+105+ if (typeOfExpression === 'string') {106+ return expression;107+ }108+109+ if (typeOfExpression === 'number') {110+ return String(expression);111+ }112+113+ if (114+ typeOfExpression === 'object'115+ && expression !== null116+ && !isSubprocess(expression)117+ && 'stdout' in expression118+ ) {119+ const typeOfStdout = typeof expression.stdout;120+121+ if (typeOfStdout === 'string') {122+ return expression.stdout;123+ }124+125+ if (isUint8Array(expression.stdout)) {126+ return uint8ArrayToString(expression.stdout);127+ }128+129+ throw new TypeError(`Unexpected "${typeOfStdout}" stdout in template expression`);130+ }131+132+ throw new TypeError(`Unexpected "${typeOfExpression}" in template expression`);133+};134+135+const isSubprocess = value => value instanceof ChildProcess;added:lib/pipe/pipe-arguments.js+79 added
1+import {normalizeParameters} from '../methods/parameters.js';2+import {getStartTime} from '../return/duration.js';3+import {SUBPROCESS_OPTIONS, getWritable, getReadable} from '../arguments/fd-options.js';4+5+export const normalizePipeArguments = ({source, sourcePromise, boundOptions, createNested}, ...args) => {6+ const startTime = getStartTime();7+ const {8+ destination,9+ destinationStream,10+ destinationError,11+ from,12+ unpipeSignal,13+ } = getDestinationStream(boundOptions, createNested, args);14+ const {sourceStream, sourceError} = getSourceStream(source, from);15+ const {options: sourceOptions, fileDescriptors} = SUBPROCESS_OPTIONS.get(source);16+ return {17+ sourcePromise,18+ sourceStream,19+ sourceOptions,20+ sourceError,21+ destination,22+ destinationStream,23+ destinationError,24+ unpipeSignal,25+ fileDescriptors,26+ startTime,27+ };28+};29+30+const getDestinationStream = (boundOptions, createNested, args) => {31+ try {32+ const {33+ destination,34+ pipeOptions: {from, to, unpipeSignal} = {},35+ } = getDestination(boundOptions, createNested, ...args);36+ const destinationStream = getWritable(destination, to);37+ return {destination, destinationStream, from, unpipeSignal};38+ } catch (error) {39+ return {destinationError: error};40+ }41+};42+43+const getDestination = (boundOptions, createNested, firstArgument, ...args) => {44+ if (Array.isArray(firstArgument)) {45+ const destination = createNested(mapDestinationArguments, boundOptions)(firstArgument, ...args);46+ return {destination, pipeOptions: boundOptions};47+ }48+49+ if (typeof firstArgument === 'string' || firstArgument instanceof URL) {50+ if (Object.keys(boundOptions).length > 0) {51+ throw new TypeError('Please use .pipe("file", ..., options) or .pipe(execa("file", ..., options)) instead of .pipe(options)("file", ...).');52+ }53+54+ const [rawFile, rawArgs, rawOptions] = normalizeParameters(firstArgument, ...args);55+ const destination = createNested(mapDestinationArguments)(rawFile, rawArgs, rawOptions);56+ return {destination, pipeOptions: rawOptions};57+ }58+59+ if (SUBPROCESS_OPTIONS.has(firstArgument)) {60+ if (Object.keys(boundOptions).length > 0) {61+ throw new TypeError('Please use .pipe(options)`command` or .pipe($(options)`command`) instead of .pipe(options)($`command`).');62+ }63+64+ return {destination: firstArgument, pipeOptions: args[0]};65+ }66+67+ throw new TypeError(`The first argument must be a template string, an options object, or an Execa subprocess: ${firstArgument}`);68+};69+70+const mapDestinationArguments = ({options}) => ({options: {...options, stdin: 'pipe', piped: true}});71+72+const getSourceStream = (source, from) => {73+ try {74+ const sourceStream = getReadable(source, from);75+ return {sourceStream};76+ } catch (error) {77+ return {sourceError: error};78+ }79+};modified:lib/pipe/setup.js+1 added-1 removed
1 import isPlainObject from 'is-plain-obj';2-import {normalizePipeArguments} from './validate.js';2+import {normalizePipeArguments} from './pipe-arguments.js';3 import {handlePipeArgumentsError} from './throw.js';4 import {waitForBothSubprocesses} from './sequence.js';5 import {pipeSubprocessStream} from './streaming.js';6 import {unpipeOnAbort} from './abort.js';54 unmodified linesmodified:lib/pipe/streaming.js+2 added-2 removed
1 import {finished} from 'node:stream/promises';2 import mergeStreams from '@sindresorhus/merge-streams';3-import {incrementMaxListeners} from '../max-listener.js';4-import {pipeStreams} from '../stdio/pipeline.js';3+import {incrementMaxListeners} from '../utils/max-listeners.js';4+import {pipeStreams} from '../io/pipeline.js';5 6 // The piping behavior is like Bash.7 // In particular, when one subprocess exits, the other is not terminated by a signal.8 // Instead, its stdout (for the source) or stdin (for the destination) closes.43 unmodified linesmodified:lib/pipe/throw.js+2 added-2 removed
1-import {makeEarlyError} from '../return/error.js';2-import {abortSourceStream, endDestinationStream} from '../stdio/pipeline.js';1+import {makeEarlyError} from '../return/result.js';2+import {abortSourceStream, endDestinationStream} from '../io/pipeline.js';3 4 export const handlePipeArgumentsError = ({5 sourceStream,6 sourceError,39 unmodified linesdeleted:lib/pipe/validate.js-79 removed
1-import {normalizeArguments} from '../arguments/normalize.js';2-import {getStartTime} from '../return/duration.js';3-import {SUBPROCESS_OPTIONS, getWritable, getReadable} from '../convert/fd-options.js';4-5-export const normalizePipeArguments = ({source, sourcePromise, boundOptions, createNested}, ...args) => {6- const startTime = getStartTime();7- const {8- destination,9- destinationStream,10- destinationError,11- from,12- unpipeSignal,13- } = getDestinationStream(boundOptions, createNested, args);14- const {sourceStream, sourceError} = getSourceStream(source, from);15- const {options: sourceOptions, fileDescriptors} = SUBPROCESS_OPTIONS.get(source);16- return {17- sourcePromise,18- sourceStream,19- sourceOptions,20- sourceError,21- destination,22- destinationStream,23- destinationError,24- unpipeSignal,25- fileDescriptors,26- startTime,27- };28-};29-30-const getDestinationStream = (boundOptions, createNested, args) => {31- try {32- const {33- destination,34- pipeOptions: {from, to, unpipeSignal} = {},35- } = getDestination(boundOptions, createNested, ...args);36- const destinationStream = getWritable(destination, to);37- return {destination, destinationStream, from, unpipeSignal};38- } catch (error) {39- return {destinationError: error};40- }41-};42-43-const getDestination = (boundOptions, createNested, firstArgument, ...args) => {44- if (Array.isArray(firstArgument)) {45- const destination = createNested(mapDestinationArguments, boundOptions)(firstArgument, ...args);46- return {destination, pipeOptions: boundOptions};47- }48-49- if (typeof firstArgument === 'string' || firstArgument instanceof URL) {50- if (Object.keys(boundOptions).length > 0) {51- throw new TypeError('Please use .pipe("file", ..., options) or .pipe(execa("file", ..., options)) instead of .pipe(options)("file", ...).');52- }53-54- const [rawFile, rawArgs, rawOptions] = normalizeArguments(firstArgument, ...args);55- const destination = createNested(mapDestinationArguments)(rawFile, rawArgs, rawOptions);56- return {destination, pipeOptions: rawOptions};57- }58-59- if (SUBPROCESS_OPTIONS.has(firstArgument)) {60- if (Object.keys(boundOptions).length > 0) {61- throw new TypeError('Please use .pipe(options)`command` or .pipe($(options)`command`) instead of .pipe(options)($`command`).');62- }63-64- return {destination: firstArgument, pipeOptions: args[0]};65- }66-67- throw new TypeError(`The first argument must be a template string, an options object, or an Execa subprocess: ${firstArgument}`);68-};69-70-const mapDestinationArguments = ({options}) => ({options: {...options, stdin: 'pipe', piped: true}});71-72-const getSourceStream = (source, from) => {73- try {74- const sourceStream = getReadable(source, from);75- return {sourceStream};76- } catch (error) {77- return {sourceError: error};78- }79-};added:lib/resolve/all-async.js+46 added
1+import mergeStreams from '@sindresorhus/merge-streams';2+import {waitForSubprocessStream} from './stdio.js';3+4+// `all` interleaves `stdout` and `stderr`5+export const makeAllStream = ({stdout, stderr}, {all}) => all && (stdout || stderr)6+ ? mergeStreams([stdout, stderr].filter(Boolean))7+ : undefined;8+9+// Read the contents of `subprocess.all` and|or wait for its completion10+export const waitForAllStream = ({subprocess, encoding, buffer, maxBuffer, lines, stripFinalNewline, verboseInfo, streamInfo}) => waitForSubprocessStream({11+ ...getAllStream(subprocess, buffer),12+ fdNumber: 'all',13+ encoding,14+ maxBuffer: maxBuffer[1] + maxBuffer[2],15+ lines: lines[1] || lines[2],16+ allMixed: getAllMixed(subprocess),17+ stripFinalNewline,18+ verboseInfo,19+ streamInfo,20+});21+22+const getAllStream = ({stdout, stderr, all}, [, bufferStdout, bufferStderr]) => {23+ const buffer = bufferStdout || bufferStderr;24+ if (!buffer) {25+ return {stream: all, buffer};26+ }27+28+ if (!bufferStdout) {29+ return {stream: stderr, buffer};30+ }31+32+ if (!bufferStderr) {33+ return {stream: stdout, buffer};34+ }35+36+ return {stream: all, buffer};37+};38+39+// When `subprocess.stdout` is in objectMode but not `subprocess.stderr` (or the opposite), we need to use both:40+// - `getStreamAsArray()` for the chunks in objectMode, to return as an array without changing each chunk41+// - `getStreamAsArrayBuffer()` or `getStream()` for the chunks not in objectMode, to convert them from Buffers to string or Uint8Array42+// We do this by emulating the Buffer -> string|Uint8Array conversion performed by `get-stream` with our own, which is identical.43+const getAllMixed = ({all, stdout, stderr}) => all44+ && stdout45+ && stderr46+ && stdout.readableObjectMode !== stderr.readableObjectMode;added:lib/resolve/all-sync.js+32 added
1+import {isUint8Array, concatUint8Arrays} from '../utils/uint-array.js';2+import {stripNewline} from '../io/strip-newline.js';3+4+export const getAllSync = ([, stdout, stderr], options) => {5+ if (!options.all) {6+ return;7+ }8+9+ if (stdout === undefined) {10+ return stderr;11+ }12+13+ if (stderr === undefined) {14+ return stdout;15+ }16+17+ if (Array.isArray(stdout)) {18+ return Array.isArray(stderr)19+ ? [...stdout, ...stderr]20+ : [...stdout, stripNewline(stderr, options, 'all')];21+ }22+23+ if (Array.isArray(stderr)) {24+ return [stripNewline(stdout, options, 'all'), ...stderr];25+ }26+27+ if (isUint8Array(stdout) && isUint8Array(stderr)) {28+ return concatUint8Arrays([stdout, stderr]);29+ }30+31+ return `${stdout}${stderr}`;32+};added:lib/resolve/exit-async.js+45 added
1+import {once} from 'node:events';2+import {DiscardedError} from '../return/final-error.js';3+4+// If `error` is emitted before `spawn`, `exit` will never be emitted.5+// However, `error` might be emitted after `spawn`, e.g. with the `cancelSignal` option.6+// In that case, `exit` will still be emitted.7+// Since the `exit` event contains the signal name, we want to make sure we are listening for it.8+// This function also takes into account the following unlikely cases:9+// - `exit` being emitted in the same microtask as `spawn`10+// - `error` being emitted multiple times11+export const waitForExit = async subprocess => {12+ const [spawnPayload, exitPayload] = await Promise.allSettled([13+ once(subprocess, 'spawn'),14+ once(subprocess, 'exit'),15+ ]);16+17+ if (spawnPayload.status === 'rejected') {18+ return [];19+ }20+21+ return exitPayload.status === 'rejected'22+ ? waitForSubprocessExit(subprocess)23+ : exitPayload.value;24+};25+26+const waitForSubprocessExit = async subprocess => {27+ try {28+ return await once(subprocess, 'exit');29+ } catch {30+ return waitForSubprocessExit(subprocess);31+ }32+};33+34+export const waitForSuccessfulExit = async exitPromise => {35+ const [exitCode, signal] = await exitPromise;36+37+ if (!isSubprocessErrorExit(exitCode, signal) && isFailedExit(exitCode, signal)) {38+ throw new DiscardedError();39+ }40+41+ return [exitCode, signal];42+};43+44+const isSubprocessErrorExit = (exitCode, signal) => exitCode === undefined && signal === undefined;45+export const isFailedExit = (exitCode, signal) => exitCode !== 0 || signal !== null;added:lib/resolve/exit-sync.js+18 added
1+import {DiscardedError} from '../return/final-error.js';2+import {isMaxBufferSync} from '../io/max-buffer.js';3+import {isFailedExit} from './exit-async.js';4+5+export const getExitResultSync = ({error, status: exitCode, signal, output}, {maxBuffer}) => {6+ const resultError = getResultError(error, exitCode, signal);7+ const timedOut = resultError?.code === 'ETIMEDOUT';8+ const isMaxBuffer = isMaxBufferSync(resultError, output, maxBuffer);9+ return {resultError, exitCode, signal, timedOut, isMaxBuffer};10+};11+12+const getResultError = (error, exitCode, signal) => {13+ if (error !== undefined) {14+ return error;15+ }16+17+ return isFailedExit(exitCode, signal) ? new DiscardedError() : undefined;18+};added:lib/resolve/stdio.js+34 added
1+import {getStreamOutput} from '../io/contents.js';2+import {waitForStream, isInputFileDescriptor} from './wait-stream.js';3+4+// Read the contents of `subprocess.std*` and|or wait for its completion5+export const waitForStdioStreams = ({subprocess, encoding, buffer, maxBuffer, lines, stripFinalNewline, verboseInfo, streamInfo}) => subprocess.stdio.map((stream, fdNumber) => waitForSubprocessStream({6+ stream,7+ fdNumber,8+ encoding,9+ buffer: buffer[fdNumber],10+ maxBuffer: maxBuffer[fdNumber],11+ lines: lines[fdNumber],12+ allMixed: false,13+ stripFinalNewline,14+ verboseInfo,15+ streamInfo,16+}));17+18+export const waitForSubprocessStream = async ({stream, fdNumber, encoding, buffer, maxBuffer, lines, allMixed, stripFinalNewline, verboseInfo, streamInfo}) => {19+ if (!stream) {20+ return;21+ }22+23+ const onStreamEnd = waitForStream(stream, fdNumber, streamInfo);24+ if (isInputFileDescriptor(streamInfo, fdNumber)) {25+ await onStreamEnd;26+ return;27+ }28+29+ const [output] = await Promise.all([30+ getStreamOutput({stream, onStreamEnd, fdNumber, encoding, buffer, maxBuffer, lines, allMixed, stripFinalNewline, verboseInfo, streamInfo}),31+ onStreamEnd,32+ ]);33+ return output;34+};added:lib/resolve/wait-stream.js+96 added
1+import {finished} from 'node:stream/promises';2+3+// Wraps `finished(stream)` to handle the following case:4+// - When the subprocess exits, Node.js automatically calls `subprocess.stdin.destroy()`, which we need to ignore.5+// - However, we still need to throw if `subprocess.stdin.destroy()` is called before subprocess exit.6+export const waitForStream = async (stream, fdNumber, streamInfo, {isSameDirection, stopOnExit = false} = {}) => {7+ const state = handleStdinDestroy(stream, streamInfo);8+ const abortController = new AbortController();9+ try {10+ await Promise.race([11+ ...(stopOnExit ? [streamInfo.exitPromise] : []),12+ finished(stream, {cleanup: true, signal: abortController.signal}),13+ ]);14+ } catch (error) {15+ if (!state.stdinCleanedUp) {16+ handleStreamError(error, fdNumber, streamInfo, isSameDirection);17+ }18+ } finally {19+ abortController.abort();20+ }21+};22+23+// If `subprocess.stdin` is destroyed before being fully written to, it is considered aborted and should throw an error.24+// This can happen for example when user called `subprocess.stdin.destroy()` before `subprocess.stdin.end()`.25+// However, Node.js calls `subprocess.stdin.destroy()` on exit for cleanup purposes.26+// https://github.com/nodejs/node/blob/0b4cdb4b42956cbd7019058e409e06700a199e11/lib/internal/child_process.js#L27827+// This is normal and should not throw an error.28+// Therefore, we need to differentiate between both situations to know whether to throw an error.29+// Unfortunately, events (`close`, `error`, `end`, `exit`) cannot be used because `.destroy()` can take an arbitrary amount of time.30+// For example, `stdin: 'pipe'` is implemented as a TCP socket, and its `.destroy()` method waits for TCP disconnection.31+// Therefore `.destroy()` might end before or after subprocess exit, based on OS speed and load.32+// The only way to detect this is to spy on `subprocess.stdin._destroy()` by wrapping it.33+// If `subprocess.exitCode` or `subprocess.signalCode` is set, it means `.destroy()` is being called by Node.js itself.34+const handleStdinDestroy = (stream, {originalStreams: [originalStdin], subprocess}) => {35+ const state = {stdinCleanedUp: false};36+ if (stream === originalStdin) {37+ spyOnStdinDestroy(stream, subprocess, state);38+ }39+40+ return state;41+};42+43+const spyOnStdinDestroy = (subprocessStdin, subprocess, state) => {44+ const {_destroy} = subprocessStdin;45+ subprocessStdin._destroy = (...args) => {46+ setStdinCleanedUp(subprocess, state);47+ _destroy.call(subprocessStdin, ...args);48+ };49+};50+51+const setStdinCleanedUp = ({exitCode, signalCode}, state) => {52+ if (exitCode !== null || signalCode !== null) {53+ state.stdinCleanedUp = true;54+ }55+};56+57+// We ignore EPIPEs on writable streams and aborts on readable streams since those can happen normally.58+// When one stream errors, the error is propagated to the other streams on the same file descriptor.59+// Those other streams might have a different direction due to the above.60+// When this happens, the direction of both the initial stream and the others should then be taken into account.61+// Therefore, we keep track of whether a stream error is currently propagating.62+const handleStreamError = (error, fdNumber, streamInfo, isSameDirection) => {63+ if (!shouldIgnoreStreamError(error, fdNumber, streamInfo, isSameDirection)) {64+ throw error;65+ }66+};67+68+const shouldIgnoreStreamError = (error, fdNumber, streamInfo, isSameDirection = true) => {69+ if (streamInfo.propagating) {70+ return isStreamEpipe(error) || isStreamAbort(error);71+ }72+73+ streamInfo.propagating = true;74+ return isInputFileDescriptor(streamInfo, fdNumber) === isSameDirection75+ ? isStreamEpipe(error)76+ : isStreamAbort(error);77+};78+79+// Unfortunately, we cannot use the stream's class or properties to know whether it is readable or writable.80+// For example, `subprocess.stdin` is technically a Duplex, but can only be used as a writable.81+// Therefore, we need to use the file descriptor's direction (`stdin` is input, `stdout` is output, etc.).82+// However, while `subprocess.std*` and transforms follow that direction, any stream passed the `std*` option has the opposite direction.83+// For example, `subprocess.stdin` is a writable, but the `stdin` option is a readable.84+export const isInputFileDescriptor = ({fileDescriptors}, fdNumber) => fdNumber !== 'all' && fileDescriptors[fdNumber].direction === 'input';85+86+// When `stream.destroy()` is called without an `error` argument, stream is aborted.87+// This is the only way to abort a readable stream, which can be useful in some instances.88+// Therefore, we ignore this error on readable streams.89+export const isStreamAbort = error => error?.code === 'ERR_STREAM_PREMATURE_CLOSE';90+91+// When `stream.write()` is called but the underlying source has been closed, `EPIPE` is emitted.92+// When piping subprocesses, the source subprocess usually decides when to stop piping.93+// However, there are some instances when the destination does instead, such as `... | head -n1`.94+// It notifies the source by using `EPIPE`.95+// Therefore, we ignore this error on writable streams.96+const isStreamEpipe = error => error?.code === 'EPIPE';added:lib/resolve/wait-subprocess.js+82 added
1+import {once} from 'node:events';2+import {isStream as isNodeStream} from 'is-stream';3+import {errorSignal} from '../terminate/kill.js';4+import {throwOnTimeout} from '../terminate/timeout.js';5+import {isStandardStream} from '../utils/standard-stream.js';6+import {TRANSFORM_TYPES} from '../stdio/type.js';7+import {getBufferedData} from '../io/contents.js';8+import {waitForAllStream} from './all-async.js';9+import {waitForStdioStreams} from './stdio.js';10+import {waitForExit, waitForSuccessfulExit} from './exit-async.js';11+import {waitForStream} from './wait-stream.js';12+13+// Retrieve result of subprocess: exit code, signal, error, streams (stdout/stderr/all)14+export const waitForSubprocessResult = async ({15+ subprocess,16+ options: {encoding, buffer, maxBuffer, lines, timeoutDuration: timeout, stripFinalNewline},17+ context,18+ verboseInfo,19+ fileDescriptors,20+ originalStreams,21+ controller,22+}) => {23+ const exitPromise = waitForExit(subprocess);24+ const streamInfo = {originalStreams, fileDescriptors, subprocess, exitPromise, propagating: false};25+26+ const stdioPromises = waitForStdioStreams({subprocess, encoding, buffer, maxBuffer, lines, stripFinalNewline, verboseInfo, streamInfo});27+ const allPromise = waitForAllStream({subprocess, encoding, buffer, maxBuffer, lines, stripFinalNewline, verboseInfo, streamInfo});28+ const originalPromises = waitForOriginalStreams(originalStreams, subprocess, streamInfo);29+ const customStreamsEndPromises = waitForCustomStreamsEnd(fileDescriptors, streamInfo);30+31+ try {32+ return await Promise.race([33+ Promise.all([34+ {},35+ waitForSuccessfulExit(exitPromise),36+ Promise.all(stdioPromises),37+ allPromise,38+ ...originalPromises,39+ ...customStreamsEndPromises,40+ ]),41+ throwOnSubprocessError(subprocess, controller),42+ throwOnInternalError(subprocess, controller),43+ ...throwOnTimeout(subprocess, timeout, context, controller),44+ ]);45+ } catch (error) {46+ return Promise.all([47+ {error},48+ exitPromise,49+ Promise.all(stdioPromises.map(stdioPromise => getBufferedData(stdioPromise))),50+ getBufferedData(allPromise),51+ Promise.allSettled(originalPromises),52+ Promise.allSettled(customStreamsEndPromises),53+ ]);54+ }55+};56+57+// Transforms replace `subprocess.std*`, which means they are not exposed to users.58+// However, we still want to wait for their completion.59+const waitForOriginalStreams = (originalStreams, subprocess, streamInfo) =>60+ originalStreams.map((stream, fdNumber) => stream === subprocess.stdio[fdNumber]61+ ? undefined62+ : waitForStream(stream, fdNumber, streamInfo));63+64+// Some `stdin`/`stdout`/`stderr` options create a stream, e.g. when passing a file path.65+// The `.pipe()` method automatically ends that stream when `subprocess` ends.66+// This makes sure we wait for the completion of those streams, in order to catch any error.67+const waitForCustomStreamsEnd = (fileDescriptors, streamInfo) => fileDescriptors.flatMap(({stdioItems}, fdNumber) => stdioItems68+ .filter(({value, stream = value}) => isNodeStream(stream, {checkOpen: false}) && !isStandardStream(stream))69+ .map(({type, value, stream = value}) => waitForStream(stream, fdNumber, streamInfo, {70+ isSameDirection: TRANSFORM_TYPES.has(type),71+ stopOnExit: type === 'native',72+ })));73+74+const throwOnSubprocessError = async (subprocess, {signal}) => {75+ const [error] = await once(subprocess, 'error', {signal});76+ throw error;77+};78+79+const throwOnInternalError = async (subprocess, {signal}) => {80+ const [error] = await once(subprocess, errorSignal, {signal});81+ throw error;82+};deleted:lib/return/cause.js-37 removed
1-export const getFinalError = (originalError, message, isSync) => {2- const ErrorClass = isSync ? ExecaSyncError : ExecaError;3- const options = originalError instanceof DiscardedError ? {} : {cause: originalError};4- return new ErrorClass(message, options);5-};6-7-// Indicates that the error is used only to interrupt control flow, but not in the return value8-export class DiscardedError extends Error {}9-10-// Proper way to set `error.name`: it should be inherited and non-enumerable11-const setErrorName = (ErrorClass, value) => {12- Object.defineProperty(ErrorClass.prototype, 'name', {13- value,14- writable: true,15- enumerable: false,16- configurable: true,17- });18- Object.defineProperty(ErrorClass.prototype, execaErrorSymbol, {19- value: true,20- writable: false,21- enumerable: false,22- configurable: false,23- });24-};25-26-// Unlike `instanceof`, this works across realms27-export const isExecaError = error => isErrorInstance(error) && execaErrorSymbol in error;28-29-const execaErrorSymbol = Symbol('isExecaError');30-31-export const isErrorInstance = value => Object.prototype.toString.call(value) === '[object Error]';32-33-export class ExecaError extends Error {}34-setErrorName(ExecaError, ExecaError.name);35-36-export class ExecaSyncError extends Error {}37-setErrorName(ExecaSyncError, ExecaSyncError.name);modified:lib/return/early-error.js+2 added-2 removed
1 import {ChildProcess} from 'node:child_process';2 import {PassThrough, Readable, Writable, Duplex} from 'node:stream';3-import {cleanupCustomStreams} from '../stdio/async.js';4-import {makeEarlyError} from './error.js';3+import {cleanupCustomStreams} from '../stdio/handle-async.js';4+import {makeEarlyError} from './result.js';5 import {handleResult} from './reject.js';6 7 // When the subprocess fails to spawn.8 // We ensure the returned error is always both a promise and a subprocess.33 unmodified linesdeleted:lib/return/error.js-122 removed
1-import {signalsByName} from 'human-signals';2-import {getDurationMs} from './duration.js';3-import {getFinalError} from './cause.js';4-import {createMessages} from './message.js';5-6-export const makeSuccessResult = ({7- command,8- escapedCommand,9- stdio,10- all,11- options: {cwd},12- startTime,13-}) => ({14- command,15- escapedCommand,16- cwd,17- durationMs: getDurationMs(startTime),18- failed: false,19- timedOut: false,20- isCanceled: false,21- isTerminated: false,22- isMaxBuffer: false,23- exitCode: 0,24- stdout: stdio[1],25- stderr: stdio[2],26- all,27- stdio,28- pipedFrom: [],29-});30-31-export const makeEarlyError = ({32- error,33- command,34- escapedCommand,35- fileDescriptors,36- options,37- startTime,38- isSync,39-}) => makeError({40- error,41- command,42- escapedCommand,43- startTime,44- timedOut: false,45- isCanceled: false,46- isMaxBuffer: false,47- stdio: Array.from({length: fileDescriptors.length}),48- options,49- isSync,50-});51-52-export const makeError = ({53- error: originalError,54- command,55- escapedCommand,56- startTime,57- timedOut,58- isCanceled,59- isMaxBuffer,60- exitCode: rawExitCode,61- signal: rawSignal,62- stdio,63- all,64- options: {timeoutDuration, timeout = timeoutDuration, cwd, maxBuffer},65- isSync,66-}) => {67- const {exitCode, signal, signalDescription} = normalizeExitPayload(rawExitCode, rawSignal);68- const {originalMessage, shortMessage, message} = createMessages({69- stdio,70- all,71- originalError,72- signal,73- signalDescription,74- exitCode,75- escapedCommand,76- timedOut,77- isCanceled,78- isMaxBuffer,79- maxBuffer,80- timeout,81- cwd,82- });83- const error = getFinalError(originalError, message, isSync);84-85- error.shortMessage = shortMessage;86- error.originalMessage = originalMessage;87- error.command = command;88- error.escapedCommand = escapedCommand;89- error.cwd = cwd;90- error.durationMs = getDurationMs(startTime);91-92- error.failed = true;93- error.timedOut = timedOut;94- error.isCanceled = isCanceled;95- error.isTerminated = signal !== undefined;96- error.isMaxBuffer = isMaxBuffer;97- error.exitCode = exitCode;98- error.signal = signal;99- error.signalDescription = signalDescription;100- error.code = error.cause?.code;101-102- error.stdout = stdio[1];103- error.stderr = stdio[2];104-105- if (all !== undefined) {106- error.all = all;107- }108-109- error.stdio = stdio;110- error.pipedFrom = [];111-112- return error;113-};114-115-// `signal` and `exitCode` emitted on `subprocess.on('exit')` event can be `null`.116-// We normalize them to `undefined`117-const normalizeExitPayload = (rawExitCode, rawSignal) => {118- const exitCode = rawExitCode === null ? undefined : rawExitCode;119- const signal = rawSignal === null ? undefined : rawSignal;120- const signalDescription = signal === undefined ? undefined : signalsByName[rawSignal].description;121- return {exitCode, signal, signalDescription};122-};added:lib/return/final-error.js+37 added
1+export const getFinalError = (originalError, message, isSync) => {2+ const ErrorClass = isSync ? ExecaSyncError : ExecaError;3+ const options = originalError instanceof DiscardedError ? {} : {cause: originalError};4+ return new ErrorClass(message, options);5+};6+7+// Indicates that the error is used only to interrupt control flow, but not in the return value8+export class DiscardedError extends Error {}9+10+// Proper way to set `error.name`: it should be inherited and non-enumerable11+const setErrorName = (ErrorClass, value) => {12+ Object.defineProperty(ErrorClass.prototype, 'name', {13+ value,14+ writable: true,15+ enumerable: false,16+ configurable: true,17+ });18+ Object.defineProperty(ErrorClass.prototype, execaErrorSymbol, {19+ value: true,20+ writable: false,21+ enumerable: false,22+ configurable: false,23+ });24+};25+26+// Unlike `instanceof`, this works across realms27+export const isExecaError = error => isErrorInstance(error) && execaErrorSymbol in error;28+29+const execaErrorSymbol = Symbol('isExecaError');30+31+export const isErrorInstance = value => Object.prototype.toString.call(value) === '[object Error]';32+33+export class ExecaError extends Error {}34+setErrorName(ExecaError, ExecaError.name);35+36+export class ExecaSyncError extends Error {}37+setErrorName(ExecaSyncError, ExecaSyncError.name);modified:lib/return/message.js+3 added-3 removed
1 import stripFinalNewline from 'strip-final-newline';2-import {isUint8Array, uint8ArrayToString} from '../stdio/uint-array.js';2+import {isUint8Array, uint8ArrayToString} from '../utils/uint-array.js';3 import {fixCwdError} from '../arguments/cwd.js';4 import {escapeLines} from '../arguments/escape.js';5-import {getMaxBufferMessage} from '../stream/max-buffer.js';6-import {DiscardedError, isExecaError} from './cause.js';5+import {getMaxBufferMessage} from '../io/max-buffer.js';6+import {DiscardedError, isExecaError} from './final-error.js';7 8 export const createMessages = ({9 stdio,10 all,79 unmodified linesadded:lib/return/result.js+122 added
1+import {signalsByName} from 'human-signals';2+import {getDurationMs} from './duration.js';3+import {getFinalError} from './final-error.js';4+import {createMessages} from './message.js';5+6+export const makeSuccessResult = ({7+ command,8+ escapedCommand,9+ stdio,10+ all,11+ options: {cwd},12+ startTime,13+}) => ({14+ command,15+ escapedCommand,16+ cwd,17+ durationMs: getDurationMs(startTime),18+ failed: false,19+ timedOut: false,20+ isCanceled: false,21+ isTerminated: false,22+ isMaxBuffer: false,23+ exitCode: 0,24+ stdout: stdio[1],25+ stderr: stdio[2],26+ all,27+ stdio,28+ pipedFrom: [],29+});30+31+export const makeEarlyError = ({32+ error,33+ command,34+ escapedCommand,35+ fileDescriptors,36+ options,37+ startTime,38+ isSync,39+}) => makeError({40+ error,41+ command,42+ escapedCommand,43+ startTime,44+ timedOut: false,45+ isCanceled: false,46+ isMaxBuffer: false,47+ stdio: Array.from({length: fileDescriptors.length}),48+ options,49+ isSync,50+});51+52+export const makeError = ({53+ error: originalError,54+ command,55+ escapedCommand,56+ startTime,57+ timedOut,58+ isCanceled,59+ isMaxBuffer,60+ exitCode: rawExitCode,61+ signal: rawSignal,62+ stdio,63+ all,64+ options: {timeoutDuration, timeout = timeoutDuration, cwd, maxBuffer},65+ isSync,66+}) => {67+ const {exitCode, signal, signalDescription} = normalizeExitPayload(rawExitCode, rawSignal);68+ const {originalMessage, shortMessage, message} = createMessages({69+ stdio,70+ all,71+ originalError,72+ signal,73+ signalDescription,74+ exitCode,75+ escapedCommand,76+ timedOut,77+ isCanceled,78+ isMaxBuffer,79+ maxBuffer,80+ timeout,81+ cwd,82+ });83+ const error = getFinalError(originalError, message, isSync);84+85+ error.shortMessage = shortMessage;86+ error.originalMessage = originalMessage;87+ error.command = command;88+ error.escapedCommand = escapedCommand;89+ error.cwd = cwd;90+ error.durationMs = getDurationMs(startTime);91+92+ error.failed = true;93+ error.timedOut = timedOut;94+ error.isCanceled = isCanceled;95+ error.isTerminated = signal !== undefined;96+ error.isMaxBuffer = isMaxBuffer;97+ error.exitCode = exitCode;98+ error.signal = signal;99+ error.signalDescription = signalDescription;100+ error.code = error.cause?.code;101+102+ error.stdout = stdio[1];103+ error.stderr = stdio[2];104+105+ if (all !== undefined) {106+ error.all = all;107+ }108+109+ error.stdio = stdio;110+ error.pipedFrom = [];111+112+ return error;113+};114+115+// `signal` and `exitCode` emitted on `subprocess.on('exit')` event can be `null`.116+// We normalize them to `undefined`117+const normalizeExitPayload = (rawExitCode, rawSignal) => {118+ const exitCode = rawExitCode === null ? undefined : rawExitCode;119+ const signal = rawSignal === null ? undefined : rawSignal;120+ const signalDescription = signal === undefined ? undefined : signalsByName[rawSignal].description;121+ return {exitCode, signal, signalDescription};122+};deleted:lib/return/strip-newline.js-9 removed
1-import stripFinalNewlineFunction from 'strip-final-newline';2-3-export const stripNewline = (value, {stripFinalNewline}, fdNumber) => getStripFinalNewline(stripFinalNewline, fdNumber) && value !== undefined && !Array.isArray(value)4- ? stripFinalNewlineFunction(value)5- : value;6-7-export const getStripFinalNewline = (stripFinalNewline, fdNumber) => fdNumber === 'all'8- ? stripFinalNewline[1] || stripFinalNewline[2]9- : stripFinalNewline[fdNumber];deleted:lib/stdio/all-sync.js-32 removed
1-import {stripNewline} from '../return/strip-newline.js';2-import {isUint8Array, concatUint8Arrays} from './uint-array.js';3-4-export const getAllSync = ([, stdout, stderr], options) => {5- if (!options.all) {6- return;7- }8-9- if (stdout === undefined) {10- return stderr;11- }12-13- if (stderr === undefined) {14- return stdout;15- }16-17- if (Array.isArray(stdout)) {18- return Array.isArray(stderr)19- ? [...stdout, ...stderr]20- : [...stdout, stripNewline(stderr, options, 'all')];21- }22-23- if (Array.isArray(stderr)) {24- return [stripNewline(stdout, options, 'all'), ...stderr];25- }26-27- if (isUint8Array(stdout) && isUint8Array(stderr)) {28- return concatUint8Arrays([stdout, stderr]);29- }30-31- return `${stdout}${stderr}`;32-};deleted:lib/stdio/async.js-64 removed
1-import {createReadStream, createWriteStream} from 'node:fs';2-import {Buffer} from 'node:buffer';3-import {Readable, Writable, Duplex} from 'node:stream';4-import {isStandardStream} from '../utils.js';5-import {handleInput} from './handle.js';6-import {TYPE_TO_MESSAGE} from './type.js';7-import {generatorToStream} from './transform-run.js';8-9-// Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in async mode10-export const handleInputAsync = (options, verboseInfo) => handleInput(addPropertiesAsync, options, verboseInfo, false);11-12-const forbiddenIfAsync = ({type, optionName}) => {13- throw new TypeError(`The \`${optionName}\` option cannot be ${TYPE_TO_MESSAGE[type]}.`);14-};15-16-const addProperties = {17- generator: generatorToStream,18- asyncGenerator: generatorToStream,19- nodeStream: ({value}) => ({stream: value}),20- webTransform({value: {transform, writableObjectMode, readableObjectMode}}) {21- const objectMode = writableObjectMode || readableObjectMode;22- const stream = Duplex.fromWeb(transform, {objectMode});23- return {stream};24- },25- duplex: ({value: {transform}}) => ({stream: transform}),26- native() {},27-};28-29-const addPropertiesAsync = {30- input: {31- ...addProperties,32- fileUrl: ({value}) => ({stream: createReadStream(value)}),33- filePath: ({value: {file}}) => ({stream: createReadStream(file)}),34- webStream: ({value}) => ({stream: Readable.fromWeb(value)}),35- iterable: ({value}) => ({stream: Readable.from(value)}),36- asyncIterable: ({value}) => ({stream: Readable.from(value)}),37- string: ({value}) => ({stream: Readable.from(value)}),38- uint8Array: ({value}) => ({stream: Readable.from(Buffer.from(value))}),39- },40- output: {41- ...addProperties,42- fileUrl: ({value}) => ({stream: createWriteStream(value)}),43- filePath: ({value: {file}}) => ({stream: createWriteStream(file)}),44- webStream: ({value}) => ({stream: Writable.fromWeb(value)}),45- iterable: forbiddenIfAsync,46- asyncIterable: forbiddenIfAsync,47- string: forbiddenIfAsync,48- uint8Array: forbiddenIfAsync,49- },50-};51-52-// The stream error handling is performed by the piping logic above, which cannot be performed before subprocess spawning.53-// If the subprocess spawning fails (e.g. due to an invalid command), the streams need to be manually destroyed.54-// We need to create those streams before subprocess spawning, in case their creation fails, e.g. when passing an invalid generator as argument.55-// Like this, an exception would be thrown, which would prevent spawning a subprocess.56-export const cleanupCustomStreams = fileDescriptors => {57- for (const {stdioItems} of fileDescriptors) {58- for (const {stream} of stdioItems) {59- if (stream !== undefined && !isStandardStream(stream)) {60- stream.destroy();61- }62- }63- }64-};deleted:lib/stdio/encoding-transform.js-54 removed
1-import {Buffer} from 'node:buffer';2-import {StringDecoder} from 'node:string_decoder';3-import {isUint8Array, bufferToUint8Array} from './uint-array.js';4-5-/*6-When using generators, add an internal generator that converts chunks from `Buffer` to `string` or `Uint8Array`.7-This allows generator functions to operate with those types instead.8-Chunks might be Buffer, Uint8Array or strings since:9-- `subprocess.stdout|stderr` emits Buffers10-- `subprocess.stdin.write()` accepts Buffer, Uint8Array or string11-- Previous generators might return Uint8Array or string12-13-However, those are converted to Buffer:14-- on writes: `Duplex.writable` `decodeStrings: true` default option15-- on reads: `Duplex.readable` `readableEncoding: null` default option16-*/17-export const getEncodingTransformGenerator = (binary, encoding, skipped) => {18- if (skipped) {19- return;20- }21-22- if (binary) {23- return {transform: encodingUint8ArrayGenerator.bind(undefined, new TextEncoder())};24- }25-26- const stringDecoder = new StringDecoder(encoding);27- return {28- transform: encodingStringGenerator.bind(undefined, stringDecoder),29- final: encodingStringFinal.bind(undefined, stringDecoder),30- };31-};32-33-const encodingUint8ArrayGenerator = function * (textEncoder, chunk) {34- if (Buffer.isBuffer(chunk)) {35- yield bufferToUint8Array(chunk);36- } else if (typeof chunk === 'string') {37- yield textEncoder.encode(chunk);38- } else {39- yield chunk;40- }41-};42-43-const encodingStringGenerator = function * (stringDecoder, chunk) {44- yield Buffer.isBuffer(chunk) || isUint8Array(chunk)45- ? stringDecoder.write(chunk)46- : chunk;47-};48-49-const encodingStringFinal = function * (stringDecoder) {50- const lastChunk = stringDecoder.end();51- if (lastChunk !== '') {52- yield lastChunk;53- }54-};added:lib/stdio/handle-async.js+64 added
1+import {createReadStream, createWriteStream} from 'node:fs';2+import {Buffer} from 'node:buffer';3+import {Readable, Writable, Duplex} from 'node:stream';4+import {isStandardStream} from '../utils/standard-stream.js';5+import {generatorToStream} from '../transform/generator.js';6+import {handleStdio} from './handle.js';7+import {TYPE_TO_MESSAGE} from './type.js';8+9+// Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in async mode10+export const handleStdioAsync = (options, verboseInfo) => handleStdio(addPropertiesAsync, options, verboseInfo, false);11+12+const forbiddenIfAsync = ({type, optionName}) => {13+ throw new TypeError(`The \`${optionName}\` option cannot be ${TYPE_TO_MESSAGE[type]}.`);14+};15+16+const addProperties = {17+ generator: generatorToStream,18+ asyncGenerator: generatorToStream,19+ nodeStream: ({value}) => ({stream: value}),20+ webTransform({value: {transform, writableObjectMode, readableObjectMode}}) {21+ const objectMode = writableObjectMode || readableObjectMode;22+ const stream = Duplex.fromWeb(transform, {objectMode});23+ return {stream};24+ },25+ duplex: ({value: {transform}}) => ({stream: transform}),26+ native() {},27+};28+29+const addPropertiesAsync = {30+ input: {31+ ...addProperties,32+ fileUrl: ({value}) => ({stream: createReadStream(value)}),33+ filePath: ({value: {file}}) => ({stream: createReadStream(file)}),34+ webStream: ({value}) => ({stream: Readable.fromWeb(value)}),35+ iterable: ({value}) => ({stream: Readable.from(value)}),36+ asyncIterable: ({value}) => ({stream: Readable.from(value)}),37+ string: ({value}) => ({stream: Readable.from(value)}),38+ uint8Array: ({value}) => ({stream: Readable.from(Buffer.from(value))}),39+ },40+ output: {41+ ...addProperties,42+ fileUrl: ({value}) => ({stream: createWriteStream(value)}),43+ filePath: ({value: {file}}) => ({stream: createWriteStream(file)}),44+ webStream: ({value}) => ({stream: Writable.fromWeb(value)}),45+ iterable: forbiddenIfAsync,46+ asyncIterable: forbiddenIfAsync,47+ string: forbiddenIfAsync,48+ uint8Array: forbiddenIfAsync,49+ },50+};51+52+// The stream error handling is performed by the piping logic above, which cannot be performed before subprocess spawning.53+// If the subprocess spawning fails (e.g. due to an invalid command), the streams need to be manually destroyed.54+// We need to create those streams before subprocess spawning, in case their creation fails, e.g. when passing an invalid generator as argument.55+// Like this, an exception would be thrown, which would prevent spawning a subprocess.56+export const cleanupCustomStreams = fileDescriptors => {57+ for (const {stdioItems} of fileDescriptors) {58+ for (const {stream} of stdioItems) {59+ if (stream !== undefined && !isStandardStream(stream)) {60+ stream.destroy();61+ }62+ }63+ }64+};added:lib/stdio/handle-sync.js+54 added
1+import {readFileSync} from 'node:fs';2+import {bufferToUint8Array} from '../utils/uint-array.js';3+import {handleStdio} from './handle.js';4+import {TYPE_TO_MESSAGE} from './type.js';5+6+// Normalize `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in sync mode7+export const handleStdioSync = (options, verboseInfo) => handleStdio(addPropertiesSync, options, verboseInfo, true);8+9+const forbiddenIfSync = ({type, optionName}) => {10+ throwInvalidSyncValue(optionName, TYPE_TO_MESSAGE[type]);11+};12+13+const forbiddenNativeIfSync = ({optionName, value}) => {14+ if (value === 'ipc' || value === 'overlapped') {15+ throwInvalidSyncValue(optionName, `"${value}"`);16+ }17+18+ return {};19+};20+21+const throwInvalidSyncValue = (optionName, value) => {22+ throw new TypeError(`The \`${optionName}\` option cannot be ${value} with synchronous methods.`);23+};24+25+const addProperties = {26+ generator() {},27+ asyncGenerator: forbiddenIfSync,28+ webStream: forbiddenIfSync,29+ nodeStream: forbiddenIfSync,30+ webTransform: forbiddenIfSync,31+ duplex: forbiddenIfSync,32+ asyncIterable: forbiddenIfSync,33+ native: forbiddenNativeIfSync,34+};35+36+const addPropertiesSync = {37+ input: {38+ ...addProperties,39+ fileUrl: ({value}) => ({contents: [bufferToUint8Array(readFileSync(value))]}),40+ filePath: ({value: {file}}) => ({contents: [bufferToUint8Array(readFileSync(file))]}),41+ iterable: ({value}) => ({contents: [...value]}),42+ string: ({value}) => ({contents: [value]}),43+ uint8Array: ({value}) => ({contents: [value]}),44+ },45+ output: {46+ ...addProperties,47+ fileUrl: ({value}) => ({path: value}),48+ filePath: ({value: {file}}) => ({path: file}),49+ fileNumber: ({value}) => ({path: value}),50+ iterable: forbiddenIfSync,51+ string: forbiddenIfSync,52+ uint8Array: forbiddenIfSync,53+ },54+};modified:lib/stdio/handle.js+7 added-7 removed
1-import {getStreamName} from '../utils.js';1+import {getStreamName} from '../utils/standard-stream.js';2+import {normalizeTransforms} from '../transform/normalize.js';3+import {getFdObjectMode} from '../transform/object-mode.js';4 import {getStdioItemType, isRegularUrl, isUnknownStdioString, FILE_TYPES} from './type.js';5 import {getStreamDirection} from './direction.js';4-import {normalizeStdio} from './option.js';6+import {normalizeStdioOption} from './stdio-option.js';7 import {handleNativeStream} from './native.js';6-import {handleInputOptions} from './input.js';7-import {normalizeTransforms} from './normalize-transform.js';8-import {getFdObjectMode} from './object-mode.js';8+import {handleInputOptions} from './input-option.js';9 10 // Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in async/sync mode11-export const handleInput = (addProperties, options, verboseInfo, isSync) => {12- const stdio = normalizeStdio(options, isSync);11+export const handleStdio = (addProperties, options, verboseInfo, isSync) => {12+ const stdio = normalizeStdioOption(options, isSync);13 const fileDescriptors = stdio.map((stdioOption, fdNumber) =>14 getFileDescriptor({stdioOption, fdNumber, addProperties, options, isSync}));15 options.stdio = fileDescriptors.map(({stdioItems}) => forwardStdio(stdioItems));16 return fileDescriptors;110 unmodified linesadded:lib/stdio/input-option.js+50 added
1+import {isReadableStream} from 'is-stream';2+import {isUint8Array} from '../utils/uint-array.js';3+import {isUrl, isFilePathString} from './type.js';4+5+// Append the `stdin` option with the `input` and `inputFile` options6+export const handleInputOptions = ({input, inputFile}, fdNumber) => fdNumber === 07+ ? [8+ ...handleInputOption(input),9+ ...handleInputFileOption(inputFile),10+ ]11+ : [];12+13+const handleInputOption = input => input === undefined ? [] : [{14+ type: getInputType(input),15+ value: input,16+ optionName: 'input',17+}];18+19+const getInputType = input => {20+ if (isReadableStream(input, {checkOpen: false})) {21+ return 'nodeStream';22+ }23+24+ if (typeof input === 'string') {25+ return 'string';26+ }27+28+ if (isUint8Array(input)) {29+ return 'uint8Array';30+ }31+32+ throw new Error('The `input` option must be a string, a Uint8Array or a Node.js Readable stream.');33+};34+35+const handleInputFileOption = inputFile => inputFile === undefined ? [] : [{36+ ...getInputFileType(inputFile),37+ optionName: 'inputFile',38+}];39+40+const getInputFileType = inputFile => {41+ if (isUrl(inputFile)) {42+ return {type: 'fileUrl', value: inputFile};43+ }44+45+ if (isFilePathString(inputFile)) {46+ return {type: 'filePath', value: {file: inputFile}};47+ }48+49+ throw new Error('The `inputFile` option must be a file path string or a file URL.');50+};deleted:lib/stdio/input-sync.js-44 removed
1-import {joinToUint8Array, isUint8Array} from './uint-array.js';2-import {TYPE_TO_MESSAGE} from './type.js';3-import {runGeneratorsSync} from './transform-run.js';4-5-// Apply `stdin`/`input`/`inputFile` options, before spawning, in sync mode, by converting it to the `input` option6-export const addInputOptionsSync = (fileDescriptors, options) => {7- for (const fdNumber of getInputFdNumbers(fileDescriptors)) {8- addInputOptionSync(fileDescriptors, fdNumber, options);9- }10-};11-12-const getInputFdNumbers = fileDescriptors => new Set(Object.entries(fileDescriptors)13- .filter(([, {direction}]) => direction === 'input')14- .map(([fdNumber]) => Number(fdNumber)));15-16-const addInputOptionSync = (fileDescriptors, fdNumber, options) => {17- const {stdioItems} = fileDescriptors[fdNumber];18- const allStdioItems = stdioItems.filter(({contents}) => contents !== undefined);19- if (allStdioItems.length === 0) {20- return;21- }22-23- if (fdNumber !== 0) {24- const [{type, optionName}] = allStdioItems;25- throw new TypeError(`Only the \`stdin\` option, not \`${optionName}\`, can be ${TYPE_TO_MESSAGE[type]} with synchronous methods.`);26- }27-28- const allContents = allStdioItems.map(({contents}) => contents);29- const transformedContents = allContents.map(contents => applySingleInputGeneratorsSync(contents, stdioItems));30- options.input = joinToUint8Array(transformedContents);31-};32-33-const applySingleInputGeneratorsSync = (contents, stdioItems) => {34- const newContents = runGeneratorsSync(contents, stdioItems, 'utf8', true);35- validateSerializable(newContents);36- return joinToUint8Array(newContents);37-};38-39-const validateSerializable = newContents => {40- const invalidItem = newContents.find(item => typeof item !== 'string' && !isUint8Array(item));41- if (invalidItem !== undefined) {42- throw new TypeError(`The \`stdin\` option is invalid: when passing objects as input, a transform must be used to serialize them to strings or Uint8Arrays: ${invalidItem}.`);43- }44-};deleted:lib/stdio/input.js-50 removed
1-import {isReadableStream} from 'is-stream';2-import {isUint8Array} from './uint-array.js';3-import {isUrl, isFilePathString} from './type.js';4-5-// Append the `stdin` option with the `input` and `inputFile` options6-export const handleInputOptions = ({input, inputFile}, fdNumber) => fdNumber === 07- ? [8- ...handleInputOption(input),9- ...handleInputFileOption(inputFile),10- ]11- : [];12-13-const handleInputOption = input => input === undefined ? [] : [{14- type: getInputType(input),15- value: input,16- optionName: 'input',17-}];18-19-const getInputType = input => {20- if (isReadableStream(input, {checkOpen: false})) {21- return 'nodeStream';22- }23-24- if (typeof input === 'string') {25- return 'string';26- }27-28- if (isUint8Array(input)) {29- return 'uint8Array';30- }31-32- throw new Error('The `input` option must be a string, a Uint8Array or a Node.js Readable stream.');33-};34-35-const handleInputFileOption = inputFile => inputFile === undefined ? [] : [{36- ...getInputFileType(inputFile),37- optionName: 'inputFile',38-}];39-40-const getInputFileType = inputFile => {41- if (isUrl(inputFile)) {42- return {type: 'fileUrl', value: inputFile};43- }44-45- if (isFilePathString(inputFile)) {46- return {type: 'filePath', value: {file: inputFile}};47- }48-49- throw new Error('The `inputFile` option must be a file path string or a file URL.');50-};modified:lib/stdio/native.js+3 added-3 removed
1 import {readFileSync} from 'node:fs';2 import tty from 'node:tty';3 import {isStream as isNodeStream} from 'is-stream';4-import {STANDARD_STREAMS} from '../utils.js';5-import {serializeOptionValue} from '../convert/fd-options.js';6-import {bufferToUint8Array} from './uint-array.js';4+import {STANDARD_STREAMS} from '../utils/standard-stream.js';5+import {bufferToUint8Array} from '../utils/uint-array.js';6+import {serializeOptionValue} from '../arguments/fd-options.js';7 8 // When we use multiple `stdio` values for the same streams, we pass 'pipe' to `child_process.spawn()`.9 // We then emulate the piping done by core Node.js.10 // To do so, we transform the following values:89 unmodified linesdeleted:lib/stdio/normalize-transform.js-83 removed
1-import isPlainObj from 'is-plain-obj';2-import {BINARY_ENCODINGS} from '../arguments/encoding.js';3-import {TRANSFORM_TYPES} from './type.js';4-import {getTransformObjectModes} from './object-mode.js';5-6-// Transforms generators/duplex/TransformStream can have multiple shapes.7-// This normalizes it and applies default values.8-export const normalizeTransforms = (stdioItems, optionName, direction, options) => [9- ...stdioItems.filter(({type}) => !TRANSFORM_TYPES.has(type)),10- ...getTransforms(stdioItems, optionName, direction, options),11-];12-13-const getTransforms = (stdioItems, optionName, direction, {encoding}) => {14- const transforms = stdioItems.filter(({type}) => TRANSFORM_TYPES.has(type));15- const newTransforms = Array.from({length: transforms.length});16-17- for (const [index, stdioItem] of Object.entries(transforms)) {18- newTransforms[index] = normalizeTransform({stdioItem, index: Number(index), newTransforms, optionName, direction, encoding});19- }20-21- return sortTransforms(newTransforms, direction);22-};23-24-const normalizeTransform = ({stdioItem, stdioItem: {type}, index, newTransforms, optionName, direction, encoding}) => {25- if (type === 'duplex') {26- return normalizeDuplex({stdioItem, optionName});27- }28-29- if (type === 'webTransform') {30- return normalizeTransformStream({stdioItem, index, newTransforms, direction});31- }32-33- return normalizeGenerator({stdioItem, index, newTransforms, direction, encoding});34-};35-36-const normalizeDuplex = ({37- stdioItem,38- stdioItem: {39- value: {40- transform,41- transform: {writableObjectMode, readableObjectMode},42- objectMode = readableObjectMode,43- },44- },45- optionName,46-}) => {47- if (objectMode && !readableObjectMode) {48- throw new TypeError(`The \`${optionName}.objectMode\` option can only be \`true\` if \`new Duplex({objectMode: true})\` is used.`);49- }50-51- if (!objectMode && readableObjectMode) {52- throw new TypeError(`The \`${optionName}.objectMode\` option cannot be \`false\` if \`new Duplex({objectMode: true})\` is used.`);53- }54-55- return {56- ...stdioItem,57- value: {transform, writableObjectMode, readableObjectMode},58- };59-};60-61-const normalizeTransformStream = ({stdioItem, stdioItem: {value}, index, newTransforms, direction}) => {62- const {transform, objectMode} = isPlainObj(value) ? value : {transform: value};63- const {writableObjectMode, readableObjectMode} = getTransformObjectModes(objectMode, index, newTransforms, direction);64- return ({65- ...stdioItem,66- value: {transform, writableObjectMode, readableObjectMode},67- });68-};69-70-const normalizeGenerator = ({stdioItem, stdioItem: {value}, index, newTransforms, direction, encoding}) => {71- const {72- transform,73- final,74- binary: binaryOption = false,75- preserveNewlines = false,76- objectMode,77- } = isPlainObj(value) ? value : {transform: value};78- const binary = binaryOption || BINARY_ENCODINGS.has(encoding);79- const {writableObjectMode, readableObjectMode} = getTransformObjectModes(objectMode, index, newTransforms, direction);80- return {...stdioItem, value: {transform, final, binary, preserveNewlines, writableObjectMode, readableObjectMode}};81-};82-83-const sortTransforms = (newTransforms, direction) => direction === 'input' ? newTransforms.reverse() : newTransforms;deleted:lib/stdio/object-mode.js-41 removed
1-import {TRANSFORM_TYPES} from './type.js';2-3-/*4-Retrieve the `objectMode`s of a single transform.5-`objectMode` determines the return value's type, i.e. the `readableObjectMode`.6-The chunk argument's type is based on the previous generator's return value, i.e. the `writableObjectMode` is based on the previous `readableObjectMode`.7-The last input's generator is read by `subprocess.stdin` which:8-- should not be in `objectMode` for performance reasons.9-- can only be strings, Buffers and Uint8Arrays.10-Therefore its `readableObjectMode` must be `false`.11-The same applies to the first output's generator's `writableObjectMode`.12-*/13-export const getTransformObjectModes = (objectMode, index, newTransforms, direction) => direction === 'output'14- ? getOutputObjectModes(objectMode, index, newTransforms)15- : getInputObjectModes(objectMode, index, newTransforms);16-17-const getOutputObjectModes = (objectMode, index, newTransforms) => {18- const writableObjectMode = index !== 0 && newTransforms[index - 1].value.readableObjectMode;19- const readableObjectMode = objectMode ?? writableObjectMode;20- return {writableObjectMode, readableObjectMode};21-};22-23-const getInputObjectModes = (objectMode, index, newTransforms) => {24- const writableObjectMode = index === 025- ? objectMode === true26- : newTransforms[index - 1].value.readableObjectMode;27- const readableObjectMode = index !== newTransforms.length - 1 && (objectMode ?? writableObjectMode);28- return {writableObjectMode, readableObjectMode};29-};30-31-// Retrieve the `objectMode` of a file descriptor, e.g. `stdout` or `stderr`32-export const getFdObjectMode = (stdioItems, direction) => {33- const lastTransform = stdioItems.findLast(({type}) => TRANSFORM_TYPES.has(type));34- if (lastTransform === undefined) {35- return false;36- }37-38- return direction === 'input'39- ? lastTransform.value.writableObjectMode40- : lastTransform.value.readableObjectMode;41-};deleted:lib/stdio/option.js-57 removed
1-import {STANDARD_STREAMS_ALIASES} from '../utils.js';2-3-// Add support for `stdin`/`stdout`/`stderr` as an alias for `stdio`4-export const normalizeStdio = ({stdio, ipc, buffer, verbose, ...options}, isSync) => {5- const stdioArray = getStdioArray(stdio, options).map((stdioOption, fdNumber) => addDefaultValue(stdioOption, fdNumber));6- return isSync ? normalizeStdioSync(stdioArray, buffer, verbose) : normalizeStdioAsync(stdioArray, ipc);7-};8-9-const getStdioArray = (stdio, options) => {10- if (stdio === undefined) {11- return STANDARD_STREAMS_ALIASES.map(alias => options[alias]);12- }13-14- if (hasAlias(options)) {15- throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${STANDARD_STREAMS_ALIASES.map(alias => `\`${alias}\``).join(', ')}`);16- }17-18- if (typeof stdio === 'string') {19- return [stdio, stdio, stdio];20- }21-22- if (!Array.isArray(stdio)) {23- throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``);24- }25-26- const length = Math.max(stdio.length, STANDARD_STREAMS_ALIASES.length);27- return Array.from({length}, (_, fdNumber) => stdio[fdNumber]);28-};29-30-const hasAlias = options => STANDARD_STREAMS_ALIASES.some(alias => options[alias] !== undefined);31-32-const addDefaultValue = (stdioOption, fdNumber) => {33- if (Array.isArray(stdioOption)) {34- return stdioOption.map(item => addDefaultValue(item, fdNumber));35- }36-37- if (stdioOption === null || stdioOption === undefined) {38- return fdNumber >= STANDARD_STREAMS_ALIASES.length ? 'ignore' : 'pipe';39- }40-41- return stdioOption;42-};43-44-const normalizeStdioSync = (stdioArray, buffer, verbose) => stdioArray.map((stdioOption, fdNumber) =>45- !buffer[fdNumber]46- && fdNumber !== 047- && verbose[fdNumber] !== 'full'48- && isOutputPipeOnly(stdioOption)49- ? 'ignore'50- : stdioOption);51-52-const isOutputPipeOnly = stdioOption => stdioOption === 'pipe'53- || (Array.isArray(stdioOption) && stdioOption.every(item => item === 'pipe'));54-55-const normalizeStdioAsync = (stdioArray, ipc) => ipc && !stdioArray.includes('ipc')56- ? [...stdioArray, 'ipc']57- : stdioArray;deleted:lib/stdio/output-async.js-71 removed
1-import mergeStreams from '@sindresorhus/merge-streams';2-import {isStandardStream} from '../utils.js';3-import {incrementMaxListeners} from '../max-listener.js';4-import {pipeStreams} from './pipeline.js';5-import {TRANSFORM_TYPES} from './type.js';6-7-// Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, after spawning, in async mode8-// When multiple input streams are used, we merge them to ensure the output stream ends only once each input stream has ended9-export const pipeOutputAsync = (subprocess, fileDescriptors, controller) => {10- const inputStreamsGroups = {};11-12- for (const [fdNumber, {stdioItems, direction}] of Object.entries(fileDescriptors)) {13- for (const {stream} of stdioItems.filter(({type}) => TRANSFORM_TYPES.has(type))) {14- pipeTransform(subprocess, stream, direction, fdNumber);15- }16-17- for (const {stream} of stdioItems.filter(({type}) => !TRANSFORM_TYPES.has(type))) {18- pipeStdioItem({subprocess, stream, direction, fdNumber, inputStreamsGroups, controller});19- }20- }21-22- for (const [fdNumber, inputStreams] of Object.entries(inputStreamsGroups)) {23- const inputStream = inputStreams.length === 1 ? inputStreams[0] : mergeStreams(inputStreams);24- pipeStreams(inputStream, subprocess.stdio[fdNumber]);25- }26-};27-28-// `subprocess.stdin|stdout|stderr|stdio` is directly mutated.29-const pipeTransform = (subprocess, stream, direction, fdNumber) => {30- if (direction === 'output') {31- pipeStreams(subprocess.stdio[fdNumber], stream);32- } else {33- pipeStreams(stream, subprocess.stdio[fdNumber]);34- }35-36- const streamProperty = SUBPROCESS_STREAM_PROPERTIES[fdNumber];37- if (streamProperty !== undefined) {38- subprocess[streamProperty] = stream;39- }40-41- subprocess.stdio[fdNumber] = stream;42-};43-44-const SUBPROCESS_STREAM_PROPERTIES = ['stdin', 'stdout', 'stderr'];45-46-const pipeStdioItem = ({subprocess, stream, direction, fdNumber, inputStreamsGroups, controller}) => {47- if (stream === undefined) {48- return;49- }50-51- setStandardStreamMaxListeners(stream, controller);52-53- if (direction === 'output') {54- pipeStreams(subprocess.stdio[fdNumber], stream);55- } else {56- inputStreamsGroups[fdNumber] = [...(inputStreamsGroups[fdNumber] ?? []), stream];57- }58-};59-60-// Multiple subprocesses might be piping from/to `process.std*` at the same time.61-// This is not necessarily an error and should not print a `maxListeners` warning.62-const setStandardStreamMaxListeners = (stream, {signal}) => {63- if (isStandardStream(stream)) {64- incrementMaxListeners(stream, MAX_LISTENERS_INCREMENT, signal);65- }66-};67-68-// `source.pipe(destination)` adds at most 1 listener for each event.69-// If `stdin` option is an array, the values might be combined with `merge-streams`.70-// That library also listens for `source` end, which adds 1 more listener.71-const MAX_LISTENERS_INCREMENT = 2;deleted:lib/stdio/output-sync.js-90 removed
1-import {writeFileSync} from 'node:fs';2-import {shouldLogOutput, logLinesSync} from '../verbose/output.js';3-import {getMaxBufferSync} from '../stream/max-buffer.js';4-import {joinToString, joinToUint8Array, bufferToUint8Array} from './uint-array.js';5-import {runGeneratorsSync} from './transform-run.js';6-import {splitLinesSync} from './split.js';7-import {FILE_TYPES} from './type.js';8-9-// Apply `stdout`/`stderr` options, after spawning, in sync mode10-export const transformOutputSync = ({fileDescriptors, syncResult: {output}, options, isMaxBuffer, verboseInfo}) => {11- if (output === null) {12- return {output: Array.from({length: 3})};13- }14-15- const state = {};16- const transformedOutput = output.map((result, fdNumber) =>17- transformOutputResultSync({result, fileDescriptors, fdNumber, state, isMaxBuffer, verboseInfo}, options));18- return {output: transformedOutput, ...state};19-};20-21-const transformOutputResultSync = ({result, fileDescriptors, fdNumber, state, isMaxBuffer, verboseInfo}, {buffer, encoding, lines, stripFinalNewline, maxBuffer}) => {22- if (result === null) {23- return;24- }25-26- const truncatedResult = truncateResult(result, isMaxBuffer, getMaxBufferSync(maxBuffer));27- const uint8ArrayResult = bufferToUint8Array(truncatedResult);28- const {stdioItems, objectMode} = fileDescriptors[fdNumber];29- const chunks = runOutputGeneratorsSync([uint8ArrayResult], stdioItems, encoding, state);30- const {31- serializedResult,32- finalResult = serializedResult,33- } = serializeChunks({chunks, objectMode, encoding, lines, stripFinalNewline, fdNumber});34-35- if (shouldLogOutput({stdioItems, encoding, verboseInfo, fdNumber})) {36- const linesArray = splitLinesSync(serializedResult, false, objectMode);37- logLinesSync(linesArray, verboseInfo);38- }39-40- const returnedResult = buffer[fdNumber] ? finalResult : undefined;41-42- try {43- if (state.error === undefined) {44- writeToFiles(serializedResult, stdioItems);45- }46-47- return returnedResult;48- } catch (error) {49- state.error = error;50- return returnedResult;51- }52-};53-54-const truncateResult = (result, isMaxBuffer, maxBuffer) => isMaxBuffer && result.length > maxBuffer55- ? result.slice(0, maxBuffer)56- : result;57-58-const runOutputGeneratorsSync = (chunks, stdioItems, encoding, state) => {59- try {60- return runGeneratorsSync(chunks, stdioItems, encoding, false);61- } catch (error) {62- state.error = error;63- return chunks;64- }65-};66-67-const serializeChunks = ({chunks, objectMode, encoding, lines, stripFinalNewline, fdNumber}) => {68- if (objectMode) {69- return {serializedResult: chunks};70- }71-72- if (encoding === 'buffer') {73- return {serializedResult: joinToUint8Array(chunks)};74- }75-76- const serializedResult = joinToString(chunks, encoding);77- if (lines[fdNumber]) {78- return {serializedResult, finalResult: splitLinesSync(serializedResult, !stripFinalNewline[fdNumber], objectMode)};79- }80-81- return {serializedResult};82-};83-84-const writeToFiles = (serializedResult, stdioItems) => {85- for (const {type, path} of stdioItems) {86- if (FILE_TYPES.has(type)) {87- writeFileSync(path, serializedResult);88- }89- }90-};deleted:lib/stdio/pipeline.js-48 removed
1-import {finished} from 'node:stream/promises';2-import {isStandardStream} from '../utils.js';3-4-// Like `Stream.pipeline(source, destination)`, but does not destroy standard streams.5-export const pipeStreams = (source, destination) => {6- source.pipe(destination);7- onSourceFinish(source, destination);8- onDestinationFinish(source, destination);9-};10-11-// `source.pipe(destination)` makes `destination` end when `source` ends.12-// But it does not propagate aborts or errors. This function does it.13-const onSourceFinish = async (source, destination) => {14- if (isStandardStream(source) || isStandardStream(destination)) {15- return;16- }17-18- try {19- await finished(source, {cleanup: true, readable: true, writable: false});20- } catch {}21-22- endDestinationStream(destination);23-};24-25-export const endDestinationStream = destination => {26- if (destination.writable) {27- destination.end();28- }29-};30-31-// We do the same thing in the other direction as well.32-const onDestinationFinish = async (source, destination) => {33- if (isStandardStream(source) || isStandardStream(destination)) {34- return;35- }36-37- try {38- await finished(destination, {cleanup: true, readable: false, writable: true});39- } catch {}40-41- abortSourceStream(source);42-};43-44-export const abortSourceStream = source => {45- if (source.readable) {46- source.destroy();47- }48-};deleted:lib/stdio/split.js-109 removed
1-// Split chunks line-wise for generators passed to the `std*` options2-export const getSplitLinesGenerator = (binary, preserveNewlines, skipped, state) => binary || skipped3- ? undefined4- : initializeSplitLines(preserveNewlines, state);5-6-export const splitLinesSync = (chunk, preserveNewlines, objectMode) => objectMode7- ? chunk.flatMap(item => splitLinesItemSync(item, preserveNewlines))8- : splitLinesItemSync(chunk, preserveNewlines);9-10-const splitLinesItemSync = (chunk, preserveNewlines) => {11- const {transform, final} = initializeSplitLines(preserveNewlines, {});12- return [...transform(chunk), ...final()];13-};14-15-const initializeSplitLines = (preserveNewlines, state) => {16- state.previousChunks = '';17- return {18- transform: splitGenerator.bind(undefined, state, preserveNewlines),19- final: linesFinal.bind(undefined, state),20- };21-};22-23-// This imperative logic is much faster than using `String.split()` and uses very low memory.24-const splitGenerator = function * (state, preserveNewlines, chunk) {25- if (typeof chunk !== 'string') {26- yield chunk;27- return;28- }29-30- let {previousChunks} = state;31- let start = -1;32-33- for (let end = 0; end < chunk.length; end += 1) {34- if (chunk[end] === '\n') {35- const newlineLength = getNewlineLength(chunk, end, preserveNewlines, state);36- let line = chunk.slice(start + 1, end + 1 - newlineLength);37-38- if (previousChunks.length > 0) {39- line = concatString(previousChunks, line);40- previousChunks = '';41- }42-43- yield line;44- start = end;45- }46- }47-48- if (start !== chunk.length - 1) {49- previousChunks = concatString(previousChunks, chunk.slice(start + 1));50- }51-52- state.previousChunks = previousChunks;53-};54-55-const getNewlineLength = (chunk, end, preserveNewlines, state) => {56- if (preserveNewlines) {57- return 0;58- }59-60- state.isWindowsNewline = end !== 0 && chunk[end - 1] === '\r';61- return state.isWindowsNewline ? 2 : 1;62-};63-64-const linesFinal = function * ({previousChunks}) {65- if (previousChunks.length > 0) {66- yield previousChunks;67- }68-};69-70-// Unless `preserveNewlines: true` is used, we strip the newline of each line.71-// This re-adds them after the user `transform` code has run.72-export const getAppendNewlineGenerator = ({binary, preserveNewlines, readableObjectMode, state}) => binary || preserveNewlines || readableObjectMode73- ? undefined74- : {transform: appendNewlineGenerator.bind(undefined, state)};75-76-const appendNewlineGenerator = function * ({isWindowsNewline = false}, chunk) {77- const {unixNewline, windowsNewline, LF, concatBytes} = typeof chunk === 'string' ? linesStringInfo : linesUint8ArrayInfo;78-79- if (chunk.at(-1) === LF) {80- yield chunk;81- return;82- }83-84- const newline = isWindowsNewline ? windowsNewline : unixNewline;85- yield concatBytes(chunk, newline);86-};87-88-const concatString = (firstChunk, secondChunk) => `${firstChunk}${secondChunk}`;89-90-const linesStringInfo = {91- windowsNewline: '\r\n',92- unixNewline: '\n',93- LF: '\n',94- concatBytes: concatString,95-};96-97-const concatUint8Array = (firstChunk, secondChunk) => {98- const chunk = new Uint8Array(firstChunk.length + secondChunk.length);99- chunk.set(firstChunk, 0);100- chunk.set(secondChunk, firstChunk.length);101- return chunk;102-};103-104-const linesUint8ArrayInfo = {105- windowsNewline: new Uint8Array([0x0D, 0x0A]),106- unixNewline: new Uint8Array([0x0A]),107- LF: 0x0A,108- concatBytes: concatUint8Array,109-};added:lib/stdio/stdio-option.js+57 added
1+import {STANDARD_STREAMS_ALIASES} from '../utils/standard-stream.js';2+3+// Add support for `stdin`/`stdout`/`stderr` as an alias for `stdio`4+export const normalizeStdioOption = ({stdio, ipc, buffer, verbose, ...options}, isSync) => {5+ const stdioArray = getStdioArray(stdio, options).map((stdioOption, fdNumber) => addDefaultValue(stdioOption, fdNumber));6+ return isSync ? normalizeStdioSync(stdioArray, buffer, verbose) : normalizeStdioAsync(stdioArray, ipc);7+};8+9+const getStdioArray = (stdio, options) => {10+ if (stdio === undefined) {11+ return STANDARD_STREAMS_ALIASES.map(alias => options[alias]);12+ }13+14+ if (hasAlias(options)) {15+ throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${STANDARD_STREAMS_ALIASES.map(alias => `\`${alias}\``).join(', ')}`);16+ }17+18+ if (typeof stdio === 'string') {19+ return [stdio, stdio, stdio];20+ }21+22+ if (!Array.isArray(stdio)) {23+ throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``);24+ }25+26+ const length = Math.max(stdio.length, STANDARD_STREAMS_ALIASES.length);27+ return Array.from({length}, (_, fdNumber) => stdio[fdNumber]);28+};29+30+const hasAlias = options => STANDARD_STREAMS_ALIASES.some(alias => options[alias] !== undefined);31+32+const addDefaultValue = (stdioOption, fdNumber) => {33+ if (Array.isArray(stdioOption)) {34+ return stdioOption.map(item => addDefaultValue(item, fdNumber));35+ }36+37+ if (stdioOption === null || stdioOption === undefined) {38+ return fdNumber >= STANDARD_STREAMS_ALIASES.length ? 'ignore' : 'pipe';39+ }40+41+ return stdioOption;42+};43+44+const normalizeStdioSync = (stdioArray, buffer, verbose) => stdioArray.map((stdioOption, fdNumber) =>45+ !buffer[fdNumber]46+ && fdNumber !== 047+ && verbose[fdNumber] !== 'full'48+ && isOutputPipeOnly(stdioOption)49+ ? 'ignore'50+ : stdioOption);51+52+const isOutputPipeOnly = stdioOption => stdioOption === 'pipe'53+ || (Array.isArray(stdioOption) && stdioOption.every(item => item === 'pipe'));54+55+const normalizeStdioAsync = (stdioArray, ipc) => ipc && !stdioArray.includes('ipc')56+ ? [...stdioArray, 'ipc']57+ : stdioArray;deleted:lib/stdio/sync.js-54 removed
1-import {readFileSync} from 'node:fs';2-import {bufferToUint8Array} from './uint-array.js';3-import {handleInput} from './handle.js';4-import {TYPE_TO_MESSAGE} from './type.js';5-6-// Normalize `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in sync mode7-export const handleInputSync = (options, verboseInfo) => handleInput(addPropertiesSync, options, verboseInfo, true);8-9-const forbiddenIfSync = ({type, optionName}) => {10- throwInvalidSyncValue(optionName, TYPE_TO_MESSAGE[type]);11-};12-13-const forbiddenNativeIfSync = ({optionName, value}) => {14- if (value === 'ipc' || value === 'overlapped') {15- throwInvalidSyncValue(optionName, `"${value}"`);16- }17-18- return {};19-};20-21-const throwInvalidSyncValue = (optionName, value) => {22- throw new TypeError(`The \`${optionName}\` option cannot be ${value} with synchronous methods.`);23-};24-25-const addProperties = {26- generator() {},27- asyncGenerator: forbiddenIfSync,28- webStream: forbiddenIfSync,29- nodeStream: forbiddenIfSync,30- webTransform: forbiddenIfSync,31- duplex: forbiddenIfSync,32- asyncIterable: forbiddenIfSync,33- native: forbiddenNativeIfSync,34-};35-36-const addPropertiesSync = {37- input: {38- ...addProperties,39- fileUrl: ({value}) => ({contents: [bufferToUint8Array(readFileSync(value))]}),40- filePath: ({value: {file}}) => ({contents: [bufferToUint8Array(readFileSync(file))]}),41- iterable: ({value}) => ({contents: [...value]}),42- string: ({value}) => ({contents: [value]}),43- uint8Array: ({value}) => ({contents: [value]}),44- },45- output: {46- ...addProperties,47- fileUrl: ({value}) => ({path: value}),48- filePath: ({value: {file}}) => ({path: file}),49- fileNumber: ({value}) => ({path: value}),50- iterable: forbiddenIfSync,51- string: forbiddenIfSync,52- uint8Array: forbiddenIfSync,53- },54-};deleted:lib/stdio/transform-async.js-59 removed
1-import {callbackify} from 'node:util';2-3-export const pushChunks = callbackify(async (getChunks, state, args, transformStream) => {4- state.currentIterable = getChunks(...args);5-6- try {7- for await (const chunk of state.currentIterable) {8- transformStream.push(chunk);9- }10- } finally {11- delete state.currentIterable;12- }13-});14-15-// For each new chunk, apply each `transform()` method16-export const transformChunk = async function * (chunk, generators, index) {17- if (index === generators.length) {18- yield chunk;19- return;20- }21-22- const {transform = identityGenerator} = generators[index];23- for await (const transformedChunk of transform(chunk)) {24- yield * transformChunk(transformedChunk, generators, index + 1);25- }26-};27-28-// At the end, apply each `final()` method, followed by the `transform()` method of the next transforms29-export const finalChunks = async function * (generators) {30- for (const [index, {final}] of Object.entries(generators)) {31- yield * generatorFinalChunks(final, Number(index), generators);32- }33-};34-35-const generatorFinalChunks = async function * (final, index, generators) {36- if (final === undefined) {37- return;38- }39-40- for await (const finalChunk of final()) {41- yield * transformChunk(finalChunk, generators, index + 1);42- }43-};44-45-// Cancel any ongoing async generator when the Transform is destroyed, e.g. when the subprocess errors46-export const destroyTransform = callbackify(async ({currentIterable}, error) => {47- if (currentIterable !== undefined) {48- await (error ? currentIterable.throw(error) : currentIterable.return());49- return;50- }51-52- if (error) {53- throw error;54- }55-});56-57-const identityGenerator = function * (chunk) {58- yield chunk;59-};deleted:lib/stdio/transform-run.js-90 removed
1-import {Transform, getDefaultHighWaterMark} from 'node:stream';2-import {pushChunks, transformChunk, finalChunks, destroyTransform} from './transform-async.js';3-import {pushChunksSync, transformChunkSync, finalChunksSync, runTransformSync} from './transform-sync.js';4-import {getEncodingTransformGenerator} from './encoding-transform.js';5-import {getSplitLinesGenerator, getAppendNewlineGenerator} from './split.js';6-import {getValidateTransformInput, getValidateTransformReturn} from './validate.js';7-import {isAsyncGenerator} from './type.js';8-9-/*10-Generators can be used to transform/filter standard streams.11-12-Generators have a simple syntax, yet allows all of the following:13-- Sharing `state` between chunks14-- Flushing logic, by using a `final` function15-- Asynchronous logic16-- Emitting multiple chunks from a single source chunk, even if spaced in time, by using multiple `yield`17-- Filtering, by using no `yield`18-19-Therefore, there is no need to allow Node.js or web transform streams.20-21-The `highWaterMark` is kept as the default value, since this is what `subprocess.std*` uses.22-23-Chunks are currently processed serially. We could add a `concurrency` option to parallelize in the future.24-25-Transform an array of generator functions into a `Transform` stream.26-`Duplex.from(generator)` cannot be used because it does not allow setting the `objectMode` and `highWaterMark`.27-*/28-export const generatorToStream = ({29- value,30- value: {transform, final, writableObjectMode, readableObjectMode},31- optionName,32-}, {encoding}) => {33- const state = {};34- const generators = addInternalGenerators(value, encoding, optionName);35-36- const transformAsync = isAsyncGenerator(transform);37- const finalAsync = isAsyncGenerator(final);38- const transformMethod = transformAsync39- ? pushChunks.bind(undefined, transformChunk, state)40- : pushChunksSync.bind(undefined, transformChunkSync);41- const finalMethod = transformAsync || finalAsync42- ? pushChunks.bind(undefined, finalChunks, state)43- : pushChunksSync.bind(undefined, finalChunksSync);44- const destroyMethod = transformAsync || finalAsync45- ? destroyTransform.bind(undefined, state)46- : undefined;47-48- const stream = new Transform({49- writableObjectMode,50- writableHighWaterMark: getDefaultHighWaterMark(writableObjectMode),51- readableObjectMode,52- readableHighWaterMark: getDefaultHighWaterMark(readableObjectMode),53- transform(chunk, encoding, done) {54- transformMethod([chunk, generators, 0], this, done);55- },56- flush(done) {57- finalMethod([generators], this, done);58- },59- destroy: destroyMethod,60- });61- return {stream};62-};63-64-export const runGeneratorsSync = (chunks, stdioItems, encoding, isInput) => {65- const generators = stdioItems.filter(({type}) => type === 'generator');66- const reversedGenerators = isInput ? generators.reverse() : generators;67-68- for (const {value, optionName} of reversedGenerators) {69- const generators = addInternalGenerators(value, encoding, optionName);70- chunks = runTransformSync(generators, chunks);71- }72-73- return chunks;74-};75-76-const addInternalGenerators = (77- {transform, final, binary, writableObjectMode, readableObjectMode, preserveNewlines},78- encoding,79- optionName,80-) => {81- const state = {};82- return [83- {transform: getValidateTransformInput(writableObjectMode, optionName)},84- getEncodingTransformGenerator(binary, encoding, writableObjectMode),85- getSplitLinesGenerator(binary, preserveNewlines, writableObjectMode, state),86- {transform, final},87- {transform: getValidateTransformReturn(readableObjectMode, optionName)},88- getAppendNewlineGenerator({binary, preserveNewlines, readableObjectMode, state}),89- ].filter(Boolean);90-};deleted:lib/stdio/transform-sync.js-50 removed
1-// Duplicate the code from `transform-async.js` but as synchronous functions2-export const pushChunksSync = (getChunksSync, args, transformStream, done) => {3- try {4- for (const chunk of getChunksSync(...args)) {5- transformStream.push(chunk);6- }7-8- done();9- } catch (error) {10- done(error);11- }12-};13-14-// Run synchronous generators with `execaSync()`15-export const runTransformSync = (generators, chunks) => [16- ...chunks.flatMap(chunk => [...transformChunkSync(chunk, generators, 0)]),17- ...finalChunksSync(generators),18-];19-20-export const transformChunkSync = function * (chunk, generators, index) {21- if (index === generators.length) {22- yield chunk;23- return;24- }25-26- const {transform = identityGenerator} = generators[index];27- for (const transformedChunk of transform(chunk)) {28- yield * transformChunkSync(transformedChunk, generators, index + 1);29- }30-};31-32-export const finalChunksSync = function * (generators) {33- for (const [index, {final}] of Object.entries(generators)) {34- yield * generatorFinalChunksSync(final, Number(index), generators);35- }36-};37-38-const generatorFinalChunksSync = function * (final, index, generators) {39- if (final === undefined) {40- return;41- }42-43- for (const finalChunk of final()) {44- yield * transformChunkSync(finalChunk, generators, index + 1);45- }46-};47-48-const identityGenerator = function * (chunk) {49- yield chunk;50-};modified:lib/stdio/type.js+1 added-1 removed
1 import {isStream as isNodeStream, isDuplexStream} from 'is-stream';2 import isPlainObj from 'is-plain-obj';3-import {isUint8Array} from './uint-array.js';3+import {isUint8Array} from '../utils/uint-array.js';4 5 // The `stdin`/`stdout`/`stderr` option can be of many types. This detects it.6 export const getStdioItemType = (value, optionName) => {7 if (isAsyncGenerator(value)) {156 unmodified linesdeleted:lib/stdio/uint-array.js-69 removed
1-import {Buffer} from 'node:buffer';2-import {StringDecoder} from 'node:string_decoder';3-4-const {toString: objectToString} = Object.prototype;5-6-export const isArrayBuffer = value => objectToString.call(value) === '[object ArrayBuffer]';7-8-export const isUint8Array = value => objectToString.call(value) === '[object Uint8Array]' && !Buffer.isBuffer(value);9-10-export const bufferToUint8Array = buffer => new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);11-12-const textEncoder = new TextEncoder();13-const stringToUint8Array = string => textEncoder.encode(string);14-15-const textDecoder = new TextDecoder();16-export const uint8ArrayToString = uint8Array => textDecoder.decode(uint8Array);17-18-export const joinToString = (uint8ArraysOrStrings, encoding) => {19- const strings = uint8ArraysToStrings(uint8ArraysOrStrings, encoding);20- return strings.join('');21-};22-23-const uint8ArraysToStrings = (uint8ArraysOrStrings, encoding) => {24- if (encoding === 'utf8' && uint8ArraysOrStrings.every(uint8ArrayOrString => typeof uint8ArrayOrString === 'string')) {25- return uint8ArraysOrStrings;26- }27-28- const decoder = new StringDecoder(encoding);29- const strings = uint8ArraysOrStrings30- .map(uint8ArrayOrString => typeof uint8ArrayOrString === 'string'31- ? stringToUint8Array(uint8ArrayOrString)32- : uint8ArrayOrString)33- .map(uint8Array => decoder.write(uint8Array));34- const finalString = decoder.end();35- return finalString === '' ? strings : [...strings, finalString];36-};37-38-export const joinToUint8Array = uint8ArraysOrStrings => {39- if (uint8ArraysOrStrings.length === 1 && isUint8Array(uint8ArraysOrStrings[0])) {40- return uint8ArraysOrStrings[0];41- }42-43- return concatUint8Arrays(stringsToUint8Arrays(uint8ArraysOrStrings));44-};45-46-const stringsToUint8Arrays = uint8ArraysOrStrings => uint8ArraysOrStrings.map(uint8ArrayOrString => typeof uint8ArrayOrString === 'string'47- ? stringToUint8Array(uint8ArrayOrString)48- : uint8ArrayOrString);49-50-export const concatUint8Arrays = uint8Arrays => {51- const result = new Uint8Array(getJoinLength(uint8Arrays));52-53- let index = 0;54- for (const uint8Array of uint8Arrays) {55- result.set(uint8Array, index);56- index += uint8Array.length;57- }58-59- return result;60-};61-62-const getJoinLength = uint8Arrays => {63- let joinLength = 0;64- for (const uint8Array of uint8Arrays) {65- joinLength += uint8Array.length;66- }67-68- return joinLength;69-};deleted:lib/stdio/validate.js-42 removed
1-import {Buffer} from 'node:buffer';2-import {isUint8Array} from './uint-array.js';3-4-export const getValidateTransformInput = (writableObjectMode, optionName) => writableObjectMode5- ? undefined6- : validateStringTransformInput.bind(undefined, optionName);7-8-const validateStringTransformInput = function * (optionName, chunk) {9- if (typeof chunk !== 'string' && !isUint8Array(chunk) && !Buffer.isBuffer(chunk)) {10- throw new TypeError(`The \`${optionName}\` option's transform must use "objectMode: true" to receive as input: ${typeof chunk}.`);11- }12-13- yield chunk;14-};15-16-export const getValidateTransformReturn = (readableObjectMode, optionName) => readableObjectMode17- ? validateObjectTransformReturn.bind(undefined, optionName)18- : validateStringTransformReturn.bind(undefined, optionName);19-20-const validateObjectTransformReturn = function * (optionName, chunk) {21- validateEmptyReturn(optionName, chunk);22- yield chunk;23-};24-25-const validateStringTransformReturn = function * (optionName, chunk) {26- validateEmptyReturn(optionName, chunk);27-28- if (typeof chunk !== 'string' && !isUint8Array(chunk)) {29- const typeName = Buffer.isBuffer(chunk) ? 'a buffer' : typeof chunk;30- throw new TypeError(`The \`${optionName}\` option's function must yield a string or an Uint8Array, not ${typeName}.`);31- }32-33- yield chunk;34-};35-36-const validateEmptyReturn = (optionName, chunk) => {37- if (chunk === null || chunk === undefined) {38- throw new TypeError(`The \`${optionName}\` option's function must not call \`yield ${chunk}\`.39-Instead, \`yield\` should either be called with a value, or not be called at all. For example:40- if (condition) { yield value; }`);41- }42-};deleted:lib/stream/all.js-46 removed
1-import mergeStreams from '@sindresorhus/merge-streams';2-import {waitForSubprocessStream} from './subprocess.js';3-4-// `all` interleaves `stdout` and `stderr`5-export const makeAllStream = ({stdout, stderr}, {all}) => all && (stdout || stderr)6- ? mergeStreams([stdout, stderr].filter(Boolean))7- : undefined;8-9-// Read the contents of `subprocess.all` and|or wait for its completion10-export const waitForAllStream = ({subprocess, encoding, buffer, maxBuffer, lines, stripFinalNewline, verboseInfo, streamInfo}) => waitForSubprocessStream({11- ...getAllStream(subprocess, buffer),12- fdNumber: 'all',13- encoding,14- maxBuffer: maxBuffer[1] + maxBuffer[2],15- lines: lines[1] || lines[2],16- allMixed: getAllMixed(subprocess),17- stripFinalNewline,18- verboseInfo,19- streamInfo,20-});21-22-const getAllStream = ({stdout, stderr, all}, [, bufferStdout, bufferStderr]) => {23- const buffer = bufferStdout || bufferStderr;24- if (!buffer) {25- return {stream: all, buffer};26- }27-28- if (!bufferStdout) {29- return {stream: stderr, buffer};30- }31-32- if (!bufferStderr) {33- return {stream: stdout, buffer};34- }35-36- return {stream: all, buffer};37-};38-39-// When `subprocess.stdout` is in objectMode but not `subprocess.stderr` (or the opposite), we need to use both:40-// - `getStreamAsArray()` for the chunks in objectMode, to return as an array without changing each chunk41-// - `getStreamAsArrayBuffer()` or `getStream()` for the chunks not in objectMode, to convert them from Buffers to string or Uint8Array42-// We do this by emulating the Buffer -> string|Uint8Array conversion performed by `get-stream` with our own, which is identical.43-const getAllMixed = ({all, stdout, stderr}) => all44- && stdout45- && stderr46- && stdout.readableObjectMode !== stderr.readableObjectMode;deleted:lib/stream/contents.js-63 removed
1-import {setImmediate} from 'node:timers/promises';2-import getStream, {getStreamAsArrayBuffer, getStreamAsArray} from 'get-stream';3-import {isArrayBuffer} from '../stdio/uint-array.js';4-import {iterateForResult} from '../convert/loop.js';5-import {shouldLogOutput, logLines} from '../verbose/output.js';6-import {getStripFinalNewline} from '../return/strip-newline.js';7-import {handleMaxBuffer} from './max-buffer.js';8-9-export const getStreamOutput = async ({stream, onStreamEnd, fdNumber, encoding, buffer, maxBuffer, lines, allMixed, stripFinalNewline, verboseInfo, streamInfo: {fileDescriptors}}) => {10- if (shouldLogOutput({stdioItems: fileDescriptors[fdNumber]?.stdioItems, encoding, verboseInfo, fdNumber})) {11- const linesIterable = iterateForResult({stream, onStreamEnd, lines: true, encoding, stripFinalNewline: true, allMixed});12- logLines(linesIterable, stream, verboseInfo);13- }14-15- if (!buffer) {16- await resumeStream(stream);17- return;18- }19-20- const stripFinalNewlineValue = getStripFinalNewline(stripFinalNewline, fdNumber);21- const iterable = iterateForResult({stream, onStreamEnd, lines, encoding, stripFinalNewline: stripFinalNewlineValue, allMixed});22- return getStreamContents({stream, iterable, fdNumber, encoding, maxBuffer, lines});23-};24-25-// When using `buffer: false`, users need to read `subprocess.stdout|stderr|all` right away26-// See https://github.com/sindresorhus/execa/issues/730 and https://github.com/sindresorhus/execa/pull/729#discussion_r146549631027-const resumeStream = async stream => {28- await setImmediate();29- if (stream.readableFlowing === null) {30- stream.resume();31- }32-};33-34-const getStreamContents = async ({stream, stream: {readableObjectMode}, iterable, fdNumber, encoding, maxBuffer, lines}) => {35- try {36- if (readableObjectMode || lines) {37- return await getStreamAsArray(iterable, {maxBuffer});38- }39-40- if (encoding === 'buffer') {41- return new Uint8Array(await getStreamAsArrayBuffer(iterable, {maxBuffer}));42- }43-44- return await getStream(iterable, {maxBuffer});45- } catch (error) {46- return handleBufferedData(handleMaxBuffer({error, stream, readableObjectMode, lines, encoding, fdNumber}));47- }48-};49-50-// On failure, `result.stdout|stderr|all` should contain the currently buffered stream51-// They are automatically closed and flushed by Node.js when the subprocess exits52-// When `buffer` is `false`, `streamPromise` is `undefined` and there is no buffered data to retrieve53-export const getBufferedData = async streamPromise => {54- try {55- return await streamPromise;56- } catch (error) {57- return handleBufferedData(error);58- }59-};60-61-const handleBufferedData = ({bufferedData}) => isArrayBuffer(bufferedData)62- ? new Uint8Array(bufferedData)63- : bufferedData;deleted:lib/stream/exit-async.js-45 removed
1-import {once} from 'node:events';2-import {DiscardedError} from '../return/cause.js';3-4-// If `error` is emitted before `spawn`, `exit` will never be emitted.5-// However, `error` might be emitted after `spawn`, e.g. with the `cancelSignal` option.6-// In that case, `exit` will still be emitted.7-// Since the `exit` event contains the signal name, we want to make sure we are listening for it.8-// This function also takes into account the following unlikely cases:9-// - `exit` being emitted in the same microtask as `spawn`10-// - `error` being emitted multiple times11-export const waitForExit = async subprocess => {12- const [spawnPayload, exitPayload] = await Promise.allSettled([13- once(subprocess, 'spawn'),14- once(subprocess, 'exit'),15- ]);16-17- if (spawnPayload.status === 'rejected') {18- return [];19- }20-21- return exitPayload.status === 'rejected'22- ? waitForSubprocessExit(subprocess)23- : exitPayload.value;24-};25-26-const waitForSubprocessExit = async subprocess => {27- try {28- return await once(subprocess, 'exit');29- } catch {30- return waitForSubprocessExit(subprocess);31- }32-};33-34-export const waitForSuccessfulExit = async exitPromise => {35- const [exitCode, signal] = await exitPromise;36-37- if (!isSubprocessErrorExit(exitCode, signal) && isFailedExit(exitCode, signal)) {38- throw new DiscardedError();39- }40-41- return [exitCode, signal];42-};43-44-const isSubprocessErrorExit = (exitCode, signal) => exitCode === undefined && signal === undefined;45-export const isFailedExit = (exitCode, signal) => exitCode !== 0 || signal !== null;deleted:lib/stream/exit-sync.js-18 removed
1-import {DiscardedError} from '../return/cause.js';2-import {isMaxBufferSync} from './max-buffer.js';3-import {isFailedExit} from './exit-async.js';4-5-export const getExitResultSync = ({error, status: exitCode, signal, output}, {maxBuffer}) => {6- const resultError = getResultError(error, exitCode, signal);7- const timedOut = resultError?.code === 'ETIMEDOUT';8- const isMaxBuffer = isMaxBufferSync(resultError, output, maxBuffer);9- return {resultError, exitCode, signal, timedOut, isMaxBuffer};10-};11-12-const getResultError = (error, exitCode, signal) => {13- if (error !== undefined) {14- return error;15- }16-17- return isFailedExit(exitCode, signal) ? new DiscardedError() : undefined;18-};deleted:lib/stream/max-buffer.js-55 removed
1-import {MaxBufferError} from 'get-stream';2-import {getStreamName} from '../utils.js';3-4-export const handleMaxBuffer = ({error, stream, readableObjectMode, lines, encoding, fdNumber}) => {5- if (!(error instanceof MaxBufferError)) {6- throw error;7- }8-9- if (fdNumber === 'all') {10- return error;11- }12-13- const unit = getMaxBufferUnit(readableObjectMode, lines, encoding);14- error.maxBufferInfo = {fdNumber, unit};15- stream.destroy();16- throw error;17-};18-19-const getMaxBufferUnit = (readableObjectMode, lines, encoding) => {20- if (readableObjectMode) {21- return 'objects';22- }23-24- if (lines) {25- return 'lines';26- }27-28- if (encoding === 'buffer') {29- return 'bytes';30- }31-32- return 'characters';33-};34-35-export const getMaxBufferMessage = (error, maxBuffer) => {36- const {streamName, threshold, unit} = getMaxBufferInfo(error, maxBuffer);37- return `Command's ${streamName} was larger than ${threshold} ${unit}`;38-};39-40-const getMaxBufferInfo = (error, maxBuffer) => {41- if (error?.maxBufferInfo === undefined) {42- return {streamName: 'output', threshold: maxBuffer[1], unit: 'bytes'};43- }44-45- const {maxBufferInfo: {fdNumber, unit}} = error;46- delete error.maxBufferInfo;47- return {streamName: getStreamName(fdNumber), threshold: maxBuffer[fdNumber], unit};48-};49-50-export const isMaxBufferSync = (resultError, output, maxBuffer) => resultError?.code === 'ENOBUFS'51- && output !== null52- && output.some(result => result !== null && result.length > getMaxBufferSync(maxBuffer));53-54-// `spawnSync()` does not allow differentiating `maxBuffer` per file descriptor, so we always use `stdout`55-export const getMaxBufferSync = maxBuffer => maxBuffer[1];deleted:lib/stream/resolve.js-82 removed
1-import {once} from 'node:events';2-import {isStream as isNodeStream} from 'is-stream';3-import {errorSignal} from '../exit/kill.js';4-import {throwOnTimeout} from '../exit/timeout.js';5-import {isStandardStream} from '../utils.js';6-import {TRANSFORM_TYPES} from '../stdio/type.js';7-import {waitForAllStream} from './all.js';8-import {waitForSubprocessStreams} from './subprocess.js';9-import {getBufferedData} from './contents.js';10-import {waitForExit, waitForSuccessfulExit} from './exit-async.js';11-import {waitForStream} from './wait.js';12-13-// Retrieve result of subprocess: exit code, signal, error, streams (stdout/stderr/all)14-export const getSubprocessResult = async ({15- subprocess,16- options: {encoding, buffer, maxBuffer, lines, timeoutDuration: timeout, stripFinalNewline},17- context,18- verboseInfo,19- fileDescriptors,20- originalStreams,21- controller,22-}) => {23- const exitPromise = waitForExit(subprocess);24- const streamInfo = {originalStreams, fileDescriptors, subprocess, exitPromise, propagating: false};25-26- const stdioPromises = waitForSubprocessStreams({subprocess, encoding, buffer, maxBuffer, lines, stripFinalNewline, verboseInfo, streamInfo});27- const allPromise = waitForAllStream({subprocess, encoding, buffer, maxBuffer, lines, stripFinalNewline, verboseInfo, streamInfo});28- const originalPromises = waitForOriginalStreams(originalStreams, subprocess, streamInfo);29- const customStreamsEndPromises = waitForCustomStreamsEnd(fileDescriptors, streamInfo);30-31- try {32- return await Promise.race([33- Promise.all([34- {},35- waitForSuccessfulExit(exitPromise),36- Promise.all(stdioPromises),37- allPromise,38- ...originalPromises,39- ...customStreamsEndPromises,40- ]),41- throwOnSubprocessError(subprocess, controller),42- throwOnInternalError(subprocess, controller),43- ...throwOnTimeout(subprocess, timeout, context, controller),44- ]);45- } catch (error) {46- return Promise.all([47- {error},48- exitPromise,49- Promise.all(stdioPromises.map(stdioPromise => getBufferedData(stdioPromise))),50- getBufferedData(allPromise),51- Promise.allSettled(originalPromises),52- Promise.allSettled(customStreamsEndPromises),53- ]);54- }55-};56-57-// Transforms replace `subprocess.std*`, which means they are not exposed to users.58-// However, we still want to wait for their completion.59-const waitForOriginalStreams = (originalStreams, subprocess, streamInfo) =>60- originalStreams.map((stream, fdNumber) => stream === subprocess.stdio[fdNumber]61- ? undefined62- : waitForStream(stream, fdNumber, streamInfo));63-64-// Some `stdin`/`stdout`/`stderr` options create a stream, e.g. when passing a file path.65-// The `.pipe()` method automatically ends that stream when `subprocess` ends.66-// This makes sure we wait for the completion of those streams, in order to catch any error.67-const waitForCustomStreamsEnd = (fileDescriptors, streamInfo) => fileDescriptors.flatMap(({stdioItems}, fdNumber) => stdioItems68- .filter(({value, stream = value}) => isNodeStream(stream, {checkOpen: false}) && !isStandardStream(stream))69- .map(({type, value, stream = value}) => waitForStream(stream, fdNumber, streamInfo, {70- isSameDirection: TRANSFORM_TYPES.has(type),71- stopOnExit: type === 'native',72- })));73-74-const throwOnSubprocessError = async (subprocess, {signal}) => {75- const [error] = await once(subprocess, 'error', {signal});76- throw error;77-};78-79-const throwOnInternalError = async (subprocess, {signal}) => {80- const [error] = await once(subprocess, errorSignal, {signal});81- throw error;82-};deleted:lib/stream/subprocess.js-34 removed
1-import {waitForStream, isInputFileDescriptor} from './wait.js';2-import {getStreamOutput} from './contents.js';3-4-// Read the contents of `subprocess.std*` and|or wait for its completion5-export const waitForSubprocessStreams = ({subprocess, encoding, buffer, maxBuffer, lines, stripFinalNewline, verboseInfo, streamInfo}) => subprocess.stdio.map((stream, fdNumber) => waitForSubprocessStream({6- stream,7- fdNumber,8- encoding,9- buffer: buffer[fdNumber],10- maxBuffer: maxBuffer[fdNumber],11- lines: lines[fdNumber],12- allMixed: false,13- stripFinalNewline,14- verboseInfo,15- streamInfo,16-}));17-18-export const waitForSubprocessStream = async ({stream, fdNumber, encoding, buffer, maxBuffer, lines, allMixed, stripFinalNewline, verboseInfo, streamInfo}) => {19- if (!stream) {20- return;21- }22-23- const onStreamEnd = waitForStream(stream, fdNumber, streamInfo);24- if (isInputFileDescriptor(streamInfo, fdNumber)) {25- await onStreamEnd;26- return;27- }28-29- const [output] = await Promise.all([30- getStreamOutput({stream, onStreamEnd, fdNumber, encoding, buffer, maxBuffer, lines, allMixed, stripFinalNewline, verboseInfo, streamInfo}),31- onStreamEnd,32- ]);33- return output;34-};deleted:lib/stream/wait.js-96 removed
1-import {finished} from 'node:stream/promises';2-3-// Wraps `finished(stream)` to handle the following case:4-// - When the subprocess exits, Node.js automatically calls `subprocess.stdin.destroy()`, which we need to ignore.5-// - However, we still need to throw if `subprocess.stdin.destroy()` is called before subprocess exit.6-export const waitForStream = async (stream, fdNumber, streamInfo, {isSameDirection, stopOnExit = false} = {}) => {7- const state = handleStdinDestroy(stream, streamInfo);8- const abortController = new AbortController();9- try {10- await Promise.race([11- ...(stopOnExit ? [streamInfo.exitPromise] : []),12- finished(stream, {cleanup: true, signal: abortController.signal}),13- ]);14- } catch (error) {15- if (!state.stdinCleanedUp) {16- handleStreamError(error, fdNumber, streamInfo, isSameDirection);17- }18- } finally {19- abortController.abort();20- }21-};22-23-// If `subprocess.stdin` is destroyed before being fully written to, it is considered aborted and should throw an error.24-// This can happen for example when user called `subprocess.stdin.destroy()` before `subprocess.stdin.end()`.25-// However, Node.js calls `subprocess.stdin.destroy()` on exit for cleanup purposes.26-// https://github.com/nodejs/node/blob/0b4cdb4b42956cbd7019058e409e06700a199e11/lib/internal/child_process.js#L27827-// This is normal and should not throw an error.28-// Therefore, we need to differentiate between both situations to know whether to throw an error.29-// Unfortunately, events (`close`, `error`, `end`, `exit`) cannot be used because `.destroy()` can take an arbitrary amount of time.30-// For example, `stdin: 'pipe'` is implemented as a TCP socket, and its `.destroy()` method waits for TCP disconnection.31-// Therefore `.destroy()` might end before or after subprocess exit, based on OS speed and load.32-// The only way to detect this is to spy on `subprocess.stdin._destroy()` by wrapping it.33-// If `subprocess.exitCode` or `subprocess.signalCode` is set, it means `.destroy()` is being called by Node.js itself.34-const handleStdinDestroy = (stream, {originalStreams: [originalStdin], subprocess}) => {35- const state = {stdinCleanedUp: false};36- if (stream === originalStdin) {37- spyOnStdinDestroy(stream, subprocess, state);38- }39-40- return state;41-};42-43-const spyOnStdinDestroy = (subprocessStdin, subprocess, state) => {44- const {_destroy} = subprocessStdin;45- subprocessStdin._destroy = (...args) => {46- setStdinCleanedUp(subprocess, state);47- _destroy.call(subprocessStdin, ...args);48- };49-};50-51-const setStdinCleanedUp = ({exitCode, signalCode}, state) => {52- if (exitCode !== null || signalCode !== null) {53- state.stdinCleanedUp = true;54- }55-};56-57-// We ignore EPIPEs on writable streams and aborts on readable streams since those can happen normally.58-// When one stream errors, the error is propagated to the other streams on the same file descriptor.59-// Those other streams might have a different direction due to the above.60-// When this happens, the direction of both the initial stream and the others should then be taken into account.61-// Therefore, we keep track of whether a stream error is currently propagating.62-const handleStreamError = (error, fdNumber, streamInfo, isSameDirection) => {63- if (!shouldIgnoreStreamError(error, fdNumber, streamInfo, isSameDirection)) {64- throw error;65- }66-};67-68-const shouldIgnoreStreamError = (error, fdNumber, streamInfo, isSameDirection = true) => {69- if (streamInfo.propagating) {70- return isStreamEpipe(error) || isStreamAbort(error);71- }72-73- streamInfo.propagating = true;74- return isInputFileDescriptor(streamInfo, fdNumber) === isSameDirection75- ? isStreamEpipe(error)76- : isStreamAbort(error);77-};78-79-// Unfortunately, we cannot use the stream's class or properties to know whether it is readable or writable.80-// For example, `subprocess.stdin` is technically a Duplex, but can only be used as a writable.81-// Therefore, we need to use the file descriptor's direction (`stdin` is input, `stdout` is output, etc.).82-// However, while `subprocess.std*` and transforms follow that direction, any stream passed the `std*` option has the opposite direction.83-// For example, `subprocess.stdin` is a writable, but the `stdin` option is a readable.84-export const isInputFileDescriptor = ({fileDescriptors}, fdNumber) => fdNumber !== 'all' && fileDescriptors[fdNumber].direction === 'input';85-86-// When `stream.destroy()` is called without an `error` argument, stream is aborted.87-// This is the only way to abort a readable stream, which can be useful in some instances.88-// Therefore, we ignore this error on readable streams.89-export const isStreamAbort = error => error?.code === 'ERR_STREAM_PREMATURE_CLOSE';90-91-// When `stream.write()` is called but the underlying source has been closed, `EPIPE` is emitted.92-// When piping subprocesses, the source subprocess usually decides when to stop piping.93-// However, there are some instances when the destination does instead, such as `... | head -n1`.94-// It notifies the source by using `EPIPE`.95-// Therefore, we ignore this error on writable streams.96-const isStreamEpipe = error => error?.code === 'EPIPE';added:lib/terminate/cleanup.js+16 added
1+import {addAbortListener} from 'node:events';2+import {onExit} from 'signal-exit';3+4+// `cleanup` option handling5+export const cleanupOnExit = (subprocess, {cleanup, detached}, {signal}) => {6+ if (!cleanup || detached) {7+ return;8+ }9+10+ const removeExitHandler = onExit(() => {11+ subprocess.kill();12+ });13+ addAbortListener(signal, () => {14+ removeExitHandler();15+ });16+};added:lib/terminate/kill.js+76 added
1+import os from 'node:os';2+import {setTimeout} from 'node:timers/promises';3+import {isErrorInstance} from '../return/final-error.js';4+5+export const normalizeForceKillAfterDelay = forceKillAfterDelay => {6+ if (forceKillAfterDelay === false) {7+ return forceKillAfterDelay;8+ }9+10+ if (forceKillAfterDelay === true) {11+ return DEFAULT_FORCE_KILL_TIMEOUT;12+ }13+14+ if (!Number.isFinite(forceKillAfterDelay) || forceKillAfterDelay < 0) {15+ throw new TypeError(`Expected the \`forceKillAfterDelay\` option to be a non-negative integer, got \`${forceKillAfterDelay}\` (${typeof forceKillAfterDelay})`);16+ }17+18+ return forceKillAfterDelay;19+};20+21+const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5;22+23+// Monkey-patches `subprocess.kill()` to add `forceKillAfterDelay` behavior and `.kill(error)`24+export const subprocessKill = ({kill, subprocess, options: {forceKillAfterDelay, killSignal}, controller}, signalOrError, errorArgument) => {25+ const {signal, error} = parseKillArguments(signalOrError, errorArgument, killSignal);26+ emitKillError(subprocess, error);27+ const killResult = kill(signal);28+ setKillTimeout({kill, signal, forceKillAfterDelay, killSignal, killResult, controller});29+ return killResult;30+};31+32+const parseKillArguments = (signalOrError, errorArgument, killSignal) => {33+ const [signal = killSignal, error] = isErrorInstance(signalOrError)34+ ? [undefined, signalOrError]35+ : [signalOrError, errorArgument];36+37+ if (typeof signal !== 'string' && typeof signal !== 'number') {38+ throw new TypeError(`The first argument must be an error instance or a signal name string/number: ${signal}`);39+ }40+41+ if (error !== undefined && !isErrorInstance(error)) {42+ throw new TypeError(`The second argument is optional. If specified, it must be an error instance: ${error}`);43+ }44+45+ return {signal, error};46+};47+48+const emitKillError = (subprocess, error) => {49+ if (error !== undefined) {50+ subprocess.emit(errorSignal, error);51+ }52+};53+54+// Like `error` signal but internal to Execa.55+// E.g. does not make subprocess crash when no `error` listener is set.56+export const errorSignal = Symbol('error');57+58+const setKillTimeout = async ({kill, signal, forceKillAfterDelay, killSignal, killResult, controller}) => {59+ if (!shouldForceKill(signal, forceKillAfterDelay, killSignal, killResult)) {60+ return;61+ }62+63+ try {64+ await setTimeout(forceKillAfterDelay, undefined, {signal: controller.signal});65+ kill('SIGKILL');66+ } catch {}67+};68+69+const shouldForceKill = (signal, forceKillAfterDelay, killSignal, killResult) =>70+ normalizeSignal(signal) === normalizeSignal(killSignal)71+ && forceKillAfterDelay !== false72+ && killResult;73+74+const normalizeSignal = signal => typeof signal === 'string'75+ ? os.constants.signals[signal.toUpperCase()]76+ : signal;added:lib/terminate/timeout.js+20 added
1+import {setTimeout} from 'node:timers/promises';2+import {DiscardedError} from '../return/final-error.js';3+4+export const validateTimeout = ({timeout}) => {5+ if (timeout !== undefined && (!Number.isFinite(timeout) || timeout < 0)) {6+ throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`);7+ }8+};9+10+// `timeout` option handling11+export const throwOnTimeout = (subprocess, timeout, context, controller) => timeout === 0 || timeout === undefined12+ ? []13+ : [killAfterTimeout(subprocess, timeout, context, controller)];14+15+const killAfterTimeout = async (subprocess, timeout, context, {signal}) => {16+ await setTimeout(timeout, undefined, {signal});17+ context.timedOut = true;18+ subprocess.kill();19+ throw new DiscardedError();20+};added:lib/transform/encoding-transform.js+54 added
1+import {Buffer} from 'node:buffer';2+import {StringDecoder} from 'node:string_decoder';3+import {isUint8Array, bufferToUint8Array} from '../utils/uint-array.js';4+5+/*6+When using generators, add an internal generator that converts chunks from `Buffer` to `string` or `Uint8Array`.7+This allows generator functions to operate with those types instead.8+Chunks might be Buffer, Uint8Array or strings since:9+- `subprocess.stdout|stderr` emits Buffers10+- `subprocess.stdin.write()` accepts Buffer, Uint8Array or string11+- Previous generators might return Uint8Array or string12+13+However, those are converted to Buffer:14+- on writes: `Duplex.writable` `decodeStrings: true` default option15+- on reads: `Duplex.readable` `readableEncoding: null` default option16+*/17+export const getEncodingTransformGenerator = (binary, encoding, skipped) => {18+ if (skipped) {19+ return;20+ }21+22+ if (binary) {23+ return {transform: encodingUint8ArrayGenerator.bind(undefined, new TextEncoder())};24+ }25+26+ const stringDecoder = new StringDecoder(encoding);27+ return {28+ transform: encodingStringGenerator.bind(undefined, stringDecoder),29+ final: encodingStringFinal.bind(undefined, stringDecoder),30+ };31+};32+33+const encodingUint8ArrayGenerator = function * (textEncoder, chunk) {34+ if (Buffer.isBuffer(chunk)) {35+ yield bufferToUint8Array(chunk);36+ } else if (typeof chunk === 'string') {37+ yield textEncoder.encode(chunk);38+ } else {39+ yield chunk;40+ }41+};42+43+const encodingStringGenerator = function * (stringDecoder, chunk) {44+ yield Buffer.isBuffer(chunk) || isUint8Array(chunk)45+ ? stringDecoder.write(chunk)46+ : chunk;47+};48+49+const encodingStringFinal = function * (stringDecoder) {50+ const lastChunk = stringDecoder.end();51+ if (lastChunk !== '') {52+ yield lastChunk;53+ }54+};added:lib/transform/generator.js+90 added
1+import {Transform, getDefaultHighWaterMark} from 'node:stream';2+import {isAsyncGenerator} from '../stdio/type.js';3+import {getSplitLinesGenerator, getAppendNewlineGenerator} from './split.js';4+import {getValidateTransformInput, getValidateTransformReturn} from './validate.js';5+import {getEncodingTransformGenerator} from './encoding-transform.js';6+import {pushChunks, transformChunk, finalChunks, destroyTransform} from './run-async.js';7+import {pushChunksSync, transformChunkSync, finalChunksSync, runTransformSync} from './run-sync.js';8+9+/*10+Generators can be used to transform/filter standard streams.11+12+Generators have a simple syntax, yet allows all of the following:13+- Sharing `state` between chunks14+- Flushing logic, by using a `final` function15+- Asynchronous logic16+- Emitting multiple chunks from a single source chunk, even if spaced in time, by using multiple `yield`17+- Filtering, by using no `yield`18+19+Therefore, there is no need to allow Node.js or web transform streams.20+21+The `highWaterMark` is kept as the default value, since this is what `subprocess.std*` uses.22+23+Chunks are currently processed serially. We could add a `concurrency` option to parallelize in the future.24+25+Transform an array of generator functions into a `Transform` stream.26+`Duplex.from(generator)` cannot be used because it does not allow setting the `objectMode` and `highWaterMark`.27+*/28+export const generatorToStream = ({29+ value,30+ value: {transform, final, writableObjectMode, readableObjectMode},31+ optionName,32+}, {encoding}) => {33+ const state = {};34+ const generators = addInternalGenerators(value, encoding, optionName);35+36+ const transformAsync = isAsyncGenerator(transform);37+ const finalAsync = isAsyncGenerator(final);38+ const transformMethod = transformAsync39+ ? pushChunks.bind(undefined, transformChunk, state)40+ : pushChunksSync.bind(undefined, transformChunkSync);41+ const finalMethod = transformAsync || finalAsync42+ ? pushChunks.bind(undefined, finalChunks, state)43+ : pushChunksSync.bind(undefined, finalChunksSync);44+ const destroyMethod = transformAsync || finalAsync45+ ? destroyTransform.bind(undefined, state)46+ : undefined;47+48+ const stream = new Transform({49+ writableObjectMode,50+ writableHighWaterMark: getDefaultHighWaterMark(writableObjectMode),51+ readableObjectMode,52+ readableHighWaterMark: getDefaultHighWaterMark(readableObjectMode),53+ transform(chunk, encoding, done) {54+ transformMethod([chunk, generators, 0], this, done);55+ },56+ flush(done) {57+ finalMethod([generators], this, done);58+ },59+ destroy: destroyMethod,60+ });61+ return {stream};62+};63+64+export const runGeneratorsSync = (chunks, stdioItems, encoding, isInput) => {65+ const generators = stdioItems.filter(({type}) => type === 'generator');66+ const reversedGenerators = isInput ? generators.reverse() : generators;67+68+ for (const {value, optionName} of reversedGenerators) {69+ const generators = addInternalGenerators(value, encoding, optionName);70+ chunks = runTransformSync(generators, chunks);71+ }72+73+ return chunks;74+};75+76+const addInternalGenerators = (77+ {transform, final, binary, writableObjectMode, readableObjectMode, preserveNewlines},78+ encoding,79+ optionName,80+) => {81+ const state = {};82+ return [83+ {transform: getValidateTransformInput(writableObjectMode, optionName)},84+ getEncodingTransformGenerator(binary, encoding, writableObjectMode),85+ getSplitLinesGenerator(binary, preserveNewlines, writableObjectMode, state),86+ {transform, final},87+ {transform: getValidateTransformReturn(readableObjectMode, optionName)},88+ getAppendNewlineGenerator({binary, preserveNewlines, readableObjectMode, state}),89+ ].filter(Boolean);90+};added:lib/transform/normalize.js+83 added
1+import isPlainObj from 'is-plain-obj';2+import {BINARY_ENCODINGS} from '../arguments/encoding-option.js';3+import {TRANSFORM_TYPES} from '../stdio/type.js';4+import {getTransformObjectModes} from './object-mode.js';5+6+// Transforms generators/duplex/TransformStream can have multiple shapes.7+// This normalizes it and applies default values.8+export const normalizeTransforms = (stdioItems, optionName, direction, options) => [9+ ...stdioItems.filter(({type}) => !TRANSFORM_TYPES.has(type)),10+ ...getTransforms(stdioItems, optionName, direction, options),11+];12+13+const getTransforms = (stdioItems, optionName, direction, {encoding}) => {14+ const transforms = stdioItems.filter(({type}) => TRANSFORM_TYPES.has(type));15+ const newTransforms = Array.from({length: transforms.length});16+17+ for (const [index, stdioItem] of Object.entries(transforms)) {18+ newTransforms[index] = normalizeTransform({stdioItem, index: Number(index), newTransforms, optionName, direction, encoding});19+ }20+21+ return sortTransforms(newTransforms, direction);22+};23+24+const normalizeTransform = ({stdioItem, stdioItem: {type}, index, newTransforms, optionName, direction, encoding}) => {25+ if (type === 'duplex') {26+ return normalizeDuplex({stdioItem, optionName});27+ }28+29+ if (type === 'webTransform') {30+ return normalizeTransformStream({stdioItem, index, newTransforms, direction});31+ }32+33+ return normalizeGenerator({stdioItem, index, newTransforms, direction, encoding});34+};35+36+const normalizeDuplex = ({37+ stdioItem,38+ stdioItem: {39+ value: {40+ transform,41+ transform: {writableObjectMode, readableObjectMode},42+ objectMode = readableObjectMode,43+ },44+ },45+ optionName,46+}) => {47+ if (objectMode && !readableObjectMode) {48+ throw new TypeError(`The \`${optionName}.objectMode\` option can only be \`true\` if \`new Duplex({objectMode: true})\` is used.`);49+ }50+51+ if (!objectMode && readableObjectMode) {52+ throw new TypeError(`The \`${optionName}.objectMode\` option cannot be \`false\` if \`new Duplex({objectMode: true})\` is used.`);53+ }54+55+ return {56+ ...stdioItem,57+ value: {transform, writableObjectMode, readableObjectMode},58+ };59+};60+61+const normalizeTransformStream = ({stdioItem, stdioItem: {value}, index, newTransforms, direction}) => {62+ const {transform, objectMode} = isPlainObj(value) ? value : {transform: value};63+ const {writableObjectMode, readableObjectMode} = getTransformObjectModes(objectMode, index, newTransforms, direction);64+ return ({65+ ...stdioItem,66+ value: {transform, writableObjectMode, readableObjectMode},67+ });68+};69+70+const normalizeGenerator = ({stdioItem, stdioItem: {value}, index, newTransforms, direction, encoding}) => {71+ const {72+ transform,73+ final,74+ binary: binaryOption = false,75+ preserveNewlines = false,76+ objectMode,77+ } = isPlainObj(value) ? value : {transform: value};78+ const binary = binaryOption || BINARY_ENCODINGS.has(encoding);79+ const {writableObjectMode, readableObjectMode} = getTransformObjectModes(objectMode, index, newTransforms, direction);80+ return {...stdioItem, value: {transform, final, binary, preserveNewlines, writableObjectMode, readableObjectMode}};81+};82+83+const sortTransforms = (newTransforms, direction) => direction === 'input' ? newTransforms.reverse() : newTransforms;added:lib/transform/object-mode.js+41 added
1+import {TRANSFORM_TYPES} from '../stdio/type.js';2+3+/*4+Retrieve the `objectMode`s of a single transform.5+`objectMode` determines the return value's type, i.e. the `readableObjectMode`.6+The chunk argument's type is based on the previous generator's return value, i.e. the `writableObjectMode` is based on the previous `readableObjectMode`.7+The last input's generator is read by `subprocess.stdin` which:8+- should not be in `objectMode` for performance reasons.9+- can only be strings, Buffers and Uint8Arrays.10+Therefore its `readableObjectMode` must be `false`.11+The same applies to the first output's generator's `writableObjectMode`.12+*/13+export const getTransformObjectModes = (objectMode, index, newTransforms, direction) => direction === 'output'14+ ? getOutputObjectModes(objectMode, index, newTransforms)15+ : getInputObjectModes(objectMode, index, newTransforms);16+17+const getOutputObjectModes = (objectMode, index, newTransforms) => {18+ const writableObjectMode = index !== 0 && newTransforms[index - 1].value.readableObjectMode;19+ const readableObjectMode = objectMode ?? writableObjectMode;20+ return {writableObjectMode, readableObjectMode};21+};22+23+const getInputObjectModes = (objectMode, index, newTransforms) => {24+ const writableObjectMode = index === 025+ ? objectMode === true26+ : newTransforms[index - 1].value.readableObjectMode;27+ const readableObjectMode = index !== newTransforms.length - 1 && (objectMode ?? writableObjectMode);28+ return {writableObjectMode, readableObjectMode};29+};30+31+// Retrieve the `objectMode` of a file descriptor, e.g. `stdout` or `stderr`32+export const getFdObjectMode = (stdioItems, direction) => {33+ const lastTransform = stdioItems.findLast(({type}) => TRANSFORM_TYPES.has(type));34+ if (lastTransform === undefined) {35+ return false;36+ }37+38+ return direction === 'input'39+ ? lastTransform.value.writableObjectMode40+ : lastTransform.value.readableObjectMode;41+};added:lib/transform/run-async.js+59 added
1+import {callbackify} from 'node:util';2+3+export const pushChunks = callbackify(async (getChunks, state, args, transformStream) => {4+ state.currentIterable = getChunks(...args);5+6+ try {7+ for await (const chunk of state.currentIterable) {8+ transformStream.push(chunk);9+ }10+ } finally {11+ delete state.currentIterable;12+ }13+});14+15+// For each new chunk, apply each `transform()` method16+export const transformChunk = async function * (chunk, generators, index) {17+ if (index === generators.length) {18+ yield chunk;19+ return;20+ }21+22+ const {transform = identityGenerator} = generators[index];23+ for await (const transformedChunk of transform(chunk)) {24+ yield * transformChunk(transformedChunk, generators, index + 1);25+ }26+};27+28+// At the end, apply each `final()` method, followed by the `transform()` method of the next transforms29+export const finalChunks = async function * (generators) {30+ for (const [index, {final}] of Object.entries(generators)) {31+ yield * generatorFinalChunks(final, Number(index), generators);32+ }33+};34+35+const generatorFinalChunks = async function * (final, index, generators) {36+ if (final === undefined) {37+ return;38+ }39+40+ for await (const finalChunk of final()) {41+ yield * transformChunk(finalChunk, generators, index + 1);42+ }43+};44+45+// Cancel any ongoing async generator when the Transform is destroyed, e.g. when the subprocess errors46+export const destroyTransform = callbackify(async ({currentIterable}, error) => {47+ if (currentIterable !== undefined) {48+ await (error ? currentIterable.throw(error) : currentIterable.return());49+ return;50+ }51+52+ if (error) {53+ throw error;54+ }55+});56+57+const identityGenerator = function * (chunk) {58+ yield chunk;59+};added:lib/transform/run-sync.js+50 added
1+// Duplicate the code from `transform-async.js` but as synchronous functions2+export const pushChunksSync = (getChunksSync, args, transformStream, done) => {3+ try {4+ for (const chunk of getChunksSync(...args)) {5+ transformStream.push(chunk);6+ }7+8+ done();9+ } catch (error) {10+ done(error);11+ }12+};13+14+// Run synchronous generators with `execaSync()`15+export const runTransformSync = (generators, chunks) => [16+ ...chunks.flatMap(chunk => [...transformChunkSync(chunk, generators, 0)]),17+ ...finalChunksSync(generators),18+];19+20+export const transformChunkSync = function * (chunk, generators, index) {21+ if (index === generators.length) {22+ yield chunk;23+ return;24+ }25+26+ const {transform = identityGenerator} = generators[index];27+ for (const transformedChunk of transform(chunk)) {28+ yield * transformChunkSync(transformedChunk, generators, index + 1);29+ }30+};31+32+export const finalChunksSync = function * (generators) {33+ for (const [index, {final}] of Object.entries(generators)) {34+ yield * generatorFinalChunksSync(final, Number(index), generators);35+ }36+};37+38+const generatorFinalChunksSync = function * (final, index, generators) {39+ if (final === undefined) {40+ return;41+ }42+43+ for (const finalChunk of final()) {44+ yield * transformChunkSync(finalChunk, generators, index + 1);45+ }46+};47+48+const identityGenerator = function * (chunk) {49+ yield chunk;50+};added:lib/transform/split.js+109 added
1+// Split chunks line-wise for generators passed to the `std*` options2+export const getSplitLinesGenerator = (binary, preserveNewlines, skipped, state) => binary || skipped3+ ? undefined4+ : initializeSplitLines(preserveNewlines, state);5+6+export const splitLinesSync = (chunk, preserveNewlines, objectMode) => objectMode7+ ? chunk.flatMap(item => splitLinesItemSync(item, preserveNewlines))8+ : splitLinesItemSync(chunk, preserveNewlines);9+10+const splitLinesItemSync = (chunk, preserveNewlines) => {11+ const {transform, final} = initializeSplitLines(preserveNewlines, {});12+ return [...transform(chunk), ...final()];13+};14+15+const initializeSplitLines = (preserveNewlines, state) => {16+ state.previousChunks = '';17+ return {18+ transform: splitGenerator.bind(undefined, state, preserveNewlines),19+ final: linesFinal.bind(undefined, state),20+ };21+};22+23+// This imperative logic is much faster than using `String.split()` and uses very low memory.24+const splitGenerator = function * (state, preserveNewlines, chunk) {25+ if (typeof chunk !== 'string') {26+ yield chunk;27+ return;28+ }29+30+ let {previousChunks} = state;31+ let start = -1;32+33+ for (let end = 0; end < chunk.length; end += 1) {34+ if (chunk[end] === '\n') {35+ const newlineLength = getNewlineLength(chunk, end, preserveNewlines, state);36+ let line = chunk.slice(start + 1, end + 1 - newlineLength);37+38+ if (previousChunks.length > 0) {39+ line = concatString(previousChunks, line);40+ previousChunks = '';41+ }42+43+ yield line;44+ start = end;45+ }46+ }47+48+ if (start !== chunk.length - 1) {49+ previousChunks = concatString(previousChunks, chunk.slice(start + 1));50+ }51+52+ state.previousChunks = previousChunks;53+};54+55+const getNewlineLength = (chunk, end, preserveNewlines, state) => {56+ if (preserveNewlines) {57+ return 0;58+ }59+60+ state.isWindowsNewline = end !== 0 && chunk[end - 1] === '\r';61+ return state.isWindowsNewline ? 2 : 1;62+};63+64+const linesFinal = function * ({previousChunks}) {65+ if (previousChunks.length > 0) {66+ yield previousChunks;67+ }68+};69+70+// Unless `preserveNewlines: true` is used, we strip the newline of each line.71+// This re-adds them after the user `transform` code has run.72+export const getAppendNewlineGenerator = ({binary, preserveNewlines, readableObjectMode, state}) => binary || preserveNewlines || readableObjectMode73+ ? undefined74+ : {transform: appendNewlineGenerator.bind(undefined, state)};75+76+const appendNewlineGenerator = function * ({isWindowsNewline = false}, chunk) {77+ const {unixNewline, windowsNewline, LF, concatBytes} = typeof chunk === 'string' ? linesStringInfo : linesUint8ArrayInfo;78+79+ if (chunk.at(-1) === LF) {80+ yield chunk;81+ return;82+ }83+84+ const newline = isWindowsNewline ? windowsNewline : unixNewline;85+ yield concatBytes(chunk, newline);86+};87+88+const concatString = (firstChunk, secondChunk) => `${firstChunk}${secondChunk}`;89+90+const linesStringInfo = {91+ windowsNewline: '\r\n',92+ unixNewline: '\n',93+ LF: '\n',94+ concatBytes: concatString,95+};96+97+const concatUint8Array = (firstChunk, secondChunk) => {98+ const chunk = new Uint8Array(firstChunk.length + secondChunk.length);99+ chunk.set(firstChunk, 0);100+ chunk.set(secondChunk, firstChunk.length);101+ return chunk;102+};103+104+const linesUint8ArrayInfo = {105+ windowsNewline: new Uint8Array([0x0D, 0x0A]),106+ unixNewline: new Uint8Array([0x0A]),107+ LF: 0x0A,108+ concatBytes: concatUint8Array,109+};added:lib/transform/validate.js+42 added
1+import {Buffer} from 'node:buffer';2+import {isUint8Array} from '../utils/uint-array.js';3+4+export const getValidateTransformInput = (writableObjectMode, optionName) => writableObjectMode5+ ? undefined6+ : validateStringTransformInput.bind(undefined, optionName);7+8+const validateStringTransformInput = function * (optionName, chunk) {9+ if (typeof chunk !== 'string' && !isUint8Array(chunk) && !Buffer.isBuffer(chunk)) {10+ throw new TypeError(`The \`${optionName}\` option's transform must use "objectMode: true" to receive as input: ${typeof chunk}.`);11+ }12+13+ yield chunk;14+};15+16+export const getValidateTransformReturn = (readableObjectMode, optionName) => readableObjectMode17+ ? validateObjectTransformReturn.bind(undefined, optionName)18+ : validateStringTransformReturn.bind(undefined, optionName);19+20+const validateObjectTransformReturn = function * (optionName, chunk) {21+ validateEmptyReturn(optionName, chunk);22+ yield chunk;23+};24+25+const validateStringTransformReturn = function * (optionName, chunk) {26+ validateEmptyReturn(optionName, chunk);27+28+ if (typeof chunk !== 'string' && !isUint8Array(chunk)) {29+ const typeName = Buffer.isBuffer(chunk) ? 'a buffer' : typeof chunk;30+ throw new TypeError(`The \`${optionName}\` option's function must yield a string or an Uint8Array, not ${typeName}.`);31+ }32+33+ yield chunk;34+};35+36+const validateEmptyReturn = (optionName, chunk) => {37+ if (chunk === null || chunk === undefined) {38+ throw new TypeError(`The \`${optionName}\` option's function must not call \`yield ${chunk}\`.39+Instead, \`yield\` should either be called with a value, or not be called at all. For example:40+ if (condition) { yield value; }`);41+ }42+};added:lib/utils/max-listeners.js+13 added
1+import {addAbortListener} from 'node:events';2+3+export const incrementMaxListeners = (eventEmitter, maxListenersIncrement, signal) => {4+ const maxListeners = eventEmitter.getMaxListeners();5+ if (maxListeners === 0 || maxListeners === Number.POSITIVE_INFINITY) {6+ return;7+ }8+9+ eventEmitter.setMaxListeners(maxListeners + maxListenersIncrement);10+ addAbortListener(signal, () => {11+ eventEmitter.setMaxListeners(eventEmitter.getMaxListeners() - maxListenersIncrement);12+ });13+};added:lib/utils/standard-stream.js+6 added
1+import process from 'node:process';2+3+export const isStandardStream = stream => STANDARD_STREAMS.includes(stream);4+export const STANDARD_STREAMS = [process.stdin, process.stdout, process.stderr];5+export const STANDARD_STREAMS_ALIASES = ['stdin', 'stdout', 'stderr'];6+export const getStreamName = fdNumber => STANDARD_STREAMS_ALIASES[fdNumber] ?? `stdio[${fdNumber}]`;added:lib/utils/uint-array.js+69 added
1+import {Buffer} from 'node:buffer';2+import {StringDecoder} from 'node:string_decoder';3+4+const {toString: objectToString} = Object.prototype;5+6+export const isArrayBuffer = value => objectToString.call(value) === '[object ArrayBuffer]';7+8+export const isUint8Array = value => objectToString.call(value) === '[object Uint8Array]' && !Buffer.isBuffer(value);9+10+export const bufferToUint8Array = buffer => new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);11+12+const textEncoder = new TextEncoder();13+const stringToUint8Array = string => textEncoder.encode(string);14+15+const textDecoder = new TextDecoder();16+export const uint8ArrayToString = uint8Array => textDecoder.decode(uint8Array);17+18+export const joinToString = (uint8ArraysOrStrings, encoding) => {19+ const strings = uint8ArraysToStrings(uint8ArraysOrStrings, encoding);20+ return strings.join('');21+};22+23+const uint8ArraysToStrings = (uint8ArraysOrStrings, encoding) => {24+ if (encoding === 'utf8' && uint8ArraysOrStrings.every(uint8ArrayOrString => typeof uint8ArrayOrString === 'string')) {25+ return uint8ArraysOrStrings;26+ }27+28+ const decoder = new StringDecoder(encoding);29+ const strings = uint8ArraysOrStrings30+ .map(uint8ArrayOrString => typeof uint8ArrayOrString === 'string'31+ ? stringToUint8Array(uint8ArrayOrString)32+ : uint8ArrayOrString)33+ .map(uint8Array => decoder.write(uint8Array));34+ const finalString = decoder.end();35+ return finalString === '' ? strings : [...strings, finalString];36+};37+38+export const joinToUint8Array = uint8ArraysOrStrings => {39+ if (uint8ArraysOrStrings.length === 1 && isUint8Array(uint8ArraysOrStrings[0])) {40+ return uint8ArraysOrStrings[0];41+ }42+43+ return concatUint8Arrays(stringsToUint8Arrays(uint8ArraysOrStrings));44+};45+46+const stringsToUint8Arrays = uint8ArraysOrStrings => uint8ArraysOrStrings.map(uint8ArrayOrString => typeof uint8ArrayOrString === 'string'47+ ? stringToUint8Array(uint8ArrayOrString)48+ : uint8ArrayOrString);49+50+export const concatUint8Arrays = uint8Arrays => {51+ const result = new Uint8Array(getJoinLength(uint8Arrays));52+53+ let index = 0;54+ for (const uint8Array of uint8Arrays) {55+ result.set(uint8Array, index);56+ index += uint8Array.length;57+ }58+59+ return result;60+};61+62+const getJoinLength = uint8Arrays => {63+ let joinLength = 0;64+ for (const uint8Array of uint8Arrays) {65+ joinLength += uint8Array.length;66+ }67+68+ return joinLength;69+};modified:lib/verbose/output.js+1 added-1 removed
1 import {inspect} from 'node:util';2 import {escapeLines} from '../arguments/escape.js';3-import {BINARY_ENCODINGS} from '../arguments/encoding.js';3+import {BINARY_ENCODINGS} from '../arguments/encoding-option.js';4 import {TRANSFORM_TYPES} from '../stdio/type.js';5 import {verboseLog} from './log.js';6 7 // `ignore` opts-out of `verbose` for a specific stream.52 unmodified linesdeleted:lib/async.js-110 removed
1-import {setMaxListeners} from 'node:events';2-import {spawn} from 'node:child_process';3-import {MaxBufferError} from 'get-stream';4-import {handleCommand} from './arguments/command.js';5-import {handleOptions} from './arguments/options.js';6-import {makeError, makeSuccessResult} from './return/error.js';7-import {stripNewline} from './return/strip-newline.js';8-import {handleResult} from './return/reject.js';9-import {handleEarlyError} from './return/early-error.js';10-import {handleInputAsync} from './stdio/async.js';11-import {pipeOutputAsync} from './stdio/output-async.js';12-import {subprocessKill} from './exit/kill.js';13-import {cleanupOnExit} from './exit/cleanup.js';14-import {pipeToSubprocess} from './pipe/setup.js';15-import {SUBPROCESS_OPTIONS} from './convert/fd-options.js';16-import {logEarlyResult} from './verbose/complete.js';17-import {makeAllStream} from './stream/all.js';18-import {addConvertedStreams} from './convert/add.js';19-import {getSubprocessResult} from './stream/resolve.js';20-import {mergePromise} from './promise.js';21-22-export const execaCoreAsync = (rawFile, rawArgs, rawOptions, createNested) => {23- const {file, args, command, escapedCommand, startTime, verboseInfo, options, fileDescriptors} = handleAsyncArguments(rawFile, rawArgs, rawOptions);24- const {subprocess, promise} = spawnSubprocessAsync({file, args, options, startTime, verboseInfo, command, escapedCommand, fileDescriptors});25- subprocess.pipe = pipeToSubprocess.bind(undefined, {source: subprocess, sourcePromise: promise, boundOptions: {}, createNested});26- mergePromise(subprocess, promise);27- SUBPROCESS_OPTIONS.set(subprocess, {options, fileDescriptors});28- return subprocess;29-};30-31-const handleAsyncArguments = (rawFile, rawArgs, rawOptions) => {32- const {command, escapedCommand, startTime, verboseInfo} = handleCommand(rawFile, rawArgs, rawOptions);33-34- try {35- const {file, args, options: normalizedOptions} = handleOptions(rawFile, rawArgs, rawOptions);36- const options = handleAsyncOptions(normalizedOptions);37- const fileDescriptors = handleInputAsync(options, verboseInfo);38- return {file, args, command, escapedCommand, startTime, verboseInfo, options, fileDescriptors};39- } catch (error) {40- logEarlyResult(error, startTime, verboseInfo);41- throw error;42- }43-};44-45-// Prevent passing the `timeout` option directly to `child_process.spawn()`46-const handleAsyncOptions = ({timeout, signal, cancelSignal, ...options}) => {47- if (signal !== undefined) {48- throw new TypeError('The "signal" option has been renamed to "cancelSignal" instead.');49- }50-51- return {...options, timeoutDuration: timeout, signal: cancelSignal};52-};53-54-const spawnSubprocessAsync = ({file, args, options, startTime, verboseInfo, command, escapedCommand, fileDescriptors}) => {55- let subprocess;56- try {57- subprocess = spawn(file, args, options);58- } catch (error) {59- return handleEarlyError({error, command, escapedCommand, fileDescriptors, options, startTime, verboseInfo});60- }61-62- const controller = new AbortController();63- setMaxListeners(Number.POSITIVE_INFINITY, controller.signal);64-65- const originalStreams = [...subprocess.stdio];66- pipeOutputAsync(subprocess, fileDescriptors, controller);67- cleanupOnExit(subprocess, options, controller);68-69- subprocess.kill = subprocessKill.bind(undefined, {kill: subprocess.kill.bind(subprocess), subprocess, options, controller});70- subprocess.all = makeAllStream(subprocess, options);71- addConvertedStreams(subprocess, options);72-73- const promise = handlePromise({subprocess, options, startTime, verboseInfo, fileDescriptors, originalStreams, command, escapedCommand, controller});74- return {subprocess, promise};75-};76-77-const handlePromise = async ({subprocess, options, startTime, verboseInfo, fileDescriptors, originalStreams, command, escapedCommand, controller}) => {78- const context = {timedOut: false};79-80- const [81- errorInfo,82- [exitCode, signal],83- stdioResults,84- allResult,85- ] = await getSubprocessResult({subprocess, options, context, verboseInfo, fileDescriptors, originalStreams, controller});86- controller.abort();87-88- const stdio = stdioResults.map((stdioResult, fdNumber) => stripNewline(stdioResult, options, fdNumber));89- const all = stripNewline(allResult, options, 'all');90- const result = getAsyncResult({errorInfo, exitCode, signal, stdio, all, context, options, command, escapedCommand, startTime});91- return handleResult(result, verboseInfo, options);92-};93-94-const getAsyncResult = ({errorInfo, exitCode, signal, stdio, all, context, options, command, escapedCommand, startTime}) => 'error' in errorInfo95- ? makeError({96- error: errorInfo.error,97- command,98- escapedCommand,99- timedOut: context.timedOut,100- isCanceled: options.signal?.aborted === true,101- isMaxBuffer: errorInfo.error instanceof MaxBufferError,102- exitCode,103- signal,104- stdio,105- all,106- options,107- startTime,108- isSync: false,109- })110- : makeSuccessResult({command, escapedCommand, stdio, all, options, startTime});deleted:lib/command.js-25 removed
1-export const mapCommandAsync = ({file, args}) => parseCommand(file, args);2-export const mapCommandSync = ({file, args}) => ({...parseCommand(file, args), isSync: true});3-4-const parseCommand = (command, unusedArgs) => {5- if (unusedArgs.length > 0) {6- throw new TypeError(`The command and its arguments must be passed as a single string: ${command} ${unusedArgs}.`);7- }8-9- const tokens = [];10- for (const token of command.trim().split(SPACES_REGEXP)) {11- // Allow spaces to be escaped by a backslash if not meant as a delimiter12- const previousToken = tokens.at(-1);13- if (previousToken && previousToken.endsWith('\\')) {14- // Merge previous token with current one15- tokens[tokens.length - 1] = `${previousToken.slice(0, -1)} ${token}`;16- } else {17- tokens.push(token);18- }19- }20-21- const [file, ...args] = tokens;22- return {file, args};23-};24-25-const SPACES_REGEXP = / +/g;deleted:lib/max-listener.js-13 removed
1-import {addAbortListener} from 'node:events';2-3-export const incrementMaxListeners = (eventEmitter, maxListenersIncrement, signal) => {4- const maxListeners = eventEmitter.getMaxListeners();5- if (maxListeners === 0 || maxListeners === Number.POSITIVE_INFINITY) {6- return;7- }8-9- eventEmitter.setMaxListeners(maxListeners + maxListenersIncrement);10- addAbortListener(signal, () => {11- eventEmitter.setMaxListeners(eventEmitter.getMaxListeners() - maxListenersIncrement);12- });13-};deleted:lib/promise.js-15 removed
1-// The return value is a mixin of `subprocess` and `Promise`2-export const mergePromise = (subprocess, promise) => {3- for (const [property, descriptor] of descriptors) {4- const value = descriptor.value.bind(promise);5- Reflect.defineProperty(subprocess, property, {...descriptor, value});6- }7-};8-9-// eslint-disable-next-line unicorn/prefer-top-level-await10-const nativePromisePrototype = (async () => {})().constructor.prototype;11-12-const descriptors = ['then', 'catch', 'finally'].map(property => [13- property,14- Reflect.getOwnPropertyDescriptor(nativePromisePrototype, property),15-]);deleted:lib/script.js-15 removed
1-export const setScriptSync = (boundExeca, createNested, boundOptions) => {2- boundExeca.sync = createNested(mapScriptSync, boundOptions);3- boundExeca.s = boundExeca.sync;4-};5-6-export const mapScriptAsync = ({options}) => getScriptOptions(options);7-const mapScriptSync = ({options}) => ({...getScriptOptions(options), isSync: true});8-9-const getScriptOptions = options => ({options: {...getScriptStdinOption(options), ...options}});10-11-const getScriptStdinOption = ({input, inputFile, stdio}) => input === undefined && inputFile === undefined && stdio === undefined12- ? {stdin: 'inherit'}13- : {};14-15-export const deepScriptOptions = {preferLocal: true};deleted:lib/sync.js-97 removed
1-import {spawnSync} from 'node:child_process';2-import {handleCommand} from './arguments/command.js';3-import {handleOptions} from './arguments/options.js';4-import {makeError, makeEarlyError, makeSuccessResult} from './return/error.js';5-import {stripNewline} from './return/strip-newline.js';6-import {handleResult} from './return/reject.js';7-import {handleInputSync} from './stdio/sync.js';8-import {addInputOptionsSync} from './stdio/input-sync.js';9-import {transformOutputSync} from './stdio/output-sync.js';10-import {getAllSync} from './stdio/all-sync.js';11-import {logEarlyResult} from './verbose/complete.js';12-import {getExitResultSync} from './stream/exit-sync.js';13-import {getMaxBufferSync} from './stream/max-buffer.js';14-15-export const execaCoreSync = (rawFile, rawArgs, rawOptions) => {16- const {file, args, command, escapedCommand, startTime, verboseInfo, options, fileDescriptors} = handleSyncArguments(rawFile, rawArgs, rawOptions);17- const result = spawnSubprocessSync({file, args, options, command, escapedCommand, verboseInfo, fileDescriptors, startTime});18- return handleResult(result, verboseInfo, options);19-};20-21-const handleSyncArguments = (rawFile, rawArgs, rawOptions) => {22- const {command, escapedCommand, startTime, verboseInfo} = handleCommand(rawFile, rawArgs, rawOptions);23-24- try {25- const syncOptions = normalizeSyncOptions(rawOptions);26- const {file, args, options} = handleOptions(rawFile, rawArgs, syncOptions);27- validateSyncOptions(options);28- const fileDescriptors = handleInputSync(options, verboseInfo);29- return {file, args, command, escapedCommand, startTime, verboseInfo, options, fileDescriptors};30- } catch (error) {31- logEarlyResult(error, startTime, verboseInfo);32- throw error;33- }34-};35-36-const normalizeSyncOptions = options => options.node && !options.ipc ? {...options, ipc: false} : options;37-38-const validateSyncOptions = ({ipc, detached, cancelSignal}) => {39- if (ipc) {40- throwInvalidSyncOption('ipc: true');41- }42-43- if (detached) {44- throwInvalidSyncOption('detached: true');45- }46-47- if (cancelSignal) {48- throwInvalidSyncOption('cancelSignal');49- }50-};51-52-const throwInvalidSyncOption = value => {53- throw new TypeError(`The "${value}" option cannot be used with synchronous methods.`);54-};55-56-const spawnSubprocessSync = ({file, args, options, command, escapedCommand, verboseInfo, fileDescriptors, startTime}) => {57- const syncResult = runSubprocessSync({file, args, options, command, escapedCommand, fileDescriptors, startTime});58- if (syncResult.failed) {59- return syncResult;60- }61-62- const {resultError, exitCode, signal, timedOut, isMaxBuffer} = getExitResultSync(syncResult, options);63- const {output, error = resultError} = transformOutputSync({fileDescriptors, syncResult, options, isMaxBuffer, verboseInfo});64- const stdio = output.map((stdioOutput, fdNumber) => stripNewline(stdioOutput, options, fdNumber));65- const all = stripNewline(getAllSync(output, options), options, 'all');66- return getSyncResult({error, exitCode, signal, timedOut, isMaxBuffer, stdio, all, options, command, escapedCommand, startTime});67-};68-69-const runSubprocessSync = ({file, args, options, command, escapedCommand, fileDescriptors, startTime}) => {70- try {71- addInputOptionsSync(fileDescriptors, options);72- const normalizedOptions = normalizeSpawnSyncOptions(options);73- return spawnSync(file, args, normalizedOptions);74- } catch (error) {75- return makeEarlyError({error, command, escapedCommand, fileDescriptors, options, startTime, isSync: true});76- }77-};78-79-const normalizeSpawnSyncOptions = ({encoding, maxBuffer, ...options}) => ({...options, encoding: 'buffer', maxBuffer: getMaxBufferSync(maxBuffer)});80-81-const getSyncResult = ({error, exitCode, signal, timedOut, isMaxBuffer, stdio, all, options, command, escapedCommand, startTime}) => error === undefined82- ? makeSuccessResult({command, escapedCommand, stdio, all, options, startTime})83- : makeError({84- error,85- command,86- escapedCommand,87- timedOut,88- isCanceled: false,89- isMaxBuffer,90- exitCode,91- signal,92- stdio,93- all,94- options,95- startTime,96- isSync: true,97- });deleted:lib/utils.js-6 removed
1-import process from 'node:process';2-3-export const isStandardStream = stream => STANDARD_STREAMS.includes(stream);4-export const STANDARD_STREAMS = [process.stdin, process.stdout, process.stderr];5-export const STANDARD_STREAMS_ALIASES = ['stdin', 'stdout', 'stderr'];6-export const getStreamName = fdNumber => STANDARD_STREAMS_ALIASES[fdNumber] ?? `stdio[${fdNumber}]`;deleted:test/arguments/create-bind.js-104 removed
1-import {join} from 'node:path';2-import test from 'ava';3-import {execa, execaSync, execaNode, $} from '../../index.js';4-import {foobarString, foobarUppercase} from '../helpers/input.js';5-import {uppercaseGenerator} from '../helpers/generator.js';6-import {setFixtureDir, FIXTURES_DIR} from '../helpers/fixtures-dir.js';7-8-setFixtureDir();9-10-const NOOP_PATH = join(FIXTURES_DIR, 'noop.js');11-const PRINT_ENV_PATH = join(FIXTURES_DIR, 'environment.js');12-13-const testBindOptions = async (t, execaMethod) => {14- const {stdout} = await execaMethod({stripFinalNewline: false})(NOOP_PATH, [foobarString]);15- t.is(stdout, `${foobarString}\n`);16-};17-18-test('execa() can bind options', testBindOptions, execa);19-test('execaNode() can bind options', testBindOptions, execaNode);20-test('$ can bind options', testBindOptions, $);21-22-const testBindOptionsSync = (t, execaMethod) => {23- const {stdout} = execaMethod({stripFinalNewline: false})(NOOP_PATH, [foobarString]);24- t.is(stdout, `${foobarString}\n`);25-};26-27-test('execaSync() can bind options', testBindOptionsSync, execaSync);28-test('$.sync can bind options', testBindOptionsSync, $.sync);29-30-const testBindPriority = async (t, execaMethod) => {31- const {stdout} = await execaMethod({stripFinalNewline: false})(NOOP_PATH, [foobarString], {stripFinalNewline: true});32- t.is(stdout, foobarString);33-};34-35-test('execa() bound options have lower priority', testBindPriority, execa);36-test('execaSync() bound options have lower priority', testBindPriority, execaSync);37-test('execaNode() bound options have lower priority', testBindPriority, execaNode);38-test('$ bound options have lower priority', testBindPriority, $);39-test('$.sync bound options have lower priority', testBindPriority, $.sync);40-41-const testBindUndefined = async (t, execaMethod) => {42- const {stdout} = await execaMethod({stripFinalNewline: false})(NOOP_PATH, [foobarString], {stripFinalNewline: undefined});43- t.is(stdout, foobarString);44-};45-46-test('execa() undefined options use default value', testBindUndefined, execa);47-test('execaSync() undefined options use default value', testBindUndefined, execaSync);48-test('execaNode() undefined options use default value', testBindUndefined, execaNode);49-test('$ undefined options use default value', testBindUndefined, $);50-test('$.sync undefined options use default value', testBindUndefined, $.sync);51-52-const testMergeEnv = async (t, execaMethod) => {53- const {stdout} = await execaMethod({env: {FOO: 'foo'}})(PRINT_ENV_PATH, {env: {BAR: 'bar'}});54- t.is(stdout, 'foo\nbar');55-};56-57-test('execa() bound options are merged', testMergeEnv, execa);58-test('execaSync() bound options are merged', testMergeEnv, execaSync);59-test('execaNode() bound options are merged', testMergeEnv, execaNode);60-test('$ bound options are merged', testMergeEnv, $);61-test('$.sync bound options are merged', testMergeEnv, $.sync);62-63-const testMergeMultiple = async (t, execaMethod) => {64- const {stdout} = await execaMethod({env: {FOO: 'baz'}})({env: {BAR: 'bar'}})(PRINT_ENV_PATH, {env: {FOO: 'foo'}});65- t.is(stdout, 'foo\nbar');66-};67-68-test('execa() bound options are merged multiple times', testMergeMultiple, execa);69-test('execaSync() bound options are merged multiple times', testMergeMultiple, execaSync);70-test('execaNode() bound options are merged multiple times', testMergeMultiple, execaNode);71-test('$ bound options are merged multiple times', testMergeMultiple, $);72-test('$.sync bound options are merged multiple times', testMergeMultiple, $.sync);73-74-const testMergeFdSpecific = async (t, execaMethod) => {75- const {isMaxBuffer, shortMessage} = await t.throwsAsync(execaMethod({maxBuffer: {stdout: 1}})(NOOP_PATH, [foobarString], {maxBuffer: {stderr: 100}}));76- t.true(isMaxBuffer);77- t.true(shortMessage.includes('Command\'s stdout was larger than 1'));78-};79-80-test('execa() bound options merge fd-specific ones', testMergeFdSpecific, execa);81-test('execaNode() bound options merge fd-specific ones', testMergeFdSpecific, execaNode);82-test('$ bound options merge fd-specific ones', testMergeFdSpecific, $);83-84-const testMergeEnvUndefined = async (t, execaMethod) => {85- const {stdout} = await execaMethod({env: {FOO: 'foo'}})(PRINT_ENV_PATH, {env: {BAR: undefined}});86- t.is(stdout, 'foo\nundefined');87-};88-89-test('execa() bound options are merged even if undefined', testMergeEnvUndefined, execa);90-test('execaSync() bound options are merged even if undefined', testMergeEnvUndefined, execaSync);91-test('execaNode() bound options are merged even if undefined', testMergeEnvUndefined, execaNode);92-test('$ bound options are merged even if undefined', testMergeEnvUndefined, $);93-test('$.sync bound options are merged even if undefined', testMergeEnvUndefined, $.sync);94-95-const testMergeSpecific = async (t, execaMethod) => {96- const {stdout} = await execaMethod({stdout: {transform: uppercaseGenerator().transform, objectMode: true}})(NOOP_PATH, {stdout: {transform: uppercaseGenerator().transform}});97- t.is(stdout, foobarUppercase);98-};99-100-test('execa() bound options only merge specific ones', testMergeSpecific, execa);101-test('execaSync() bound options only merge specific ones', testMergeSpecific, execaSync);102-test('execaNode() bound options only merge specific ones', testMergeSpecific, execaNode);103-test('$ bound options only merge specific ones', testMergeSpecific, $);104-test('$.sync bound options only merge specific ones', testMergeSpecific, $.sync);deleted:test/arguments/create-main.js-58 removed
1-import {join} from 'node:path';2-import test from 'ava';3-import {execa, execaSync, execaNode, $} from '../../index.js';4-import {foobarString, foobarArray} from '../helpers/input.js';5-import {setFixtureDir, FIXTURES_DIR} from '../helpers/fixtures-dir.js';6-7-setFixtureDir();8-9-const NOOP_PATH = join(FIXTURES_DIR, 'noop.js');10-11-const testTemplate = async (t, execaMethod) => {12- const {stdout} = await execaMethod`${NOOP_PATH} ${foobarString}`;13- t.is(stdout, foobarString);14-};15-16-test('execa() can use template strings', testTemplate, execa);17-test('execaNode() can use template strings', testTemplate, execaNode);18-test('$ can use template strings', testTemplate, $);19-20-const testTemplateSync = (t, execaMethod) => {21- const {stdout} = execaMethod`${NOOP_PATH} ${foobarString}`;22- t.is(stdout, foobarString);23-};24-25-test('execaSync() can use template strings', testTemplateSync, execaSync);26-test('$.sync can use template strings', testTemplateSync, $.sync);27-28-const testTemplateOptions = async (t, execaMethod) => {29- const {stdout} = await execaMethod({stripFinalNewline: false})`${NOOP_PATH} ${foobarString}`;30- t.is(stdout, `${foobarString}\n`);31-};32-33-test('execa() can use template strings with options', testTemplateOptions, execa);34-test('execaNode() can use template strings with options', testTemplateOptions, execaNode);35-test('$ can use template strings with options', testTemplateOptions, $);36-37-const testTemplateOptionsSync = (t, execaMethod) => {38- const {stdout} = execaMethod({stripFinalNewline: false})`${NOOP_PATH} ${foobarString}`;39- t.is(stdout, `${foobarString}\n`);40-};41-42-test('execaSync() can use template strings with options', testTemplateOptionsSync, execaSync);43-test('$.sync can use template strings with options', testTemplateOptionsSync, $.sync);44-45-const testSpacedCommand = async (t, args, execaMethod) => {46- const {stdout} = await execaMethod('command with space.js', args);47- const expectedStdout = args === undefined ? '' : args.join('\n');48- t.is(stdout, expectedStdout);49-};50-51-test('allow commands with spaces and no array arguments', testSpacedCommand, undefined, execa);52-test('allow commands with spaces and array arguments', testSpacedCommand, foobarArray, execa);53-test('allow commands with spaces and no array arguments, execaSync', testSpacedCommand, undefined, execaSync);54-test('allow commands with spaces and array arguments, execaSync', testSpacedCommand, foobarArray, execaSync);55-test('allow commands with spaces and no array arguments, $', testSpacedCommand, undefined, $);56-test('allow commands with spaces and array arguments, $', testSpacedCommand, foobarArray, $);57-test('allow commands with spaces and no array arguments, $.sync', testSpacedCommand, undefined, $.sync);58-test('allow commands with spaces and array arguments, $.sync', testSpacedCommand, foobarArray, $.sync);added:test/arguments/encoding-option.js+39 added
1+import test from 'ava';2+import {execa, execaSync} from '../../index.js';3+import {setFixtureDir} from '../helpers/fixtures-dir.js';4+5+setFixtureDir();6+7+const testInvalidEncoding = (t, encoding, message, execaMethod) => {8+ const error = t.throws(() => {9+ execaMethod('empty.js', {encoding});10+ });11+ t.true(error.message.includes(message));12+};13+14+const UNKNOWN_ENCODING_MESSAGE = 'Please rename it to one of';15+const getCorrectEncodingMessage = correctEncoding => `Please rename it to "${correctEncoding}"`;16+17+test('cannot pass unknown encodings', testInvalidEncoding, 'unknown', UNKNOWN_ENCODING_MESSAGE, execa);18+test('cannot pass unknown encodings, sync', testInvalidEncoding, 'unknown', UNKNOWN_ENCODING_MESSAGE, execaSync);19+test('cannot pass empty encodings', testInvalidEncoding, '', UNKNOWN_ENCODING_MESSAGE, execa);20+test('cannot pass encoding: false', testInvalidEncoding, false, UNKNOWN_ENCODING_MESSAGE, execa);21+test('cannot pass encoding: Symbol', testInvalidEncoding, Symbol('test'), UNKNOWN_ENCODING_MESSAGE, execa);22+test('cannot pass encoding: null', testInvalidEncoding, null, getCorrectEncodingMessage('buffer'), execa);23+test('cannot pass encoding: null, sync', testInvalidEncoding, null, getCorrectEncodingMessage('buffer'), execaSync);24+/* eslint-disable unicorn/text-encoding-identifier-case */25+test('cannot pass encoding: utf-8', testInvalidEncoding, 'utf-8', getCorrectEncodingMessage('utf8'), execa);26+test('cannot pass encoding: utf-8, sync', testInvalidEncoding, 'utf-8', getCorrectEncodingMessage('utf8'), execaSync);27+test('cannot pass encoding: UTF-8', testInvalidEncoding, 'UTF-8', getCorrectEncodingMessage('utf8'), execa);28+test('cannot pass encoding: UTF-8, sync', testInvalidEncoding, 'UTF-8', getCorrectEncodingMessage('utf8'), execaSync);29+test('cannot pass encoding: UTF8', testInvalidEncoding, 'UTF8', getCorrectEncodingMessage('utf8'), execa);30+test('cannot pass encoding: UTF8, sync', testInvalidEncoding, 'UTF8', getCorrectEncodingMessage('utf8'), execaSync);31+/* eslint-enable unicorn/text-encoding-identifier-case */32+test('cannot pass encoding: utf-16le', testInvalidEncoding, 'utf-16le', getCorrectEncodingMessage('utf16le'), execa);33+test('cannot pass encoding: UTF-16LE', testInvalidEncoding, 'UTF-16LE', getCorrectEncodingMessage('utf16le'), execa);34+test('cannot pass encoding: UTF16LE', testInvalidEncoding, 'UTF16LE', getCorrectEncodingMessage('utf16le'), execa);35+test('cannot pass encoding: ucs2', testInvalidEncoding, 'ucs2', getCorrectEncodingMessage('utf16le'), execa);36+test('cannot pass encoding: UCS2', testInvalidEncoding, 'UCS2', getCorrectEncodingMessage('utf16le'), execa);37+test('cannot pass encoding: ucs-2', testInvalidEncoding, 'ucs-2', getCorrectEncodingMessage('utf16le'), execa);38+test('cannot pass encoding: UCS-2', testInvalidEncoding, 'UCS-2', getCorrectEncodingMessage('utf16le'), execa);39+test('cannot pass encoding: binary', testInvalidEncoding, 'binary', getCorrectEncodingMessage('latin1'), execa);deleted:test/arguments/encoding.js-39 removed
1-import test from 'ava';2-import {execa, execaSync} from '../../index.js';3-import {setFixtureDir} from '../helpers/fixtures-dir.js';4-5-setFixtureDir();6-7-const testInvalidEncoding = (t, encoding, message, execaMethod) => {8- const error = t.throws(() => {9- execaMethod('empty.js', {encoding});10- });11- t.true(error.message.includes(message));12-};13-14-const UNKNOWN_ENCODING_MESSAGE = 'Please rename it to one of';15-const getCorrectEncodingMessage = correctEncoding => `Please rename it to "${correctEncoding}"`;16-17-test('cannot pass unknown encodings', testInvalidEncoding, 'unknown', UNKNOWN_ENCODING_MESSAGE, execa);18-test('cannot pass unknown encodings, sync', testInvalidEncoding, 'unknown', UNKNOWN_ENCODING_MESSAGE, execaSync);19-test('cannot pass empty encodings', testInvalidEncoding, '', UNKNOWN_ENCODING_MESSAGE, execa);20-test('cannot pass encoding: false', testInvalidEncoding, false, UNKNOWN_ENCODING_MESSAGE, execa);21-test('cannot pass encoding: Symbol', testInvalidEncoding, Symbol('test'), UNKNOWN_ENCODING_MESSAGE, execa);22-test('cannot pass encoding: null', testInvalidEncoding, null, getCorrectEncodingMessage('buffer'), execa);23-test('cannot pass encoding: null, sync', testInvalidEncoding, null, getCorrectEncodingMessage('buffer'), execaSync);24-/* eslint-disable unicorn/text-encoding-identifier-case */25-test('cannot pass encoding: utf-8', testInvalidEncoding, 'utf-8', getCorrectEncodingMessage('utf8'), execa);26-test('cannot pass encoding: utf-8, sync', testInvalidEncoding, 'utf-8', getCorrectEncodingMessage('utf8'), execaSync);27-test('cannot pass encoding: UTF-8', testInvalidEncoding, 'UTF-8', getCorrectEncodingMessage('utf8'), execa);28-test('cannot pass encoding: UTF-8, sync', testInvalidEncoding, 'UTF-8', getCorrectEncodingMessage('utf8'), execaSync);29-test('cannot pass encoding: UTF8', testInvalidEncoding, 'UTF8', getCorrectEncodingMessage('utf8'), execa);30-test('cannot pass encoding: UTF8, sync', testInvalidEncoding, 'UTF8', getCorrectEncodingMessage('utf8'), execaSync);31-/* eslint-enable unicorn/text-encoding-identifier-case */32-test('cannot pass encoding: utf-16le', testInvalidEncoding, 'utf-16le', getCorrectEncodingMessage('utf16le'), execa);33-test('cannot pass encoding: UTF-16LE', testInvalidEncoding, 'UTF-16LE', getCorrectEncodingMessage('utf16le'), execa);34-test('cannot pass encoding: UTF16LE', testInvalidEncoding, 'UTF16LE', getCorrectEncodingMessage('utf16le'), execa);35-test('cannot pass encoding: ucs2', testInvalidEncoding, 'ucs2', getCorrectEncodingMessage('utf16le'), execa);36-test('cannot pass encoding: UCS2', testInvalidEncoding, 'UCS2', getCorrectEncodingMessage('utf16le'), execa);37-test('cannot pass encoding: ucs-2', testInvalidEncoding, 'ucs-2', getCorrectEncodingMessage('utf16le'), execa);38-test('cannot pass encoding: UCS-2', testInvalidEncoding, 'UCS-2', getCorrectEncodingMessage('utf16le'), execa);39-test('cannot pass encoding: binary', testInvalidEncoding, 'binary', getCorrectEncodingMessage('latin1'), execa);added:test/arguments/fd-options.js+725 added
1+import {PassThrough} from 'node:stream';2+import {spawn} from 'node:child_process';3+import process from 'node:process';4+import test from 'ava';5+import {execa} from '../../index.js';6+import {setFixtureDir} from '../helpers/fixtures-dir.js';7+import {fullStdio, getStdio} from '../helpers/stdio.js';8+import {getEarlyErrorSubprocess} from '../helpers/early-error.js';9+import {assertPipeError} from '../helpers/pipe.js';10+11+setFixtureDir();12+13+const getMessage = message => Array.isArray(message)14+ ? `"${message[0]}: ${message[1]}" option is incompatible`15+ : message;16+17+const testPipeError = async (t, {18+ message,19+ sourceOptions = {},20+ destinationOptions = {},21+ getSource = () => execa('empty.js', sourceOptions),22+ getDestination = () => execa('empty.js', destinationOptions),23+ isScript = false,24+ from,25+ to,26+}) => {27+ const source = getSource();28+ const pipePromise = isScript ? source.pipe({from, to})`empty.js` : source.pipe(getDestination(), {from, to});29+ await assertPipeError(t, pipePromise, getMessage(message));30+};31+32+const testNodeStream = async (t, {33+ message,34+ sourceOptions = {},35+ getSource = () => execa('empty.js', sourceOptions),36+ from,37+ to,38+ writable = to !== undefined,39+}) => {40+ assertNodeStream({t, message, getSource, from, to, methodName: writable ? 'writable' : 'readable'});41+ assertNodeStream({t, message, getSource, from, to, methodName: 'duplex'});42+};43+44+const assertNodeStream = ({t, message, getSource, from, to, methodName}) => {45+ const error = t.throws(() => {46+ getSource()[methodName]({from, to});47+ });48+ t.true(error.message.includes(getMessage(message)));49+};50+51+const testIterable = async (t, {52+ message,53+ sourceOptions = {},54+ getSource = () => execa('empty.js', sourceOptions),55+ from,56+}) => {57+ const error = t.throws(() => {58+ getSource().iterable({from});59+ });60+ t.true(error.message.includes(getMessage(message)));61+};62+63+test('Must set "all" option to "true" to use .pipe("all")', testPipeError, {64+ from: 'all',65+ message: '"all" option must be true',66+});67+test('Must set "all" option to "true" to use .duplex("all")', testNodeStream, {68+ from: 'all',69+ message: '"all" option must be true',70+});71+test('Must set "all" option to "true" to use .iterable("all")', testIterable, {72+ from: 'all',73+ message: '"all" option must be true',74+});75+test('.pipe() cannot pipe to non-subprocesses', testPipeError, {76+ getDestination: () => new PassThrough(),77+ message: 'an Execa subprocess',78+});79+test('.pipe() cannot pipe to non-Execa subprocesses', testPipeError, {80+ getDestination: () => spawn('node', ['--version']),81+ message: 'an Execa subprocess',82+});83+test('.pipe() "from" option cannot be "stdin"', testPipeError, {84+ from: 'stdin',85+ message: '"from" must not be',86+});87+test('.duplex() "from" option cannot be "stdin"', testNodeStream, {88+ from: 'stdin',89+ message: '"from" must not be',90+});91+test('.iterable() "from" option cannot be "stdin"', testIterable, {92+ from: 'stdin',93+ message: '"from" must not be',94+});95+test('$.pipe() "from" option cannot be "stdin"', testPipeError, {96+ from: 'stdin',97+ isScript: true,98+ message: '"from" must not be',99+});100+test('.pipe() "to" option cannot be "stdout"', testPipeError, {101+ to: 'stdout',102+ message: '"to" must not be',103+});104+test('.duplex() "to" option cannot be "stdout"', testNodeStream, {105+ to: 'stdout',106+ message: '"to" must not be',107+});108+test('$.pipe() "to" option cannot be "stdout"', testPipeError, {109+ to: 'stdout',110+ isScript: true,111+ message: '"to" must not be',112+});113+test('.pipe() "from" option cannot be any string', testPipeError, {114+ from: 'other',115+ message: 'must be "stdout", "stderr", "all"',116+});117+test('.duplex() "from" option cannot be any string', testNodeStream, {118+ from: 'other',119+ message: 'must be "stdout", "stderr", "all"',120+});121+test('.iterable() "from" option cannot be any string', testIterable, {122+ from: 'other',123+ message: 'must be "stdout", "stderr", "all"',124+});125+test('.pipe() "to" option cannot be any string', testPipeError, {126+ to: 'other',127+ message: 'must be "stdin"',128+});129+test('.duplex() "to" option cannot be any string', testNodeStream, {130+ to: 'other',131+ message: 'must be "stdin"',132+});133+test('.pipe() "from" option cannot be a number without "fd"', testPipeError, {134+ from: '1',135+ message: 'must be "stdout", "stderr", "all"',136+});137+test('.duplex() "from" option cannot be a number without "fd"', testNodeStream, {138+ from: '1',139+ message: 'must be "stdout", "stderr", "all"',140+});141+test('.iterable() "from" option cannot be a number without "fd"', testIterable, {142+ from: '1',143+ message: 'must be "stdout", "stderr", "all"',144+});145+test('.pipe() "to" option cannot be a number without "fd"', testPipeError, {146+ to: '0',147+ message: 'must be "stdin"',148+});149+test('.duplex() "to" option cannot be a number without "fd"', testNodeStream, {150+ to: '0',151+ message: 'must be "stdin"',152+});153+test('.pipe() "from" option cannot be just "fd"', testPipeError, {154+ from: 'fd',155+ message: 'must be "stdout", "stderr", "all"',156+});157+test('.duplex() "from" option cannot be just "fd"', testNodeStream, {158+ from: 'fd',159+ message: 'must be "stdout", "stderr", "all"',160+});161+test('.iterable() "from" option cannot be just "fd"', testIterable, {162+ from: 'fd',163+ message: 'must be "stdout", "stderr", "all"',164+});165+test('.pipe() "to" option cannot be just "fd"', testPipeError, {166+ to: 'fd',167+ message: 'must be "stdin"',168+});169+test('.duplex() "to" option cannot be just "fd"', testNodeStream, {170+ to: 'fd',171+ message: 'must be "stdin"',172+});173+test('.pipe() "from" option cannot be a float', testPipeError, {174+ from: 'fd1.5',175+ message: 'must be "stdout", "stderr", "all"',176+});177+test('.duplex() "from" option cannot be a float', testNodeStream, {178+ from: 'fd1.5',179+ message: 'must be "stdout", "stderr", "all"',180+});181+test('.iterable() "from" option cannot be a float', testIterable, {182+ from: 'fd1.5',183+ message: 'must be "stdout", "stderr", "all"',184+});185+test('.pipe() "to" option cannot be a float', testPipeError, {186+ to: 'fd1.5',187+ message: 'must be "stdin"',188+});189+test('.duplex() "to" option cannot be a float', testNodeStream, {190+ to: 'fd1.5',191+ message: 'must be "stdin"',192+});193+test('.pipe() "from" option cannot be a negative number', testPipeError, {194+ from: 'fd-1',195+ message: 'must be "stdout", "stderr", "all"',196+});197+test('.duplex() "from" option cannot be a negative number', testNodeStream, {198+ from: 'fd-1',199+ message: 'must be "stdout", "stderr", "all"',200+});201+test('.iterable() "from" option cannot be a negative number', testIterable, {202+ from: 'fd-1',203+ message: 'must be "stdout", "stderr", "all"',204+});205+test('.pipe() "to" option cannot be a negative number', testPipeError, {206+ to: 'fd-1',207+ message: 'must be "stdin"',208+});209+test('.duplex() "to" option cannot be a negative number', testNodeStream, {210+ to: 'fd-1',211+ message: 'must be "stdin"',212+});213+test('.pipe() "from" option cannot be a non-existing file descriptor', testPipeError, {214+ from: 'fd3',215+ message: 'file descriptor does not exist',216+});217+test('.duplex() "from" cannot be a non-existing file descriptor', testNodeStream, {218+ from: 'fd3',219+ message: 'file descriptor does not exist',220+});221+test('.iterable() "from" cannot be a non-existing file descriptor', testIterable, {222+ from: 'fd3',223+ message: 'file descriptor does not exist',224+});225+test('.pipe() "to" option cannot be a non-existing file descriptor', testPipeError, {226+ to: 'fd3',227+ message: 'file descriptor does not exist',228+});229+test('.duplex() "to" cannot be a non-existing file descriptor', testNodeStream, {230+ to: 'fd3',231+ message: 'file descriptor does not exist',232+});233+test('.pipe() "from" option cannot be an input file descriptor', testPipeError, {234+ sourceOptions: getStdio(3, new Uint8Array()),235+ from: 'fd3',236+ message: 'must be a readable stream',237+});238+test('.duplex() "from" option cannot be an input file descriptor', testNodeStream, {239+ sourceOptions: getStdio(3, new Uint8Array()),240+ from: 'fd3',241+ message: 'must be a readable stream',242+});243+test('.iterable() "from" option cannot be an input file descriptor', testIterable, {244+ sourceOptions: getStdio(3, new Uint8Array()),245+ from: 'fd3',246+ message: 'must be a readable stream',247+});248+test('.pipe() "to" option cannot be an output file descriptor', testPipeError, {249+ destinationOptions: fullStdio,250+ to: 'fd3',251+ message: 'must be a writable stream',252+});253+test('.duplex() "to" option cannot be an output file descriptor', testNodeStream, {254+ sourceOptions: fullStdio,255+ to: 'fd3',256+ message: 'must be a writable stream',257+});258+test('.pipe() "to" option cannot be "all"', testPipeError, {259+ destinationOptions: fullStdio,260+ to: 'all',261+ message: 'must be a writable stream',262+});263+test('.duplex() "to" option cannot be "all"', testNodeStream, {264+ sourceOptions: fullStdio,265+ to: 'all',266+ message: 'must be a writable stream',267+});268+test('Cannot set "stdout" option to "ignore" to use .pipe()', testPipeError, {269+ sourceOptions: {stdout: 'ignore'},270+ message: ['stdout', '\'ignore\''],271+});272+test('Cannot set "stdout" option to "ignore" to use .duplex()', testNodeStream, {273+ sourceOptions: {stdout: 'ignore'},274+ message: ['stdout', '\'ignore\''],275+});276+test('Cannot set "stdout" option to "ignore" to use .iterable()', testIterable, {277+ sourceOptions: {stdout: 'ignore'},278+ message: ['stdout', '\'ignore\''],279+});280+test('Cannot set "stdin" option to "ignore" to use .pipe()', testPipeError, {281+ destinationOptions: {stdin: 'ignore'},282+ message: ['stdin', '\'ignore\''],283+});284+test('Cannot set "stdin" option to "ignore" to use .duplex()', testNodeStream, {285+ sourceOptions: {stdin: 'ignore'},286+ message: ['stdin', '\'ignore\''],287+ writable: true,288+});289+test('Cannot set "stdout" option to "ignore" to use .pipe(1)', testPipeError, {290+ sourceOptions: {stdout: 'ignore'},291+ from: 'fd1',292+ message: ['stdout', '\'ignore\''],293+});294+test('Cannot set "stdout" option to "ignore" to use .duplex(1)', testNodeStream, {295+ sourceOptions: {stdout: 'ignore'},296+ from: 'fd1',297+ message: ['stdout', '\'ignore\''],298+});299+test('Cannot set "stdout" option to "ignore" to use .iterable(1)', testIterable, {300+ sourceOptions: {stdout: 'ignore'},301+ from: 'fd1',302+ message: ['stdout', '\'ignore\''],303+});304+test('Cannot set "stdin" option to "ignore" to use .pipe(0)', testPipeError, {305+ destinationOptions: {stdin: 'ignore'},306+ message: ['stdin', '\'ignore\''],307+ to: 'fd0',308+});309+test('Cannot set "stdin" option to "ignore" to use .duplex(0)', testNodeStream, {310+ sourceOptions: {stdin: 'ignore'},311+ message: ['stdin', '\'ignore\''],312+ to: 'fd0',313+});314+test('Cannot set "stdout" option to "ignore" to use .pipe("stdout")', testPipeError, {315+ sourceOptions: {stdout: 'ignore'},316+ from: 'stdout',317+ message: ['stdout', '\'ignore\''],318+});319+test('Cannot set "stdout" option to "ignore" to use .duplex("stdout")', testNodeStream, {320+ sourceOptions: {stdout: 'ignore'},321+ from: 'stdout',322+ message: ['stdout', '\'ignore\''],323+});324+test('Cannot set "stdout" option to "ignore" to use .iterable("stdout")', testIterable, {325+ sourceOptions: {stdout: 'ignore'},326+ from: 'stdout',327+ message: ['stdout', '\'ignore\''],328+});329+test('Cannot set "stdin" option to "ignore" to use .pipe("stdin")', testPipeError, {330+ destinationOptions: {stdin: 'ignore'},331+ message: ['stdin', '\'ignore\''],332+ to: 'stdin',333+});334+test('Cannot set "stdin" option to "ignore" to use .duplex("stdin")', testNodeStream, {335+ sourceOptions: {stdin: 'ignore'},336+ message: ['stdin', '\'ignore\''],337+ to: 'stdin',338+});339+test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe()', testPipeError, {340+ sourceOptions: {stdout: 'ignore', stderr: 'ignore'},341+ message: ['stdout', '\'ignore\''],342+});343+test('Cannot set "stdout" + "stderr" option to "ignore" to use .duplex()', testNodeStream, {344+ sourceOptions: {stdout: 'ignore', stderr: 'ignore'},345+ message: ['stdout', '\'ignore\''],346+});347+test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable()', testIterable, {348+ sourceOptions: {stdout: 'ignore', stderr: 'ignore'},349+ message: ['stdout', '\'ignore\''],350+});351+test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe(1)', testPipeError, {352+ sourceOptions: {stdout: 'ignore', stderr: 'ignore'},353+ from: 'fd1',354+ message: ['stdout', '\'ignore\''],355+});356+test('Cannot set "stdout" + "stderr" option to "ignore" to use .duplex(1)', testNodeStream, {357+ sourceOptions: {stdout: 'ignore', stderr: 'ignore'},358+ from: 'fd1',359+ message: ['stdout', '\'ignore\''],360+});361+test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable(1)', testIterable, {362+ sourceOptions: {stdout: 'ignore', stderr: 'ignore'},363+ from: 'fd1',364+ message: ['stdout', '\'ignore\''],365+});366+test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe("stdout")', testPipeError, {367+ sourceOptions: {stdout: 'ignore', stderr: 'ignore'},368+ from: 'stdout',369+ message: ['stdout', '\'ignore\''],370+});371+test('Cannot set "stdout" + "stderr" option to "ignore" to use .duplex("stdout")', testNodeStream, {372+ sourceOptions: {stdout: 'ignore', stderr: 'ignore'},373+ from: 'stdout',374+ message: ['stdout', '\'ignore\''],375+});376+test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable("stdout")', testIterable, {377+ sourceOptions: {stdout: 'ignore', stderr: 'ignore'},378+ from: 'stdout',379+ message: ['stdout', '\'ignore\''],380+});381+test('Cannot set "stdio[1]" option to "ignore" to use .pipe()', testPipeError, {382+ sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},383+ message: ['stdio[1]', '\'ignore\''],384+});385+test('Cannot set "stdio[1]" option to "ignore" to use .duplex()', testNodeStream, {386+ sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},387+ message: ['stdio[1]', '\'ignore\''],388+});389+test('Cannot set "stdio[1]" option to "ignore" to use .iterable()', testIterable, {390+ sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},391+ message: ['stdio[1]', '\'ignore\''],392+});393+test('Cannot set "stdio[0]" option to "ignore" to use .pipe()', testPipeError, {394+ destinationOptions: {stdio: ['ignore', 'pipe', 'pipe']},395+ message: ['stdio[0]', '\'ignore\''],396+});397+test('Cannot set "stdio[0]" option to "ignore" to use .duplex()', testNodeStream, {398+ sourceOptions: {stdio: ['ignore', 'pipe', 'pipe']},399+ message: ['stdio[0]', '\'ignore\''],400+ writable: true,401+});402+test('Cannot set "stdio[1]" option to "ignore" to use .pipe(1)', testPipeError, {403+ sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},404+ from: 'fd1',405+ message: ['stdio[1]', '\'ignore\''],406+});407+test('Cannot set "stdio[1]" option to "ignore" to use .duplex(1)', testNodeStream, {408+ sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},409+ from: 'fd1',410+ message: ['stdio[1]', '\'ignore\''],411+});412+test('Cannot set "stdio[1]" option to "ignore" to use .iterable(1)', testIterable, {413+ sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},414+ from: 'fd1',415+ message: ['stdio[1]', '\'ignore\''],416+});417+test('Cannot set "stdio[0]" option to "ignore" to use .pipe(0)', testPipeError, {418+ destinationOptions: {stdio: ['ignore', 'pipe', 'pipe']},419+ message: ['stdio[0]', '\'ignore\''],420+ to: 'fd0',421+});422+test('Cannot set "stdio[0]" option to "ignore" to use .duplex(0)', testNodeStream, {423+ sourceOptions: {stdio: ['ignore', 'pipe', 'pipe']},424+ message: ['stdio[0]', '\'ignore\''],425+ to: 'fd0',426+});427+test('Cannot set "stdio[1]" option to "ignore" to use .pipe("stdout")', testPipeError, {428+ sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},429+ from: 'stdout',430+ message: ['stdio[1]', '\'ignore\''],431+});432+test('Cannot set "stdio[1]" option to "ignore" to use .duplex("stdout")', testNodeStream, {433+ sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},434+ from: 'stdout',435+ message: ['stdio[1]', '\'ignore\''],436+});437+test('Cannot set "stdio[1]" option to "ignore" to use .iterable("stdout")', testIterable, {438+ sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},439+ from: 'stdout',440+ message: ['stdio[1]', '\'ignore\''],441+});442+test('Cannot set "stdio[0]" option to "ignore" to use .pipe("stdin")', testPipeError, {443+ destinationOptions: {stdio: ['ignore', 'pipe', 'pipe']},444+ message: ['stdio[0]', '\'ignore\''],445+ to: 'stdin',446+});447+test('Cannot set "stdio[0]" option to "ignore" to use .duplex("stdin")', testNodeStream, {448+ sourceOptions: {stdio: ['ignore', 'pipe', 'pipe']},449+ message: ['stdio[0]', '\'ignore\''],450+ to: 'stdin',451+});452+test('Cannot set "stderr" option to "ignore" to use .pipe(2)', testPipeError, {453+ sourceOptions: {stderr: 'ignore'},454+ from: 'fd2',455+ message: ['stderr', '\'ignore\''],456+});457+test('Cannot set "stderr" option to "ignore" to use .duplex(2)', testNodeStream, {458+ sourceOptions: {stderr: 'ignore'},459+ from: 'fd2',460+ message: ['stderr', '\'ignore\''],461+});462+test('Cannot set "stderr" option to "ignore" to use .iterable(2)', testIterable, {463+ sourceOptions: {stderr: 'ignore'},464+ from: 'fd2',465+ message: ['stderr', '\'ignore\''],466+});467+test('Cannot set "stderr" option to "ignore" to use .pipe("stderr")', testPipeError, {468+ sourceOptions: {stderr: 'ignore'},469+ from: 'stderr',470+ message: ['stderr', '\'ignore\''],471+});472+test('Cannot set "stderr" option to "ignore" to use .duplex("stderr")', testNodeStream, {473+ sourceOptions: {stderr: 'ignore'},474+ from: 'stderr',475+ message: ['stderr', '\'ignore\''],476+});477+test('Cannot set "stderr" option to "ignore" to use .iterable("stderr")', testIterable, {478+ sourceOptions: {stderr: 'ignore'},479+ from: 'stderr',480+ message: ['stderr', '\'ignore\''],481+});482+test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe(2)', testPipeError, {483+ sourceOptions: {stdout: 'ignore', stderr: 'ignore'},484+ from: 'fd2',485+ message: ['stderr', '\'ignore\''],486+});487+test('Cannot set "stdout" + "stderr" option to "ignore" to use .duplex(2)', testNodeStream, {488+ sourceOptions: {stdout: 'ignore', stderr: 'ignore'},489+ from: 'fd2',490+ message: ['stderr', '\'ignore\''],491+});492+test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable(2)', testIterable, {493+ sourceOptions: {stdout: 'ignore', stderr: 'ignore'},494+ from: 'fd2',495+ message: ['stderr', '\'ignore\''],496+});497+test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe("stderr")', testPipeError, {498+ sourceOptions: {stdout: 'ignore', stderr: 'ignore'},499+ from: 'stderr',500+ message: ['stderr', '\'ignore\''],501+});502+test('Cannot set "stdout" + "stderr" option to "ignore" to use .duplex("stderr")', testNodeStream, {503+ sourceOptions: {stdout: 'ignore', stderr: 'ignore'},504+ from: 'stderr',505+ message: ['stderr', '\'ignore\''],506+});507+test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable("stderr")', testIterable, {508+ sourceOptions: {stdout: 'ignore', stderr: 'ignore'},509+ from: 'stderr',510+ message: ['stderr', '\'ignore\''],511+});512+test('Cannot set "stdio[2]" option to "ignore" to use .pipe(2)', testPipeError, {513+ sourceOptions: {stdio: ['pipe', 'pipe', 'ignore']},514+ from: 'fd2',515+ message: ['stdio[2]', '\'ignore\''],516+});517+test('Cannot set "stdio[2]" option to "ignore" to use .duplex(2)', testNodeStream, {518+ sourceOptions: {stdio: ['pipe', 'pipe', 'ignore']},519+ from: 'fd2',520+ message: ['stdio[2]', '\'ignore\''],521+});522+test('Cannot set "stdio[2]" option to "ignore" to use .iterable(2)', testIterable, {523+ sourceOptions: {stdio: ['pipe', 'pipe', 'ignore']},524+ from: 'fd2',525+ message: ['stdio[2]', '\'ignore\''],526+});527+test('Cannot set "stdio[2]" option to "ignore" to use .pipe("stderr")', testPipeError, {528+ sourceOptions: {stdio: ['pipe', 'pipe', 'ignore']},529+ from: 'stderr',530+ message: ['stdio[2]', '\'ignore\''],531+});532+test('Cannot set "stdio[2]" option to "ignore" to use .duplex("stderr")', testNodeStream, {533+ sourceOptions: {stdio: ['pipe', 'pipe', 'ignore']},534+ from: 'stderr',535+ message: ['stdio[2]', '\'ignore\''],536+});537+test('Cannot set "stdio[2]" option to "ignore" to use .iterable("stderr")', testIterable, {538+ sourceOptions: {stdio: ['pipe', 'pipe', 'ignore']},539+ from: 'stderr',540+ message: ['stdio[2]', '\'ignore\''],541+});542+test('Cannot set "stdio[3]" option to "ignore" to use .pipe(3)', testPipeError, {543+ sourceOptions: getStdio(3, 'ignore'),544+ from: 'fd3',545+ message: ['stdio[3]', '\'ignore\''],546+});547+test('Cannot set "stdio[3]" option to "ignore" to use .duplex(3)', testNodeStream, {548+ sourceOptions: getStdio(3, 'ignore'),549+ from: 'fd3',550+ message: ['stdio[3]', '\'ignore\''],551+});552+test('Cannot set "stdio[3]" option to "ignore" to use .iterable(3)', testIterable, {553+ sourceOptions: getStdio(3, 'ignore'),554+ from: 'fd3',555+ message: ['stdio[3]', '\'ignore\''],556+});557+test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe("all")', testPipeError, {558+ sourceOptions: {stdout: 'ignore', stderr: 'ignore', all: true},559+ from: 'all',560+ message: ['stdout', '\'ignore\''],561+});562+test('Cannot set "stdout" + "stderr" option to "ignore" to use .duplex("all")', testNodeStream, {563+ sourceOptions: {stdout: 'ignore', stderr: 'ignore', all: true},564+ from: 'all',565+ message: ['stdout', '\'ignore\''],566+});567+test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable("all")', testIterable, {568+ sourceOptions: {stdout: 'ignore', stderr: 'ignore', all: true},569+ from: 'all',570+ message: ['stdout', '\'ignore\''],571+});572+test('Cannot set "stdio[1]" + "stdio[2]" option to "ignore" to use .pipe("all")', testPipeError, {573+ sourceOptions: {stdio: ['pipe', 'ignore', 'ignore'], all: true},574+ from: 'all',575+ message: ['stdio[1]', '\'ignore\''],576+});577+test('Cannot set "stdio[1]" + "stdio[2]" option to "ignore" to use .duplex("all")', testNodeStream, {578+ sourceOptions: {stdio: ['pipe', 'ignore', 'ignore'], all: true},579+ from: 'all',580+ message: ['stdio[1]', '\'ignore\''],581+});582+test('Cannot set "stdio[1]" + "stdio[2]" option to "ignore" to use .iterable("all")', testIterable, {583+ sourceOptions: {stdio: ['pipe', 'ignore', 'ignore'], all: true},584+ from: 'all',585+ message: ['stdio[1]', '\'ignore\''],586+});587+test('Cannot set "stdout" option to "inherit" to use .pipe()', testPipeError, {588+ sourceOptions: {stdout: 'inherit'},589+ message: ['stdout', '\'inherit\''],590+});591+test('Cannot set "stdout" option to "inherit" to use .duplex()', testNodeStream, {592+ sourceOptions: {stdout: 'inherit'},593+ message: ['stdout', '\'inherit\''],594+});595+test('Cannot set "stdout" option to "inherit" to use .iterable()', testIterable, {596+ sourceOptions: {stdout: 'inherit'},597+ message: ['stdout', '\'inherit\''],598+});599+test('Cannot set "stdin" option to "inherit" to use .pipe()', testPipeError, {600+ destinationOptions: {stdin: 'inherit'},601+ message: ['stdin', '\'inherit\''],602+});603+test('Cannot set "stdin" option to "inherit" to use .duplex()', testNodeStream, {604+ sourceOptions: {stdin: 'inherit'},605+ message: ['stdin', '\'inherit\''],606+ writable: true,607+});608+test('Cannot set "stdout" option to "ipc" to use .pipe()', testPipeError, {609+ sourceOptions: {stdout: 'ipc'},610+ message: ['stdout', '\'ipc\''],611+});612+test('Cannot set "stdout" option to "ipc" to use .duplex()', testNodeStream, {613+ sourceOptions: {stdout: 'ipc'},614+ message: ['stdout', '\'ipc\''],615+});616+test('Cannot set "stdout" option to "ipc" to use .iterable()', testIterable, {617+ sourceOptions: {stdout: 'ipc'},618+ message: ['stdout', '\'ipc\''],619+});620+test('Cannot set "stdin" option to "ipc" to use .pipe()', testPipeError, {621+ destinationOptions: {stdin: 'ipc'},622+ message: ['stdin', '\'ipc\''],623+});624+test('Cannot set "stdin" option to "ipc" to use .duplex()', testNodeStream, {625+ sourceOptions: {stdin: 'ipc'},626+ message: ['stdin', '\'ipc\''],627+ writable: true,628+});629+test('Cannot set "stdout" option to file descriptors to use .pipe()', testPipeError, {630+ sourceOptions: {stdout: 1},631+ message: ['stdout', '1'],632+});633+test('Cannot set "stdout" option to file descriptors to use .duplex()', testNodeStream, {634+ sourceOptions: {stdout: 1},635+ message: ['stdout', '1'],636+});637+test('Cannot set "stdout" option to file descriptors to use .iterable()', testIterable, {638+ sourceOptions: {stdout: 1},639+ message: ['stdout', '1'],640+});641+test('Cannot set "stdin" option to file descriptors to use .pipe()', testPipeError, {642+ destinationOptions: {stdin: 0},643+ message: ['stdin', '0'],644+});645+test('Cannot set "stdin" option to file descriptors to use .duplex()', testNodeStream, {646+ sourceOptions: {stdin: 0},647+ message: ['stdin', '0'],648+ writable: true,649+});650+test('Cannot set "stdout" option to Node.js streams to use .pipe()', testPipeError, {651+ sourceOptions: {stdout: process.stdout},652+ message: ['stdout', 'Stream'],653+});654+test('Cannot set "stdout" option to Node.js streams to use .duplex()', testNodeStream, {655+ sourceOptions: {stdout: process.stdout},656+ message: ['stdout', 'Stream'],657+});658+test('Cannot set "stdout" option to Node.js streams to use .iterable()', testIterable, {659+ sourceOptions: {stdout: process.stdout},660+ message: ['stdout', 'Stream'],661+});662+test('Cannot set "stdin" option to Node.js streams to use .pipe()', testPipeError, {663+ destinationOptions: {stdin: process.stdin},664+ message: ['stdin', 'Stream'],665+});666+test('Cannot set "stdin" option to Node.js streams to use .duplex()', testNodeStream, {667+ sourceOptions: {stdin: process.stdin},668+ message: ['stdin', 'Stream'],669+ writable: true,670+});671+test('Cannot set "stdio[3]" option to Node.js Writable streams to use .pipe()', testPipeError, {672+ sourceOptions: getStdio(3, process.stdout),673+ message: ['stdio[3]', 'Stream'],674+ from: 'fd3',675+});676+test('Cannot set "stdio[3]" option to Node.js Writable streams to use .duplex()', testNodeStream, {677+ sourceOptions: getStdio(3, process.stdout),678+ message: ['stdio[3]', 'Stream'],679+ from: 'fd3',680+});681+test('Cannot set "stdio[3]" option to Node.js Writable streams to use .iterable()', testIterable, {682+ sourceOptions: getStdio(3, process.stdout),683+ message: ['stdio[3]', 'Stream'],684+ from: 'fd3',685+});686+test('Cannot set "stdio[3]" option to Node.js Readable streams to use .pipe()', testPipeError, {687+ destinationOptions: getStdio(3, process.stdin),688+ message: ['stdio[3]', 'Stream'],689+ to: 'fd3',690+});691+test('Cannot set "stdio[3]" option to Node.js Readable streams to use .duplex()', testNodeStream, {692+ sourceOptions: getStdio(3, process.stdin),693+ message: ['stdio[3]', 'Stream'],694+ to: 'fd3',695+});696+697+test('Sets the right error message when the "all" option is incompatible - execa.$', async t => {698+ await assertPipeError(699+ t,700+ execa('empty.js')701+ .pipe({all: false})`stdin.js`702+ .pipe(execa('empty.js'), {from: 'all'}),703+ '"all" option must be true',704+ );705+});706+707+test('Sets the right error message when the "all" option is incompatible - execa.execa', async t => {708+ await assertPipeError(709+ t,710+ execa('empty.js')711+ .pipe(execa('stdin.js', {all: false}))712+ .pipe(execa('empty.js'), {from: 'all'}),713+ '"all" option must be true',714+ );715+});716+717+test('Sets the right error message when the "all" option is incompatible - early error', async t => {718+ await assertPipeError(719+ t,720+ getEarlyErrorSubprocess()721+ .pipe(execa('stdin.js', {all: false}))722+ .pipe(execa('empty.js'), {from: 'all'}),723+ '"all" option must be true',724+ );725+});deleted:test/arguments/node.js-305 removed
1-import {once} from 'node:events';2-import {dirname, relative} from 'node:path';3-import process, {version} from 'node:process';4-import {pathToFileURL} from 'node:url';5-import test from 'ava';6-import getNode from 'get-node';7-import {pEvent} from 'p-event';8-import {execa, execaSync, execaNode} from '../../index.js';9-import {FIXTURES_DIR} from '../helpers/fixtures-dir.js';10-import {identity, fullStdio} from '../helpers/stdio.js';11-import {foobarString} from '../helpers/input.js';12-13-process.chdir(FIXTURES_DIR);14-15-const runWithNodeOption = (file, args, options) => Array.isArray(args)16- ? execa(file, args, {...options, node: true})17- : execa(file, {...options, node: true});18-const runWithNodeOptionSync = (file, args, options) => Array.isArray(args)19- ? execaSync(file, args, {...options, node: true})20- : execaSync(file, {...options, node: true});21-const runWithIpc = (file, options) => execa('node', [file], {...options, ipc: true});22-23-const testNodeSuccess = async (t, execaMethod) => {24- const {exitCode, stdout} = await execaMethod('noop.js', [foobarString]);25- t.is(exitCode, 0);26- t.is(stdout, foobarString);27-};28-29-test('execaNode() succeeds', testNodeSuccess, execaNode);30-test('The "node" option succeeds', testNodeSuccess, runWithNodeOption);31-test('The "node" option succeeds - sync', testNodeSuccess, runWithNodeOptionSync);32-33-test('execaNode(options) succeeds', async t => {34- const {stdout} = await execaNode({stripFinalNewline: false})('noop.js', [foobarString]);35- t.is(stdout, `${foobarString}\n`);36-});37-38-test('execaNode`...` succeeds', async t => {39- const {stdout} = await execaNode`noop.js ${foobarString}`;40- t.is(stdout, foobarString);41-});42-43-test('execaNode().pipe(execaNode()) succeeds', async t => {44- const {stdout} = await execaNode('noop.js').pipe(execaNode('--version'));45- t.is(stdout, version);46-});47-48-test('execaNode().pipe(execa()) requires using "node"', async t => {49- await t.throwsAsync(execaNode('noop.js').pipe(execa('--version')));50-});51-52-test('execaNode().pipe(...) requires using "node"', async t => {53- await t.throwsAsync(execaNode('noop.js').pipe('--version'));54-});55-56-test('execaNode().pipe`...` requires using "node"', async t => {57- await t.throwsAsync(execaNode('noop.js').pipe`--version`);58-});59-60-test('execaNode() cannot set the "node" option to false', t => {61- t.throws(() => {62- execaNode('empty.js', {node: false});63- }, {message: /The "node" option cannot be false/});64-});65-66-const testDoubleNode = (t, nodePath, execaMethod) => {67- t.throws(() => {68- execaMethod(nodePath, ['noop.js']);69- }, {message: /does not need to be "node"/});70-};71-72-test('Cannot use "node" as binary - execaNode()', testDoubleNode, 'node', execaNode);73-test('Cannot use "node" as binary - "node" option', testDoubleNode, 'node', runWithNodeOption);74-test('Cannot use "node" as binary - "node" option sync', testDoubleNode, 'node', runWithNodeOptionSync);75-test('Cannot use path to "node" as binary - execaNode()', testDoubleNode, process.execPath, execaNode);76-test('Cannot use path to "node" as binary - "node" option', testDoubleNode, process.execPath, runWithNodeOption);77-test('Cannot use path to "node" as binary - "node" option sync', testDoubleNode, process.execPath, runWithNodeOptionSync);78-79-const getNodePath = async () => {80- const {path} = await getNode(TEST_NODE_VERSION);81- return path;82-};83-84-const TEST_NODE_VERSION = '16.0.0';85-86-const testNodePath = async (t, execaMethod, mapPath) => {87- const nodePath = mapPath(await getNodePath());88- const {stdout} = await execaMethod('--version', [], {nodePath});89- t.is(stdout, `v${TEST_NODE_VERSION}`);90-};91-92-test.serial('The "nodePath" option can be used - execaNode()', testNodePath, execaNode, identity);93-test.serial('The "nodePath" option can be a file URL - execaNode()', testNodePath, execaNode, pathToFileURL);94-test.serial('The "nodePath" option can be used - "node" option', testNodePath, runWithNodeOption, identity);95-test.serial('The "nodePath" option can be a file URL - "node" option', testNodePath, runWithNodeOption, pathToFileURL);96-test.serial('The "nodePath" option can be used - "node" option sync', testNodePath, runWithNodeOptionSync, identity);97-test.serial('The "nodePath" option can be a file URL - "node" option sync', testNodePath, runWithNodeOptionSync, pathToFileURL);98-99-const testNodePathDefault = async (t, execaMethod) => {100- const {stdout} = await execaMethod('--version');101- t.is(stdout, process.version);102-};103-104-test('The "nodePath" option defaults to the current Node.js binary - execaNode()', testNodePathDefault, execaNode);105-test('The "nodePath" option defaults to the current Node.js binary - "node" option', testNodePathDefault, runWithNodeOption);106-test('The "nodePath" option defaults to the current Node.js binary - "node" option sync', testNodePathDefault, runWithNodeOptionSync);107-108-const testNodePathInvalid = (t, execaMethod) => {109- t.throws(() => {110- execaMethod('noop.js', [], {nodePath: true});111- }, {message: /The "nodePath" option must be a string or a file URL/});112-};113-114-test('The "nodePath" option must be a string or URL - execaNode()', testNodePathInvalid, execaNode);115-test('The "nodePath" option must be a string or URL - "node" option', testNodePathInvalid, runWithNodeOption);116-test('The "nodePath" option must be a string or URL - "node" option sync', testNodePathInvalid, runWithNodeOptionSync);117-118-const testFormerNodePath = (t, execaMethod) => {119- t.throws(() => {120- execaMethod('noop.js', [], {execPath: process.execPath});121- }, {message: /The "execPath" option has been removed/});122-};123-124-test('The "execPath" option cannot be used - execaNode()', testFormerNodePath, execaNode);125-test('The "execPath" option cannot be used - "node" option', testFormerNodePath, runWithNodeOption);126-test('The "execPath" option cannot be used - "node" option sync', testFormerNodePath, runWithNodeOptionSync);127-128-const nodePathArguments = ['-p', ['process.env.Path || process.env.PATH']];129-130-const testSubprocessNodePath = async (t, execaMethod, mapPath) => {131- const nodePath = mapPath(await getNodePath());132- const {stdout} = await execaMethod(...nodePathArguments, {nodePath});133- t.true(stdout.includes(TEST_NODE_VERSION));134-};135-136-test.serial('The "nodePath" option impacts the subprocess - execaNode()', testSubprocessNodePath, execaNode, identity);137-test.serial('The "nodePath" option impacts the subprocess - "node" option', testSubprocessNodePath, runWithNodeOption, identity);138-test.serial('The "nodePath" option impacts the subprocess - "node" option sync', testSubprocessNodePath, runWithNodeOptionSync, identity);139-140-const testSubprocessNodePathDefault = async (t, execaMethod) => {141- const {stdout} = await execaMethod(...nodePathArguments);142- t.true(stdout.includes(dirname(process.execPath)));143-};144-145-test('The "nodePath" option defaults to the current Node.js binary in the subprocess - execaNode()', testSubprocessNodePathDefault, execaNode);146-test('The "nodePath" option defaults to the current Node.js binary in the subprocess - "node" option', testSubprocessNodePathDefault, runWithNodeOption);147-test('The "nodePath" option defaults to the current Node.js binary in the subprocess - "node" option sync', testSubprocessNodePathDefault, runWithNodeOptionSync);148-149-test.serial('The "nodePath" option requires "node: true" to impact the subprocess', async t => {150- const nodePath = await getNodePath();151- const {stdout} = await execa('node', nodePathArguments.flat(), {nodePath});152- t.false(stdout.includes(TEST_NODE_VERSION));153-});154-155-const testSubprocessNodePathCwd = async (t, execaMethod) => {156- const nodePath = await getNodePath();157- const cwd = dirname(dirname(nodePath));158- const relativeExecPath = relative(cwd, nodePath);159- const {stdout} = await execaMethod(...nodePathArguments, {nodePath: relativeExecPath, cwd});160- t.true(stdout.includes(TEST_NODE_VERSION));161-};162-163-test.serial('The "nodePath" option is relative to "cwd" when used in the subprocess - execaNode()', testSubprocessNodePathCwd, execaNode);164-test.serial('The "nodePath" option is relative to "cwd" when used in the subprocess - "node" option', testSubprocessNodePathCwd, runWithNodeOption);165-test.serial('The "nodePath" option is relative to "cwd" when used in the subprocess - "node" option sync', testSubprocessNodePathCwd, runWithNodeOptionSync);166-167-const testCwdNodePath = async (t, execaMethod) => {168- const nodePath = await getNodePath();169- const cwd = dirname(dirname(nodePath));170- const relativeExecPath = relative(cwd, nodePath);171- const {stdout} = await execaMethod('--version', [], {nodePath: relativeExecPath, cwd});172- t.is(stdout, `v${TEST_NODE_VERSION}`);173-};174-175-test.serial('The "nodePath" option is relative to "cwd" - execaNode()', testCwdNodePath, execaNode);176-test.serial('The "nodePath" option is relative to "cwd" - "node" option', testCwdNodePath, runWithNodeOption);177-test.serial('The "nodePath" option is relative to "cwd" - "node" option sync', testCwdNodePath, runWithNodeOptionSync);178-179-const testNodeOptions = async (t, execaMethod) => {180- const {stdout} = await execaMethod('empty.js', [], {nodeOptions: ['--version']});181- t.is(stdout, process.version);182-};183-184-test('The "nodeOptions" option can be used - execaNode()', testNodeOptions, execaNode);185-test('The "nodeOptions" option can be used - "node" option', testNodeOptions, runWithNodeOption);186-test('The "nodeOptions" option can be used - "node" option sync', testNodeOptions, runWithNodeOptionSync);187-188-const spawnNestedExecaNode = (realExecArgv, fakeExecArgv, execaMethod, nodeOptions) => execa(189- 'node',190- [...realExecArgv, 'nested-node.js', fakeExecArgv, execaMethod, nodeOptions, 'noop.js', foobarString],191- {...fullStdio, cwd: FIXTURES_DIR},192-);193-194-const testInspectRemoval = async (t, fakeExecArgv, execaMethod) => {195- const {stdout, stdio} = await spawnNestedExecaNode([], fakeExecArgv, execaMethod, '');196- t.is(stdout, foobarString);197- t.is(stdio[3], '');198-};199-200-test('The "nodeOptions" option removes --inspect without a port when defined by current process - execaNode()', testInspectRemoval, '--inspect', 'execaNode');201-test('The "nodeOptions" option removes --inspect without a port when defined by current process - "node" option', testInspectRemoval, '--inspect', 'nodeOption');202-test('The "nodeOptions" option removes --inspect with a port when defined by current process - execaNode()', testInspectRemoval, '--inspect=9222', 'execaNode');203-test('The "nodeOptions" option removes --inspect with a port when defined by current process - "node" option', testInspectRemoval, '--inspect=9222', 'nodeOption');204-test('The "nodeOptions" option removes --inspect-brk without a port when defined by current process - execaNode()', testInspectRemoval, '--inspect-brk', 'execaNode');205-test('The "nodeOptions" option removes --inspect-brk without a port when defined by current process - "node" option', testInspectRemoval, '--inspect-brk', 'nodeOption');206-test('The "nodeOptions" option removes --inspect-brk with a port when defined by current process - execaNode()', testInspectRemoval, '--inspect-brk=9223', 'execaNode');207-test('The "nodeOptions" option removes --inspect-brk with a port when defined by current process - "node" option', testInspectRemoval, '--inspect-brk=9223', 'nodeOption');208-209-const testInspectDifferentPort = async (t, execaMethod) => {210- const {stdout, stdio} = await spawnNestedExecaNode(['--inspect=9225'], '', execaMethod, '--inspect=9224');211- t.is(stdout, foobarString);212- t.true(stdio[3].includes('Debugger listening'));213-};214-215-test.serial('The "nodeOptions" option allows --inspect with a different port even when defined by current process - execaNode()', testInspectDifferentPort, 'execaNode');216-test.serial('The "nodeOptions" option allows --inspect with a different port even when defined by current process - "node" option', testInspectDifferentPort, 'nodeOption');217-218-const testInspectSamePort = async (t, execaMethod) => {219- const {stdout, stdio} = await spawnNestedExecaNode(['--inspect=9226'], '', execaMethod, '--inspect=9226');220- t.is(stdout, foobarString);221- t.true(stdio[3].includes('address already in use'));222-};223-224-test.serial('The "nodeOptions" option forbids --inspect with the same port when defined by current process - execaNode()', testInspectSamePort, 'execaNode');225-test.serial('The "nodeOptions" option forbids --inspect with the same port when defined by current process - "node" option', testInspectSamePort, 'nodeOption');226-227-const testIpc = async (t, execaMethod, options) => {228- const subprocess = execaMethod('send.js', [], options);229- await pEvent(subprocess, 'message');230- subprocess.send(foobarString);231- const {stdout, stdio} = await subprocess;232- t.is(stdout, foobarString);233- t.is(stdio.length, 4);234- t.is(stdio[3], undefined);235-};236-237-test('execaNode() adds an ipc channel', testIpc, execaNode, {});238-test('The "node" option adds an ipc channel', testIpc, runWithNodeOption, {});239-test('The "ipc" option adds an ipc channel', testIpc, runWithIpc, {});240-test('The "ipc" option works with "stdio: \'pipe\'"', testIpc, runWithIpc, {stdio: 'pipe'});241-test('The "ipc" option works with "stdio: [\'pipe\', \'pipe\', \'pipe\']"', testIpc, runWithIpc, {stdio: ['pipe', 'pipe', 'pipe']});242-test('The "ipc" option works with "stdio: [\'pipe\', \'pipe\', \'pipe\', \'ipc\']"', testIpc, runWithIpc, {stdio: ['pipe', 'pipe', 'pipe', 'ipc']});243-test('The "ipc" option works with "stdout: \'pipe\'"', testIpc, runWithIpc, {stdout: 'pipe'});244-245-test('No ipc channel is added by default', async t => {246- const {stdio} = await t.throwsAsync(execa('node', ['send.js']), {message: /process.send is not a function/});247- t.is(stdio.length, 3);248-});249-250-const testDisableIpc = async (t, execaMethod) => {251- const {failed, message, stdio} = await execaMethod('send.js', [], {ipc: false, reject: false});252- t.true(failed);253- t.true(message.includes('process.send is not a function'));254- t.is(stdio.length, 3);255-};256-257-test('Can disable "ipc" - execaNode()', testDisableIpc, execaNode);258-test('Can disable "ipc" - "node" option', testDisableIpc, runWithNodeOption);259-test('Can disable "ipc" - "node" option sync', testDisableIpc, runWithNodeOptionSync);260-261-const NO_IPC_MESSAGE = /The "ipc: true" option cannot be used/;262-263-const testNoIpcSync = (t, node) => {264- t.throws(() => {265- execaSync('node', ['send.js'], {ipc: true, node});266- }, {message: NO_IPC_MESSAGE});267-};268-269-test('Cannot use "ipc: true" with execaSync()', testNoIpcSync, undefined);270-test('Cannot use "ipc: true" with execaSync() - "node: false"', testNoIpcSync, false);271-272-test('Cannot use "ipc: true" with execaSync() - "node: true"', t => {273- t.throws(() => {274- execaSync('send.js', {ipc: true, node: true});275- }, {message: NO_IPC_MESSAGE});276-});277-278-const testNoShell = async (t, execaMethod) => {279- const {failed, message} = await execaMethod('node --version', [], {shell: true, reject: false});280- t.true(failed);281- t.true(message.includes('MODULE_NOT_FOUND'));282-};283-284-test('Cannot use "shell: true" - execaNode()', testNoShell, execaNode);285-test('Cannot use "shell: true" - "node" option', testNoShell, runWithNodeOption);286-test('Cannot use "shell: true" - "node" option sync', testNoShell, runWithNodeOptionSync);287-288-test('The "serialization" option defaults to "advanced"', async t => {289- const subprocess = execa('node', ['ipc-echo.js'], {ipc: true});290- subprocess.send([0n]);291- const [message] = await once(subprocess, 'message');292- t.is(message[0], 0n);293- await subprocess;294-});295-296-test('The "serialization" option can be set to "json"', async t => {297- const subprocess = execa('node', ['ipc-echo.js'], {ipc: true, serialization: 'json'});298- t.throws(() => {299- subprocess.send([0n]);300- }, {message: /serialize a BigInt/});301- subprocess.send(0);302- const [message] = await once(subprocess, 'message');303- t.is(message, 0);304- await subprocess;305-});deleted:test/arguments/normalize-args.js-47 removed
1-import test from 'ava';2-import {execa, execaSync, execaCommand, execaCommandSync, execaNode, $} from '../../index.js';3-import {setFixtureDir} from '../helpers/fixtures-dir.js';4-5-setFixtureDir();6-7-const testInvalidArgs = async (t, execaMethod) => {8- t.throws(() => {9- execaMethod('echo', true);10- }, {message: /Second argument must be either/});11-};12-13-test('execa()\'s second argument must be valid', testInvalidArgs, execa);14-test('execaSync()\'s second argument must be valid', testInvalidArgs, execaSync);15-test('execaCommand()\'s second argument must be valid', testInvalidArgs, execaCommand);16-test('execaCommandSync()\'s second argument must be valid', testInvalidArgs, execaCommandSync);17-test('execaNode()\'s second argument must be valid', testInvalidArgs, execaNode);18-test('$\'s second argument must be valid', testInvalidArgs, $);19-test('$.sync\'s second argument must be valid', testInvalidArgs, $.sync);20-21-const testInvalidArgsItems = async (t, execaMethod) => {22- t.throws(() => {23- execaMethod('echo', [{}]);24- }, {message: 'Second argument must be an array of strings: [object Object]'});25-};26-27-test('execa()\'s second argument must not be objects', testInvalidArgsItems, execa);28-test('execaSync()\'s second argument must not be objects', testInvalidArgsItems, execaSync);29-test('execaCommand()\'s second argument must not be objects', testInvalidArgsItems, execaCommand);30-test('execaCommandSync()\'s second argument must not be objects', testInvalidArgsItems, execaCommandSync);31-test('execaNode()\'s second argument must not be objects', testInvalidArgsItems, execaNode);32-test('$\'s second argument must not be objects', testInvalidArgsItems, $);33-test('$.sync\'s second argument must not be objects', testInvalidArgsItems, $.sync);34-35-const testNullByteArg = async (t, execaMethod) => {36- t.throws(() => {37- execaMethod('echo', ['a\0b']);38- }, {message: /null bytes/});39-};40-41-test('execa()\'s second argument must not include \\0', testNullByteArg, execa);42-test('execaSync()\'s second argument must not include \\0', testNullByteArg, execaSync);43-test('execaCommand()\'s second argument must not include \\0', testNullByteArg, execaCommand);44-test('execaCommandSync()\'s second argument must not include \\0', testNullByteArg, execaCommandSync);45-test('execaNode()\'s second argument must not include \\0', testNullByteArg, execaNode);46-test('$\'s second argument must not include \\0', testNullByteArg, $);47-test('$.sync\'s second argument must not include \\0', testNullByteArg, $.sync);deleted:test/arguments/normalize-command.js-80 removed
1-import {join, basename} from 'node:path';2-import {fileURLToPath} from 'node:url';3-import test from 'ava';4-import {execa, execaSync, execaCommand, execaCommandSync, execaNode, $} from '../../index.js';5-import {setFixtureDir, FIXTURES_DIR_URL} from '../helpers/fixtures-dir.js';6-import {foobarString} from '../helpers/input.js';7-8-setFixtureDir();9-10-const testFileUrl = async (t, execaMethod) => {11- const command = new URL('noop.js', FIXTURES_DIR_URL);12- const {stdout} = await execaMethod(command);13- t.is(stdout, foobarString);14-};15-16-test('execa()\'s command argument can be a file URL', testFileUrl, execa);17-test('execaSync()\'s command argument can be a file URL', testFileUrl, execaSync);18-test('execaCommand()\'s command argument can be a file URL', testFileUrl, execaCommand);19-test('execaCommandSync()\'s command argument can be a file URL', testFileUrl, execaCommandSync);20-test('execaNode()\'s command argument can be a file URL', testFileUrl, execaNode);21-test('$\'s command argument can be a file URL', testFileUrl, $);22-test('$.sync\'s command argument can be a file URL', testFileUrl, $.sync);23-24-const testInvalidFileUrl = async (t, execaMethod) => {25- const invalidUrl = new URL('https://invalid.com');26- t.throws(() => {27- execaMethod(invalidUrl);28- }, {code: 'ERR_INVALID_URL_SCHEME'});29-};30-31-test('execa()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execa);32-test('execaSync()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execaSync);33-test('execaCommand()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execaCommand);34-test('execaCommandSync()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execaCommandSync);35-test('execaNode()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execaNode);36-test('$\'s command argument cannot be a non-file URL', testInvalidFileUrl, $);37-test('$.sync\'s command argument cannot be a non-file URL', testInvalidFileUrl, $.sync);38-39-const testInvalidCommand = async (t, arg, execaMethod) => {40- t.throws(() => {41- execaMethod(arg);42- }, {message: /First argument must be a string or a file URL/});43-};44-45-test('execa()\'s first argument must be defined', testInvalidCommand, undefined, execa);46-test('execaSync()\'s first argument must be defined', testInvalidCommand, undefined, execaSync);47-test('execaCommand()\'s first argument must be defined', testInvalidCommand, undefined, execaCommand);48-test('execaCommandSync()\'s first argument must be defined', testInvalidCommand, undefined, execaCommandSync);49-test('execaNode()\'s first argument must be defined', testInvalidCommand, undefined, execaNode);50-test('$\'s first argument must be defined', testInvalidCommand, undefined, $);51-test('$.sync\'s first argument must be defined', testInvalidCommand, undefined, $.sync);52-test('execa()\'s first argument must be valid', testInvalidCommand, true, execa);53-test('execaSync()\'s first argument must be valid', testInvalidCommand, true, execaSync);54-test('execaCommand()\'s first argument must be valid', testInvalidCommand, true, execaCommand);55-test('execaCommandSync()\'s first argument must be valid', testInvalidCommand, true, execaCommandSync);56-test('execaNode()\'s first argument must be valid', testInvalidCommand, true, execaNode);57-test('$\'s first argument must be valid', testInvalidCommand, true, $);58-test('$.sync\'s first argument must be valid', testInvalidCommand, true, $.sync);59-test('execa()\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], execa);60-test('execaSync()\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], execaSync);61-test('execaCommand()\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], execaCommand);62-test('execaCommandSync()\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], execaCommandSync);63-test('execaNode()\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], execaNode);64-test('$\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], $);65-test('$.sync\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], $.sync);66-67-const testRelativePath = async (t, execaMethod) => {68- const rootDir = basename(fileURLToPath(new URL('../..', import.meta.url)));69- const pathViaParentDir = join('..', rootDir, 'test', 'fixtures', 'noop.js');70- const {stdout} = await execaMethod(pathViaParentDir);71- t.is(stdout, foobarString);72-};73-74-test('execa() use relative path with \'..\' chars', testRelativePath, execa);75-test('execaSync() use relative path with \'..\' chars', testRelativePath, execaSync);76-test('execaCommand() use relative path with \'..\' chars', testRelativePath, execaCommand);77-test('execaCommandSync() use relative path with \'..\' chars', testRelativePath, execaCommandSync);78-test('execaNode() use relative path with \'..\' chars', testRelativePath, execaNode);79-test('$ use relative path with \'..\' chars', testRelativePath, $);80-test('$.sync use relative path with \'..\' chars', testRelativePath, $.sync);deleted:test/arguments/normalize-options.js-68 removed
1-import {join} from 'node:path';2-import test from 'ava';3-import {execa, execaSync, execaCommand, execaCommandSync, execaNode, $} from '../../index.js';4-import {setFixtureDir, FIXTURES_DIR} from '../helpers/fixtures-dir.js';5-6-setFixtureDir();7-8-const NOOP_PATH = join(FIXTURES_DIR, 'noop.js');9-10-const testSerializeArg = async (t, arg, execaMethod) => {11- const {stdout} = await execaMethod(NOOP_PATH, [arg]);12- t.is(stdout, String(arg));13-};14-15-test('execa()\'s arguments can be numbers', testSerializeArg, 1, execa);16-test('execa()\'s arguments can be booleans', testSerializeArg, true, execa);17-test('execa()\'s arguments can be NaN', testSerializeArg, Number.NaN, execa);18-test('execa()\'s arguments can be Infinity', testSerializeArg, Number.POSITIVE_INFINITY, execa);19-test('execa()\'s arguments can be null', testSerializeArg, null, execa);20-test('execa()\'s arguments can be undefined', testSerializeArg, undefined, execa);21-test('execa()\'s arguments can be bigints', testSerializeArg, 1n, execa);22-test('execa()\'s arguments can be symbols', testSerializeArg, Symbol('test'), execa);23-test('execaSync()\'s arguments can be numbers', testSerializeArg, 1, execaSync);24-test('execaSync()\'s arguments can be booleans', testSerializeArg, true, execaSync);25-test('execaSync()\'s arguments can be NaN', testSerializeArg, Number.NaN, execaSync);26-test('execaSync()\'s arguments can be Infinity', testSerializeArg, Number.POSITIVE_INFINITY, execaSync);27-test('execaSync()\'s arguments can be null', testSerializeArg, null, execaSync);28-test('execaSync()\'s arguments can be undefined', testSerializeArg, undefined, execaSync);29-test('execaSync()\'s arguments can be bigints', testSerializeArg, 1n, execaSync);30-test('execaSync()\'s arguments can be symbols', testSerializeArg, Symbol('test'), execaSync);31-test('execaNode()\'s arguments can be numbers', testSerializeArg, 1, execaNode);32-test('execaNode()\'s arguments can be booleans', testSerializeArg, true, execaNode);33-test('execaNode()\'s arguments can be NaN', testSerializeArg, Number.NaN, execaNode);34-test('execaNode()\'s arguments can be Infinity', testSerializeArg, Number.POSITIVE_INFINITY, execaNode);35-test('execaNode()\'s arguments can be null', testSerializeArg, null, execaNode);36-test('execaNode()\'s arguments can be undefined', testSerializeArg, undefined, execaNode);37-test('execaNode()\'s arguments can be bigints', testSerializeArg, 1n, execaNode);38-test('execaNode()\'s arguments can be symbols', testSerializeArg, Symbol('test'), execaNode);39-test('$\'s arguments can be numbers', testSerializeArg, 1, $);40-test('$\'s arguments can be booleans', testSerializeArg, true, $);41-test('$\'s arguments can be NaN', testSerializeArg, Number.NaN, $);42-test('$\'s arguments can be Infinity', testSerializeArg, Number.POSITIVE_INFINITY, $);43-test('$\'s arguments can be null', testSerializeArg, null, $);44-test('$\'s arguments can be undefined', testSerializeArg, undefined, $);45-test('$\'s arguments can be bigints', testSerializeArg, 1n, $);46-test('$\'s arguments can be symbols', testSerializeArg, Symbol('test'), $);47-test('$.sync\'s arguments can be numbers', testSerializeArg, 1, $.sync);48-test('$.sync\'s arguments can be booleans', testSerializeArg, true, $.sync);49-test('$.sync\'s arguments can be NaN', testSerializeArg, Number.NaN, $.sync);50-test('$.sync\'s arguments can be Infinity', testSerializeArg, Number.POSITIVE_INFINITY, $.sync);51-test('$.sync\'s arguments can be null', testSerializeArg, null, $.sync);52-test('$.sync\'s arguments can be undefined', testSerializeArg, undefined, $.sync);53-test('$.sync\'s arguments can be bigints', testSerializeArg, 1n, $.sync);54-test('$.sync\'s arguments can be symbols', testSerializeArg, Symbol('test'), $.sync);55-56-const testInvalidOptions = async (t, execaMethod) => {57- t.throws(() => {58- execaMethod('echo', [], new Map());59- }, {message: /Last argument must be an options object/});60-};61-62-test('execa()\'s third argument must be a plain object', testInvalidOptions, execa);63-test('execaSync()\'s third argument must be a plain object', testInvalidOptions, execaSync);64-test('execaCommand()\'s third argument must be a plain object', testInvalidOptions, execaCommand);65-test('execaCommandSync()\'s third argument must be a plain object', testInvalidOptions, execaCommandSync);66-test('execaNode()\'s third argument must be a plain object', testInvalidOptions, execaNode);67-test('$\'s third argument must be a plain object', testInvalidOptions, $);68-test('$.sync\'s third argument must be a plain object', testInvalidOptions, $.sync);deleted:test/arguments/template.js-329 removed
1-import test from 'ava';2-import {$} from '../../index.js';3-import {setFixtureDir} from '../helpers/fixtures-dir.js';4-5-setFixtureDir();6-7-// Workaround since some text editors or IDEs do not allow inputting \r directly8-const escapedCall = string => {9- const templates = [string];10- templates.raw = [string];11- return $(templates);12-};13-14-const testScriptStdout = async (t, getSubprocess, expectedStdout) => {15- const {stdout} = await getSubprocess();16- t.is(stdout, expectedStdout);17-};18-19-test('$ allows number interpolation', testScriptStdout, () => $`echo.js 1 ${2}`, '1\n2');20-test('$ can concatenate multiple tokens', testScriptStdout, () => $`echo.js ${'foo'}bar${'foo'}`, 'foobarfoo');21-test('$ can use newlines and tab indentations', testScriptStdout, () => $`echo.js foo22- bar`, 'foo\nbar');23-test('$ can use newlines and space indentations', testScriptStdout, () => $`echo.js foo24- bar`, 'foo\nbar');25-test('$ can use Windows newlines and tab indentations', testScriptStdout, () => escapedCall('echo.js foo\r\n\tbar'), 'foo\nbar');26-test('$ can use Windows newlines and space indentations', testScriptStdout, () => escapedCall('echo.js foo\r\n bar'), 'foo\nbar');27-test('$ does not ignore comments in expressions', testScriptStdout, () => $`echo.js foo28- ${/* This is a comment */''}29- bar30- ${/* This is another comment */''}31- baz32-`, 'foo\n\nbar\n\nbaz');33-test('$ allows escaping spaces with interpolation', testScriptStdout, () => $`echo.js ${'foo bar'}`, 'foo bar');34-test('$ allows escaping spaces in commands with interpolation', testScriptStdout, () => $`${'command with space.js'} foo bar`, 'foo\nbar');35-test('$ trims', testScriptStdout, () => $` echo.js foo bar `, 'foo\nbar');36-test('$ allows array interpolation', testScriptStdout, () => $`echo.js ${['foo', 'bar']}`, 'foo\nbar');37-test('$ allows empty array interpolation', testScriptStdout, () => $`echo.js foo ${[]} bar`, 'foo\nbar');38-test('$ allows space escaped values in array interpolation', testScriptStdout, () => $`echo.js ${['foo', 'bar baz']}`, 'foo\nbar baz');39-test('$ can concatenate at the end of tokens followed by an array', testScriptStdout, () => $`echo.js foo${['bar', 'foo']}`, 'foobar\nfoo');40-test('$ can concatenate at the start of tokens followed by an array', testScriptStdout, () => $`echo.js ${['foo', 'bar']}foo`, 'foo\nbarfoo');41-test('$ can concatenate at the start and end of tokens followed by an array', testScriptStdout, () => $`echo.js foo${['bar', 'foo']}bar`, 'foobar\nfoobar');42-test('$ handles escaped newlines', testScriptStdout, () => $`echo.js a\43-b`, 'ab');44-test('$ handles backslashes at end of lines', testScriptStdout, () => $`echo.js a\\45- b`, 'a\\\nb');46-test('$ handles double backslashes at end of lines', testScriptStdout, () => $`echo.js a\\\\47- b`, 'a\\\\\nb');48-test('$ handles tokens - a', testScriptStdout, () => $`echo.js a`, 'a');49-test('$ handles expressions - a', testScriptStdout, () => $`echo.js ${'a'}`, 'a');50-test('$ handles tokens - abc', testScriptStdout, () => $`echo.js abc`, 'abc');51-test('$ handles expressions - abc', testScriptStdout, () => $`echo.js ${'abc'}`, 'abc');52-test('$ handles tokens - ""', testScriptStdout, () => $`echo.js`, '');53-test('$ handles expressions - ""', testScriptStdout, () => $`echo.js a ${''} b`, 'a\n\nb');54-test('$ splits tokens - ""', testScriptStdout, () => $`echo.js ab`, 'ab');55-test('$ splits expressions - ""', testScriptStdout, () => $`echo.js ${'a'}${'b'}`, 'ab');56-test('$ concatenates expressions - ""', testScriptStdout, () => $`echo.js a${'b'}c`, 'abc');57-test('$ handles tokens - " "', testScriptStdout, () => $`echo.js `, '');58-test('$ handles expressions - " "', testScriptStdout, () => $`echo.js ${' '}`, ' ');59-test('$ splits tokens - " "', testScriptStdout, () => $`echo.js a b`, 'a\nb');60-test('$ splits expressions - " "', testScriptStdout, () => $`echo.js ${'a'} ${'b'}`, 'a\nb');61-test('$ concatenates tokens - " "', testScriptStdout, () => $`echo.js a `, 'a');62-test('$ concatenates expressions - " "', testScriptStdout, () => $`echo.js ${'a'} `, 'a');63-test('$ handles tokens - " " (2 spaces)', testScriptStdout, () => $`echo.js `, '');64-test('$ handles expressions - " " (2 spaces)', testScriptStdout, () => $`echo.js ${' '}`, ' ');65-test('$ splits tokens - " " (2 spaces)', testScriptStdout, () => $`echo.js a b`, 'a\nb');66-test('$ splits expressions - " " (2 spaces)', testScriptStdout, () => $`echo.js ${'a'} ${'b'}`, 'a\nb');67-test('$ concatenates tokens - " " (2 spaces)', testScriptStdout, () => $`echo.js a `, 'a');68-test('$ concatenates expressions - " " (2 spaces)', testScriptStdout, () => $`echo.js ${'a'} `, 'a');69-test('$ handles tokens - " " (3 spaces)', testScriptStdout, () => $`echo.js `, '');70-test('$ handles expressions - " " (3 spaces)', testScriptStdout, () => $`echo.js ${' '}`, ' ');71-test('$ splits tokens - " " (3 spaces)', testScriptStdout, () => $`echo.js a b`, 'a\nb');72-test('$ splits expressions - " " (3 spaces)', testScriptStdout, () => $`echo.js ${'a'} ${'b'}`, 'a\nb');73-test('$ concatenates tokens - " " (3 spaces)', testScriptStdout, () => $`echo.js a `, 'a');74-test('$ concatenates expressions - " " (3 spaces)', testScriptStdout, () => $`echo.js ${'a'} `, 'a');75-test('$ handles tokens - \\t (no escape)', testScriptStdout, () => $`echo.js `, '');76-test('$ handles expressions - \\t (no escape)', testScriptStdout, () => $`echo.js ${' '}`, '\t');77-test('$ splits tokens - \\t (no escape)', testScriptStdout, () => $`echo.js a b`, 'a\nb');78-test('$ splits expressions - \\t (no escape)', testScriptStdout, () => $`echo.js ${'a'} ${'b'}`, 'a\nb');79-test('$ concatenates tokens - \\t (no escape)', testScriptStdout, () => $`echo.js a b`, 'a\nb');80-test('$ concatenates expressions - \\t (no escape)', testScriptStdout, () => $`echo.js ${'a'} b`, 'a\nb');81-test('$ handles tokens - \\t (escape)', testScriptStdout, () => $`echo.js \t`, '\t');82-test('$ handles expressions - \\t (escape)', testScriptStdout, () => $`echo.js ${'\t'}`, '\t');83-test('$ splits tokens - \\t (escape)', testScriptStdout, () => $`echo.js a\tb`, 'a\tb');84-test('$ splits expressions - \\t (escape)', testScriptStdout, () => $`echo.js ${'a'}\t${'b'}`, 'a\tb');85-test('$ concatenates tokens - \\t (escape)', testScriptStdout, () => $`echo.js \ta\t b`, '\ta\t\nb');86-test('$ concatenates expressions - \\t (escape)', testScriptStdout, () => $`echo.js \t${'a'}\t b`, '\ta\t\nb');87-test('$ handles tokens - \\n (no escape)', testScriptStdout, () => $`echo.js88- `, '');89-test('$ handles expressions - \\n (no escape)', testScriptStdout, () => $`echo.js ${`90-`} `, '\n');91-test('$ splits tokens - \\n (no escape)', testScriptStdout, () => $`echo.js a92- b`, 'a\nb');93-test('$ splits expressions - \\n (no escape)', testScriptStdout, () => $`echo.js ${'a'}94- ${'b'}`, 'a\nb');95-test('$ concatenates tokens - \\n (no escape)', testScriptStdout, () => $`echo.js96-a97- b`, 'a\nb');98-test('$ concatenates expressions - \\n (no escape)', testScriptStdout, () => $`echo.js99-${'a'}100- b`, 'a\nb');101-test('$ handles tokens - \\n (escape)', testScriptStdout, () => $`echo.js \n `, '\n');102-test('$ handles expressions - \\n (escape)', testScriptStdout, () => $`echo.js ${'\n'} `, '\n');103-test('$ splits tokens - \\n (escape)', testScriptStdout, () => $`echo.js a\n b`, 'a\n\nb');104-test('$ splits expressions - \\n (escape)', testScriptStdout, () => $`echo.js ${'a'}\n ${'b'}`, 'a\n\nb');105-test('$ concatenates tokens - \\n (escape)', testScriptStdout, () => $`echo.js \na\n b`, '\na\n\nb');106-test('$ concatenates expressions - \\n (escape)', testScriptStdout, () => $`echo.js \n${'a'}\n b`, '\na\n\nb');107-test('$ handles tokens - \\r (no escape)', testScriptStdout, () => escapedCall('echo.js \r '), '');108-test('$ splits tokens - \\r (no escape)', testScriptStdout, () => escapedCall('echo.js a\rb'), 'a\nb');109-test('$ splits expressions - \\r (no escape)', testScriptStdout, () => escapedCall(`echo.js ${'a'}\r${'b'}`), 'a\nb');110-test('$ concatenates tokens - \\r (no escape)', testScriptStdout, () => escapedCall('echo.js \ra\r b'), 'a\nb');111-test('$ concatenates expressions - \\r (no escape)', testScriptStdout, () => escapedCall(`echo.js \r${'a'}\r b`), 'a\nb');112-test('$ splits tokens - \\r (escape)', testScriptStdout, () => $`echo.js a\r b`, 'a\r\nb');113-test('$ splits expressions - \\r (escape)', testScriptStdout, () => $`echo.js ${'a'}\r ${'b'}`, 'a\r\nb');114-test('$ concatenates tokens - \\r (escape)', testScriptStdout, () => $`echo.js \ra\r b`, '\ra\r\nb');115-test('$ concatenates expressions - \\r (escape)', testScriptStdout, () => $`echo.js \r${'a'}\r b`, '\ra\r\nb');116-test('$ handles tokens - \\r\\n (no escape)', testScriptStdout, () => escapedCall('echo.js \r\n '), '');117-test('$ splits tokens - \\r\\n (no escape)', testScriptStdout, () => escapedCall('echo.js a\r\nb'), 'a\nb');118-test('$ splits expressions - \\r\\n (no escape)', testScriptStdout, () => escapedCall(`echo.js ${'a'}\r\n${'b'}`), 'a\nb');119-test('$ concatenates tokens - \\r\\n (no escape)', testScriptStdout, () => escapedCall('echo.js \r\na\r\n b'), 'a\nb');120-test('$ concatenates expressions - \\r\\n (no escape)', testScriptStdout, () => escapedCall(`echo.js \r\n${'a'}\r\n b`), 'a\nb');121-test('$ handles tokens - \\r\\n (escape)', testScriptStdout, () => $`echo.js \r\n `, '\r\n');122-test('$ handles expressions - \\r\\n (escape)', testScriptStdout, () => $`echo.js ${'\r\n'} `, '\r\n');123-test('$ splits tokens - \\r\\n (escape)', testScriptStdout, () => $`echo.js a\r\n b`, 'a\r\n\nb');124-test('$ splits expressions - \\r\\n (escape)', testScriptStdout, () => $`echo.js ${'a'}\r\n ${'b'}`, 'a\r\n\nb');125-test('$ concatenates tokens - \\r\\n (escape)', testScriptStdout, () => $`echo.js \r\na\r\n b`, '\r\na\r\n\nb');126-test('$ concatenates expressions - \\r\\n (escape)', testScriptStdout, () => $`echo.js \r\n${'a'}\r\n b`, '\r\na\r\n\nb');127-/* eslint-disable no-irregular-whitespace */128-test('$ handles expressions - \\f (no escape)', testScriptStdout, () => $`echo.js ${''}`, '\f');129-test('$ splits tokens - \\f (no escape)', testScriptStdout, () => $`echo.js ab`, 'a\fb');130-test('$ splits expressions - \\f (no escape)', testScriptStdout, () => $`echo.js ${'a'}${'b'}`, 'a\fb');131-test('$ concatenates tokens - \\f (no escape)', testScriptStdout, () => $`echo.js a b`, '\fa\f\nb');132-test('$ concatenates expressions - \\f (no escape)', testScriptStdout, () => $`echo.js ${'a'} b`, '\fa\f\nb');133-/* eslint-enable no-irregular-whitespace */134-test('$ handles tokens - \\f (escape)', testScriptStdout, () => $`echo.js \f`, '\f');135-test('$ handles expressions - \\f (escape)', testScriptStdout, () => $`echo.js ${'\f'}`, '\f');136-test('$ splits tokens - \\f (escape)', testScriptStdout, () => $`echo.js a\fb`, 'a\fb');137-test('$ splits expressions - \\f (escape)', testScriptStdout, () => $`echo.js ${'a'}\f${'b'}`, 'a\fb');138-test('$ concatenates tokens - \\f (escape)', testScriptStdout, () => $`echo.js \fa\f b`, '\fa\f\nb');139-test('$ concatenates expressions - \\f (escape)', testScriptStdout, () => $`echo.js \f${'a'}\f b`, '\fa\f\nb');140-test('$ handles tokens - \\', testScriptStdout, () => $`echo.js \\`, '\\');141-test('$ handles expressions - \\', testScriptStdout, () => $`echo.js ${'\\'}`, '\\');142-test('$ splits tokens - \\', testScriptStdout, () => $`echo.js a\\b`, 'a\\b');143-test('$ splits expressions - \\', testScriptStdout, () => $`echo.js ${'a'}\\${'b'}`, 'a\\b');144-test('$ concatenates tokens - \\', testScriptStdout, () => $`echo.js \\a\\ b`, '\\a\\\nb');145-test('$ concatenates expressions - \\', testScriptStdout, () => $`echo.js \\${'a'}\\ b`, '\\a\\\nb');146-test('$ handles tokens - \\\\', testScriptStdout, () => $`echo.js \\\\`, '\\\\');147-test('$ handles expressions - \\\\', testScriptStdout, () => $`echo.js ${'\\\\'}`, '\\\\');148-test('$ splits tokens - \\\\', testScriptStdout, () => $`echo.js a\\\\b`, 'a\\\\b');149-test('$ splits expressions - \\\\', testScriptStdout, () => $`echo.js ${'a'}\\\\${'b'}`, 'a\\\\b');150-test('$ concatenates tokens - \\\\', testScriptStdout, () => $`echo.js \\\\a\\\\ b`, '\\\\a\\\\\nb');151-test('$ concatenates expressions - \\\\', testScriptStdout, () => $`echo.js \\\\${'a'}\\\\ b`, '\\\\a\\\\\nb');152-test('$ handles tokens - `', testScriptStdout, () => $`echo.js \``, '`');153-test('$ handles expressions - `', testScriptStdout, () => $`echo.js ${'`'}`, '`');154-test('$ splits tokens - `', testScriptStdout, () => $`echo.js a\`b`, 'a`b');155-test('$ splits expressions - `', testScriptStdout, () => $`echo.js ${'a'}\`${'b'}`, 'a`b');156-test('$ concatenates tokens - `', testScriptStdout, () => $`echo.js \`a\` b`, '`a`\nb');157-test('$ concatenates expressions - `', testScriptStdout, () => $`echo.js \`${'a'}\` b`, '`a`\nb');158-test('$ handles tokens - \\v', testScriptStdout, () => $`echo.js \v`, '\v');159-test('$ handles expressions - \\v', testScriptStdout, () => $`echo.js ${'\v'}`, '\v');160-test('$ splits tokens - \\v', testScriptStdout, () => $`echo.js a\vb`, 'a\vb');161-test('$ splits expressions - \\v', testScriptStdout, () => $`echo.js ${'a'}\v${'b'}`, 'a\vb');162-test('$ concatenates tokens - \\v', testScriptStdout, () => $`echo.js \va\v b`, '\va\v\nb');163-test('$ concatenates expressions - \\v', testScriptStdout, () => $`echo.js \v${'a'}\v b`, '\va\v\nb');164-test('$ handles tokens - \\u2028', testScriptStdout, () => $`echo.js \u2028`, '\u2028');165-test('$ handles expressions - \\u2028', testScriptStdout, () => $`echo.js ${'\u2028'}`, '\u2028');166-test('$ splits tokens - \\u2028', testScriptStdout, () => $`echo.js a\u2028b`, 'a\u2028b');167-test('$ splits expressions - \\u2028', testScriptStdout, () => $`echo.js ${'a'}\u2028${'b'}`, 'a\u2028b');168-test('$ concatenates tokens - \\u2028', testScriptStdout, () => $`echo.js \u2028a\u2028 b`, '\u2028a\u2028\nb');169-test('$ concatenates expressions - \\u2028', testScriptStdout, () => $`echo.js \u2028${'a'}\u2028 b`, '\u2028a\u2028\nb');170-test('$ handles tokens - \\a', testScriptStdout, () => $`echo.js \a`, 'a');171-test('$ splits tokens - \\a', testScriptStdout, () => $`echo.js a\ab`, 'aab');172-test('$ splits expressions - \\a', testScriptStdout, () => $`echo.js ${'a'}\a${'b'}`, 'aab');173-test('$ concatenates tokens - \\a', testScriptStdout, () => $`echo.js \aa\a b`, 'aaa\nb');174-test('$ concatenates expressions - \\a', testScriptStdout, () => $`echo.js \a${'a'}\a b`, 'aaa\nb');175-test('$ handles tokens - \\cJ', testScriptStdout, () => $`echo.js \cJ`, 'cJ');176-test('$ splits tokens - \\cJ', testScriptStdout, () => $`echo.js a\cJb`, 'acJb');177-test('$ splits expressions - \\cJ', testScriptStdout, () => $`echo.js ${'a'}\cJ${'b'}`, 'acJb');178-test('$ concatenates tokens - \\cJ', testScriptStdout, () => $`echo.js \cJa\cJ b`, 'cJacJ\nb');179-test('$ concatenates expressions - \\cJ', testScriptStdout, () => $`echo.js \cJ${'a'}\cJ b`, 'cJacJ\nb');180-test('$ handles tokens - \\.', testScriptStdout, () => $`echo.js \.`, '.');181-test('$ splits tokens - \\.', testScriptStdout, () => $`echo.js a\.b`, 'a.b');182-test('$ splits expressions - \\.', testScriptStdout, () => $`echo.js ${'a'}\.${'b'}`, 'a.b');183-test('$ concatenates tokens - \\.', testScriptStdout, () => $`echo.js \.a\. b`, '.a.\nb');184-test('$ concatenates expressions - \\.', testScriptStdout, () => $`echo.js \.${'a'}\. b`, '.a.\nb');185-/* eslint-disable unicorn/no-hex-escape */186-test('$ handles tokens - \\x63', testScriptStdout, () => $`echo.js \x63`, 'c');187-test('$ splits tokens - \\x63', testScriptStdout, () => $`echo.js a\x63b`, 'acb');188-test('$ splits expressions - \\x63', testScriptStdout, () => $`echo.js ${'a'}\x63${'b'}`, 'acb');189-test('$ concatenates tokens - \\x63', testScriptStdout, () => $`echo.js \x63a\x63 b`, 'cac\nb');190-test('$ concatenates expressions - \\x63', testScriptStdout, () => $`echo.js \x63${'a'}\x63 b`, 'cac\nb');191-/* eslint-enable unicorn/no-hex-escape */192-test('$ handles tokens - \\u0063', testScriptStdout, () => $`echo.js \u0063`, 'c');193-test('$ splits tokens - \\u0063', testScriptStdout, () => $`echo.js a\u0063b`, 'acb');194-test('$ splits expressions - \\u0063', testScriptStdout, () => $`echo.js ${'a'}\u0063${'b'}`, 'acb');195-test('$ concatenates tokens - \\u0063', testScriptStdout, () => $`echo.js \u0063a\u0063 b`, 'cac\nb');196-test('$ concatenates expressions - \\u0063', testScriptStdout, () => $`echo.js \u0063${'a'}\u0063 b`, 'cac\nb');197-test('$ handles tokens - \\u{1}', testScriptStdout, () => $`echo.js \u{1}`, '\u0001');198-test('$ splits tokens - \\u{1}', testScriptStdout, () => $`echo.js a\u{1}b`, 'a\u0001b');199-test('$ splits expressions - \\u{1}', testScriptStdout, () => $`echo.js ${'a'}\u{1}${'b'}`, 'a\u0001b');200-test('$ concatenates tokens - \\u{1}', testScriptStdout, () => $`echo.js \u{1}a\u{1} b`, '\u0001a\u0001\nb');201-test('$ concatenates expressions - \\u{1}', testScriptStdout, () => $`echo.js \u{1}${'a'}\u{1} b`, '\u0001a\u0001\nb');202-test('$ handles tokens - \\u{63}', testScriptStdout, () => $`echo.js \u{63}`, 'c');203-test('$ splits tokens - \\u{63}', testScriptStdout, () => $`echo.js a\u{63}b`, 'acb');204-test('$ splits expressions - \\u{63}', testScriptStdout, () => $`echo.js ${'a'}\u{63}${'b'}`, 'acb');205-test('$ concatenates tokens - \\u{63}', testScriptStdout, () => $`echo.js \u{63}a\u{63} b`, 'cac\nb');206-test('$ concatenates expressions - \\u{63}', testScriptStdout, () => $`echo.js \u{63}${'a'}\u{63} b`, 'cac\nb');207-test('$ handles tokens - \\u{063}', testScriptStdout, () => $`echo.js \u{063}`, 'c');208-test('$ splits tokens - \\u{063}', testScriptStdout, () => $`echo.js a\u{063}b`, 'acb');209-test('$ splits expressions - \\u{063}', testScriptStdout, () => $`echo.js ${'a'}\u{063}${'b'}`, 'acb');210-test('$ concatenates tokens - \\u{063}', testScriptStdout, () => $`echo.js \u{063}a\u{063} b`, 'cac\nb');211-test('$ concatenates expressions - \\u{063}', testScriptStdout, () => $`echo.js \u{063}${'a'}\u{063} b`, 'cac\nb');212-test('$ handles tokens - \\u{0063}', testScriptStdout, () => $`echo.js \u{0063}`, 'c');213-test('$ splits tokens - \\u{0063}', testScriptStdout, () => $`echo.js a\u{0063}b`, 'acb');214-test('$ splits expressions - \\u{0063}', testScriptStdout, () => $`echo.js ${'a'}\u{0063}${'b'}`, 'acb');215-test('$ concatenates tokens - \\u{0063}', testScriptStdout, () => $`echo.js \u{0063}a\u{0063} b`, 'cac\nb');216-test('$ concatenates expressions - \\u{0063}', testScriptStdout, () => $`echo.js \u{0063}${'a'}\u{0063} b`, 'cac\nb');217-test('$ handles tokens - \\u{00063}', testScriptStdout, () => $`echo.js \u{00063}`, 'c');218-test('$ splits tokens - \\u{00063}', testScriptStdout, () => $`echo.js a\u{00063}b`, 'acb');219-test('$ splits expressions - \\u{00063}', testScriptStdout, () => $`echo.js ${'a'}\u{00063}${'b'}`, 'acb');220-test('$ concatenates tokens - \\u{00063}', testScriptStdout, () => $`echo.js \u{00063}a\u{00063} b`, 'cac\nb');221-test('$ concatenates expressions - \\u{00063}', testScriptStdout, () => $`echo.js \u{00063}${'a'}\u{00063} b`, 'cac\nb');222-test('$ handles tokens - \\u{000063}', testScriptStdout, () => $`echo.js \u{000063}`, 'c');223-test('$ splits tokens - \\u{000063}', testScriptStdout, () => $`echo.js a\u{000063}b`, 'acb');224-test('$ splits expressions - \\u{000063}', testScriptStdout, () => $`echo.js ${'a'}\u{000063}${'b'}`, 'acb');225-test('$ concatenates tokens - \\u{000063}', testScriptStdout, () => $`echo.js \u{000063}a\u{000063} b`, 'cac\nb');226-test('$ concatenates expressions - \\u{000063}', testScriptStdout, () => $`echo.js \u{000063}${'a'}\u{000063} b`, 'cac\nb');227-test('$ handles tokens - \\u{0000063}', testScriptStdout, () => $`echo.js \u{0000063}`, 'c');228-test('$ splits tokens - \\u{0000063}', testScriptStdout, () => $`echo.js a\u{0000063}b`, 'acb');229-test('$ splits expressions - \\u{0000063}', testScriptStdout, () => $`echo.js ${'a'}\u{0000063}${'b'}`, 'acb');230-test('$ concatenates tokens - \\u{0000063}', testScriptStdout, () => $`echo.js \u{0000063}a\u{0000063} b`, 'cac\nb');231-test('$ concatenates expressions - \\u{0000063}', testScriptStdout, () => $`echo.js \u{0000063}${'a'}\u{0000063} b`, 'cac\nb');232-test('$ handles tokens - \\u{0063}}', testScriptStdout, () => $`echo.js \u{0063}}`, 'c}');233-test('$ splits tokens - \\u{0063}}', testScriptStdout, () => $`echo.js a\u{0063}}b`, 'ac}b');234-test('$ splits expressions - \\u{0063}}', testScriptStdout, () => $`echo.js ${'a'}\u{0063}}${'b'}`, 'ac}b');235-test('$ concatenates tokens - \\u{0063}}', testScriptStdout, () => $`echo.js \u{0063}}a\u{0063}} b`, 'c}ac}\nb');236-test('$ concatenates expressions - \\u{0063}}', testScriptStdout, () => $`echo.js \u{0063}}${'a'}\u{0063}} b`, 'c}ac}\nb');237-238-const testScriptErrorStdout = async (t, getSubprocess) => {239- t.throws(getSubprocess, {message: /null bytes/});240-};241-242-test('$ handles tokens - \\0', testScriptErrorStdout, () => $`echo.js \0`);243-test('$ splits tokens - \\0', testScriptErrorStdout, () => $`echo.js a\0b`);244-test('$ splits expressions - \\0', testScriptErrorStdout, () => $`echo.js ${'a'}\0${'b'}`);245-test('$ concatenates tokens - \\0', testScriptErrorStdout, () => $`echo.js \0a\0 b`);246-test('$ concatenates expressions - \\0', testScriptErrorStdout, () => $`echo.js \0${'a'}\0 b`);247-248-const testReturnInterpolate = async (t, getSubprocess, expectedStdout, options = {}) => {249- const foo = await $(options)`echo.js foo`;250- const {stdout} = await getSubprocess(foo);251- t.is(stdout, expectedStdout);252-};253-254-test('$ allows execa return value interpolation', testReturnInterpolate, foo => $`echo.js ${foo} bar`, 'foo\nbar');255-test('$ allows execa return value buffer interpolation', testReturnInterpolate, foo => $`echo.js ${foo} bar`, 'foo\nbar', {encoding: 'buffer'});256-test('$ allows execa return value array interpolation', testReturnInterpolate, foo => $`echo.js ${[foo, 'bar']}`, 'foo\nbar');257-test('$ allows execa return value buffer array interpolation', testReturnInterpolate, foo => $`echo.js ${[foo, 'bar']}`, 'foo\nbar', {encoding: 'buffer'});258-259-const testReturnInterpolateSync = (t, getSubprocess, expectedStdout, options = {}) => {260- const foo = $(options).sync`echo.js foo`;261- const {stdout} = getSubprocess(foo);262- t.is(stdout, expectedStdout);263-};264-265-test('$.sync allows execa return value interpolation', testReturnInterpolateSync, foo => $.sync`echo.js ${foo} bar`, 'foo\nbar');266-test('$.sync allows execa return value buffer interpolation', testReturnInterpolateSync, foo => $.sync`echo.js ${foo} bar`, 'foo\nbar', {encoding: 'buffer'});267-test('$.sync allows execa return value array interpolation', testReturnInterpolateSync, foo => $.sync`echo.js ${[foo, 'bar']}`, 'foo\nbar');268-test('$.sync allows execa return value buffer array interpolation', testReturnInterpolateSync, foo => $.sync`echo.js ${[foo, 'bar']}`, 'foo\nbar', {encoding: 'buffer'});269-270-const testInvalidSequence = (t, getSubprocess) => {271- t.throws(getSubprocess, {message: /Invalid backslash sequence/});272-};273-274-test('$ handles invalid escape sequence - \\1', testInvalidSequence, () => $`echo.js \1`);275-test('$ handles invalid escape sequence - \\u', testInvalidSequence, () => $`echo.js \u`);276-test('$ handles invalid escape sequence - \\u0', testInvalidSequence, () => $`echo.js \u0`);277-test('$ handles invalid escape sequence - \\u00', testInvalidSequence, () => $`echo.js \u00`);278-test('$ handles invalid escape sequence - \\u000', testInvalidSequence, () => $`echo.js \u000`);279-test('$ handles invalid escape sequence - \\ug', testInvalidSequence, () => $`echo.js \ug`);280-test('$ handles invalid escape sequence - \\u{', testInvalidSequence, () => $`echo.js \u{`);281-test('$ handles invalid escape sequence - \\u{0000', testInvalidSequence, () => $`echo.js \u{0000`);282-test('$ handles invalid escape sequence - \\u{g}', testInvalidSequence, () => $`echo.js \u{g}`);283-/* eslint-disable unicorn/no-hex-escape */284-test('$ handles invalid escape sequence - \\x', testInvalidSequence, () => $`echo.js \x`);285-test('$ handles invalid escape sequence - \\x0', testInvalidSequence, () => $`echo.js \x0`);286-test('$ handles invalid escape sequence - \\xgg', testInvalidSequence, () => $`echo.js \xgg`);287-/* eslint-enable unicorn/no-hex-escape */288-289-const testEmptyScript = (t, getSubprocess) => {290- t.throws(getSubprocess, {message: /Template script must not be empty/});291-};292-293-test('$``', testEmptyScript, () => $``);294-test('$` `', testEmptyScript, () => $` `);295-test('$` ` (2 spaces)', testEmptyScript, () => $` `);296-test('$`\\t`', testEmptyScript, () => $` `);297-test('$`\\n`', testEmptyScript, () => $`298-`);299-300-const testInvalidExpression = (t, invalidExpression, execaMethod) => {301- const expression = typeof invalidExpression === 'function' ? invalidExpression() : invalidExpression;302- t.throws(303- () => execaMethod`echo.js ${expression}`,304- {message: /in template expression/},305- );306-};307-308-test('$ throws on invalid expression - undefined', testInvalidExpression, undefined, $);309-test('$ throws on invalid expression - null', testInvalidExpression, null, $);310-test('$ throws on invalid expression - true', testInvalidExpression, true, $);311-test('$ throws on invalid expression - {}', testInvalidExpression, {}, $);312-test('$ throws on invalid expression - {foo: "bar"}', testInvalidExpression, {foo: 'bar'}, $);313-test('$ throws on invalid expression - {stdout: undefined}', testInvalidExpression, {stdout: undefined}, $);314-test('$ throws on invalid expression - {stdout: 1}', testInvalidExpression, {stdout: 1}, $);315-test('$ throws on invalid expression - Promise.resolve()', testInvalidExpression, Promise.resolve(), $);316-test('$ throws on invalid expression - Promise.resolve({stdout: "foo"})', testInvalidExpression, Promise.resolve({foo: 'bar'}), $);317-test('$ throws on invalid expression - $', testInvalidExpression, () => $`noop.js`, $);318-test('$ throws on invalid expression - $(options).sync', testInvalidExpression, () => $({stdio: 'ignore'}).sync`noop.js`, $);319-test('$ throws on invalid expression - [undefined]', testInvalidExpression, [undefined], $);320-test('$ throws on invalid expression - [null]', testInvalidExpression, [null], $);321-test('$ throws on invalid expression - [true]', testInvalidExpression, [true], $);322-test('$ throws on invalid expression - [{}]', testInvalidExpression, [{}], $);323-test('$ throws on invalid expression - [{foo: "bar"}]', testInvalidExpression, [{foo: 'bar'}], $);324-test('$ throws on invalid expression - [{stdout: undefined}]', testInvalidExpression, [{stdout: undefined}], $);325-test('$ throws on invalid expression - [{stdout: 1}]', testInvalidExpression, [{stdout: 1}], $);326-test('$ throws on invalid expression - [Promise.resolve()]', testInvalidExpression, [Promise.resolve()], $);327-test('$ throws on invalid expression - [Promise.resolve({stdout: "foo"})]', testInvalidExpression, [Promise.resolve({stdout: 'foo'})], $);328-test('$ throws on invalid expression - [$]', testInvalidExpression, () => [$`noop.js`], $);329-test('$ throws on invalid expression - [$(options).sync]', testInvalidExpression, () => [$({stdio: 'ignore'}).sync`noop.js`], $);deleted:test/convert/fd-options.js-725 removed
1-import {PassThrough} from 'node:stream';2-import {spawn} from 'node:child_process';3-import process from 'node:process';4-import test from 'ava';5-import {execa} from '../../index.js';6-import {setFixtureDir} from '../helpers/fixtures-dir.js';7-import {fullStdio, getStdio} from '../helpers/stdio.js';8-import {getEarlyErrorSubprocess} from '../helpers/early-error.js';9-import {assertPipeError} from '../helpers/pipe.js';10-11-setFixtureDir();12-13-const getMessage = message => Array.isArray(message)14- ? `"${message[0]}: ${message[1]}" option is incompatible`15- : message;16-17-const testPipeError = async (t, {18- message,19- sourceOptions = {},20- destinationOptions = {},21- getSource = () => execa('empty.js', sourceOptions),22- getDestination = () => execa('empty.js', destinationOptions),23- isScript = false,24- from,25- to,26-}) => {27- const source = getSource();28- const pipePromise = isScript ? source.pipe({from, to})`empty.js` : source.pipe(getDestination(), {from, to});29- await assertPipeError(t, pipePromise, getMessage(message));30-};31-32-const testNodeStream = async (t, {33- message,34- sourceOptions = {},35- getSource = () => execa('empty.js', sourceOptions),36- from,37- to,38- writable = to !== undefined,39-}) => {40- assertNodeStream({t, message, getSource, from, to, methodName: writable ? 'writable' : 'readable'});41- assertNodeStream({t, message, getSource, from, to, methodName: 'duplex'});42-};43-44-const assertNodeStream = ({t, message, getSource, from, to, methodName}) => {45- const error = t.throws(() => {46- getSource()[methodName]({from, to});47- });48- t.true(error.message.includes(getMessage(message)));49-};50-51-const testIterable = async (t, {52- message,53- sourceOptions = {},54- getSource = () => execa('empty.js', sourceOptions),55- from,56-}) => {57- const error = t.throws(() => {58- getSource().iterable({from});59- });60- t.true(error.message.includes(getMessage(message)));61-};62-63-test('Must set "all" option to "true" to use .pipe("all")', testPipeError, {64- from: 'all',65- message: '"all" option must be true',66-});67-test('Must set "all" option to "true" to use .duplex("all")', testNodeStream, {68- from: 'all',69- message: '"all" option must be true',70-});71-test('Must set "all" option to "true" to use .iterable("all")', testIterable, {72- from: 'all',73- message: '"all" option must be true',74-});75-test('.pipe() cannot pipe to non-subprocesses', testPipeError, {76- getDestination: () => new PassThrough(),77- message: 'an Execa subprocess',78-});79-test('.pipe() cannot pipe to non-Execa subprocesses', testPipeError, {80- getDestination: () => spawn('node', ['--version']),81- message: 'an Execa subprocess',82-});83-test('.pipe() "from" option cannot be "stdin"', testPipeError, {84- from: 'stdin',85- message: '"from" must not be',86-});87-test('.duplex() "from" option cannot be "stdin"', testNodeStream, {88- from: 'stdin',89- message: '"from" must not be',90-});91-test('.iterable() "from" option cannot be "stdin"', testIterable, {92- from: 'stdin',93- message: '"from" must not be',94-});95-test('$.pipe() "from" option cannot be "stdin"', testPipeError, {96- from: 'stdin',97- isScript: true,98- message: '"from" must not be',99-});100-test('.pipe() "to" option cannot be "stdout"', testPipeError, {101- to: 'stdout',102- message: '"to" must not be',103-});104-test('.duplex() "to" option cannot be "stdout"', testNodeStream, {105- to: 'stdout',106- message: '"to" must not be',107-});108-test('$.pipe() "to" option cannot be "stdout"', testPipeError, {109- to: 'stdout',110- isScript: true,111- message: '"to" must not be',112-});113-test('.pipe() "from" option cannot be any string', testPipeError, {114- from: 'other',115- message: 'must be "stdout", "stderr", "all"',116-});117-test('.duplex() "from" option cannot be any string', testNodeStream, {118- from: 'other',119- message: 'must be "stdout", "stderr", "all"',120-});121-test('.iterable() "from" option cannot be any string', testIterable, {122- from: 'other',123- message: 'must be "stdout", "stderr", "all"',124-});125-test('.pipe() "to" option cannot be any string', testPipeError, {126- to: 'other',127- message: 'must be "stdin"',128-});129-test('.duplex() "to" option cannot be any string', testNodeStream, {130- to: 'other',131- message: 'must be "stdin"',132-});133-test('.pipe() "from" option cannot be a number without "fd"', testPipeError, {134- from: '1',135- message: 'must be "stdout", "stderr", "all"',136-});137-test('.duplex() "from" option cannot be a number without "fd"', testNodeStream, {138- from: '1',139- message: 'must be "stdout", "stderr", "all"',140-});141-test('.iterable() "from" option cannot be a number without "fd"', testIterable, {142- from: '1',143- message: 'must be "stdout", "stderr", "all"',144-});145-test('.pipe() "to" option cannot be a number without "fd"', testPipeError, {146- to: '0',147- message: 'must be "stdin"',148-});149-test('.duplex() "to" option cannot be a number without "fd"', testNodeStream, {150- to: '0',151- message: 'must be "stdin"',152-});153-test('.pipe() "from" option cannot be just "fd"', testPipeError, {154- from: 'fd',155- message: 'must be "stdout", "stderr", "all"',156-});157-test('.duplex() "from" option cannot be just "fd"', testNodeStream, {158- from: 'fd',159- message: 'must be "stdout", "stderr", "all"',160-});161-test('.iterable() "from" option cannot be just "fd"', testIterable, {162- from: 'fd',163- message: 'must be "stdout", "stderr", "all"',164-});165-test('.pipe() "to" option cannot be just "fd"', testPipeError, {166- to: 'fd',167- message: 'must be "stdin"',168-});169-test('.duplex() "to" option cannot be just "fd"', testNodeStream, {170- to: 'fd',171- message: 'must be "stdin"',172-});173-test('.pipe() "from" option cannot be a float', testPipeError, {174- from: 'fd1.5',175- message: 'must be "stdout", "stderr", "all"',176-});177-test('.duplex() "from" option cannot be a float', testNodeStream, {178- from: 'fd1.5',179- message: 'must be "stdout", "stderr", "all"',180-});181-test('.iterable() "from" option cannot be a float', testIterable, {182- from: 'fd1.5',183- message: 'must be "stdout", "stderr", "all"',184-});185-test('.pipe() "to" option cannot be a float', testPipeError, {186- to: 'fd1.5',187- message: 'must be "stdin"',188-});189-test('.duplex() "to" option cannot be a float', testNodeStream, {190- to: 'fd1.5',191- message: 'must be "stdin"',192-});193-test('.pipe() "from" option cannot be a negative number', testPipeError, {194- from: 'fd-1',195- message: 'must be "stdout", "stderr", "all"',196-});197-test('.duplex() "from" option cannot be a negative number', testNodeStream, {198- from: 'fd-1',199- message: 'must be "stdout", "stderr", "all"',200-});201-test('.iterable() "from" option cannot be a negative number', testIterable, {202- from: 'fd-1',203- message: 'must be "stdout", "stderr", "all"',204-});205-test('.pipe() "to" option cannot be a negative number', testPipeError, {206- to: 'fd-1',207- message: 'must be "stdin"',208-});209-test('.duplex() "to" option cannot be a negative number', testNodeStream, {210- to: 'fd-1',211- message: 'must be "stdin"',212-});213-test('.pipe() "from" option cannot be a non-existing file descriptor', testPipeError, {214- from: 'fd3',215- message: 'file descriptor does not exist',216-});217-test('.duplex() "from" cannot be a non-existing file descriptor', testNodeStream, {218- from: 'fd3',219- message: 'file descriptor does not exist',220-});221-test('.iterable() "from" cannot be a non-existing file descriptor', testIterable, {222- from: 'fd3',223- message: 'file descriptor does not exist',224-});225-test('.pipe() "to" option cannot be a non-existing file descriptor', testPipeError, {226- to: 'fd3',227- message: 'file descriptor does not exist',228-});229-test('.duplex() "to" cannot be a non-existing file descriptor', testNodeStream, {230- to: 'fd3',231- message: 'file descriptor does not exist',232-});233-test('.pipe() "from" option cannot be an input file descriptor', testPipeError, {234- sourceOptions: getStdio(3, new Uint8Array()),235- from: 'fd3',236- message: 'must be a readable stream',237-});238-test('.duplex() "from" option cannot be an input file descriptor', testNodeStream, {239- sourceOptions: getStdio(3, new Uint8Array()),240- from: 'fd3',241- message: 'must be a readable stream',242-});243-test('.iterable() "from" option cannot be an input file descriptor', testIterable, {244- sourceOptions: getStdio(3, new Uint8Array()),245- from: 'fd3',246- message: 'must be a readable stream',247-});248-test('.pipe() "to" option cannot be an output file descriptor', testPipeError, {249- destinationOptions: fullStdio,250- to: 'fd3',251- message: 'must be a writable stream',252-});253-test('.duplex() "to" option cannot be an output file descriptor', testNodeStream, {254- sourceOptions: fullStdio,255- to: 'fd3',256- message: 'must be a writable stream',257-});258-test('.pipe() "to" option cannot be "all"', testPipeError, {259- destinationOptions: fullStdio,260- to: 'all',261- message: 'must be a writable stream',262-});263-test('.duplex() "to" option cannot be "all"', testNodeStream, {264- sourceOptions: fullStdio,265- to: 'all',266- message: 'must be a writable stream',267-});268-test('Cannot set "stdout" option to "ignore" to use .pipe()', testPipeError, {269- sourceOptions: {stdout: 'ignore'},270- message: ['stdout', '\'ignore\''],271-});272-test('Cannot set "stdout" option to "ignore" to use .duplex()', testNodeStream, {273- sourceOptions: {stdout: 'ignore'},274- message: ['stdout', '\'ignore\''],275-});276-test('Cannot set "stdout" option to "ignore" to use .iterable()', testIterable, {277- sourceOptions: {stdout: 'ignore'},278- message: ['stdout', '\'ignore\''],279-});280-test('Cannot set "stdin" option to "ignore" to use .pipe()', testPipeError, {281- destinationOptions: {stdin: 'ignore'},282- message: ['stdin', '\'ignore\''],283-});284-test('Cannot set "stdin" option to "ignore" to use .duplex()', testNodeStream, {285- sourceOptions: {stdin: 'ignore'},286- message: ['stdin', '\'ignore\''],287- writable: true,288-});289-test('Cannot set "stdout" option to "ignore" to use .pipe(1)', testPipeError, {290- sourceOptions: {stdout: 'ignore'},291- from: 'fd1',292- message: ['stdout', '\'ignore\''],293-});294-test('Cannot set "stdout" option to "ignore" to use .duplex(1)', testNodeStream, {295- sourceOptions: {stdout: 'ignore'},296- from: 'fd1',297- message: ['stdout', '\'ignore\''],298-});299-test('Cannot set "stdout" option to "ignore" to use .iterable(1)', testIterable, {300- sourceOptions: {stdout: 'ignore'},301- from: 'fd1',302- message: ['stdout', '\'ignore\''],303-});304-test('Cannot set "stdin" option to "ignore" to use .pipe(0)', testPipeError, {305- destinationOptions: {stdin: 'ignore'},306- message: ['stdin', '\'ignore\''],307- to: 'fd0',308-});309-test('Cannot set "stdin" option to "ignore" to use .duplex(0)', testNodeStream, {310- sourceOptions: {stdin: 'ignore'},311- message: ['stdin', '\'ignore\''],312- to: 'fd0',313-});314-test('Cannot set "stdout" option to "ignore" to use .pipe("stdout")', testPipeError, {315- sourceOptions: {stdout: 'ignore'},316- from: 'stdout',317- message: ['stdout', '\'ignore\''],318-});319-test('Cannot set "stdout" option to "ignore" to use .duplex("stdout")', testNodeStream, {320- sourceOptions: {stdout: 'ignore'},321- from: 'stdout',322- message: ['stdout', '\'ignore\''],323-});324-test('Cannot set "stdout" option to "ignore" to use .iterable("stdout")', testIterable, {325- sourceOptions: {stdout: 'ignore'},326- from: 'stdout',327- message: ['stdout', '\'ignore\''],328-});329-test('Cannot set "stdin" option to "ignore" to use .pipe("stdin")', testPipeError, {330- destinationOptions: {stdin: 'ignore'},331- message: ['stdin', '\'ignore\''],332- to: 'stdin',333-});334-test('Cannot set "stdin" option to "ignore" to use .duplex("stdin")', testNodeStream, {335- sourceOptions: {stdin: 'ignore'},336- message: ['stdin', '\'ignore\''],337- to: 'stdin',338-});339-test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe()', testPipeError, {340- sourceOptions: {stdout: 'ignore', stderr: 'ignore'},341- message: ['stdout', '\'ignore\''],342-});343-test('Cannot set "stdout" + "stderr" option to "ignore" to use .duplex()', testNodeStream, {344- sourceOptions: {stdout: 'ignore', stderr: 'ignore'},345- message: ['stdout', '\'ignore\''],346-});347-test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable()', testIterable, {348- sourceOptions: {stdout: 'ignore', stderr: 'ignore'},349- message: ['stdout', '\'ignore\''],350-});351-test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe(1)', testPipeError, {352- sourceOptions: {stdout: 'ignore', stderr: 'ignore'},353- from: 'fd1',354- message: ['stdout', '\'ignore\''],355-});356-test('Cannot set "stdout" + "stderr" option to "ignore" to use .duplex(1)', testNodeStream, {357- sourceOptions: {stdout: 'ignore', stderr: 'ignore'},358- from: 'fd1',359- message: ['stdout', '\'ignore\''],360-});361-test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable(1)', testIterable, {362- sourceOptions: {stdout: 'ignore', stderr: 'ignore'},363- from: 'fd1',364- message: ['stdout', '\'ignore\''],365-});366-test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe("stdout")', testPipeError, {367- sourceOptions: {stdout: 'ignore', stderr: 'ignore'},368- from: 'stdout',369- message: ['stdout', '\'ignore\''],370-});371-test('Cannot set "stdout" + "stderr" option to "ignore" to use .duplex("stdout")', testNodeStream, {372- sourceOptions: {stdout: 'ignore', stderr: 'ignore'},373- from: 'stdout',374- message: ['stdout', '\'ignore\''],375-});376-test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable("stdout")', testIterable, {377- sourceOptions: {stdout: 'ignore', stderr: 'ignore'},378- from: 'stdout',379- message: ['stdout', '\'ignore\''],380-});381-test('Cannot set "stdio[1]" option to "ignore" to use .pipe()', testPipeError, {382- sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},383- message: ['stdio[1]', '\'ignore\''],384-});385-test('Cannot set "stdio[1]" option to "ignore" to use .duplex()', testNodeStream, {386- sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},387- message: ['stdio[1]', '\'ignore\''],388-});389-test('Cannot set "stdio[1]" option to "ignore" to use .iterable()', testIterable, {390- sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},391- message: ['stdio[1]', '\'ignore\''],392-});393-test('Cannot set "stdio[0]" option to "ignore" to use .pipe()', testPipeError, {394- destinationOptions: {stdio: ['ignore', 'pipe', 'pipe']},395- message: ['stdio[0]', '\'ignore\''],396-});397-test('Cannot set "stdio[0]" option to "ignore" to use .duplex()', testNodeStream, {398- sourceOptions: {stdio: ['ignore', 'pipe', 'pipe']},399- message: ['stdio[0]', '\'ignore\''],400- writable: true,401-});402-test('Cannot set "stdio[1]" option to "ignore" to use .pipe(1)', testPipeError, {403- sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},404- from: 'fd1',405- message: ['stdio[1]', '\'ignore\''],406-});407-test('Cannot set "stdio[1]" option to "ignore" to use .duplex(1)', testNodeStream, {408- sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},409- from: 'fd1',410- message: ['stdio[1]', '\'ignore\''],411-});412-test('Cannot set "stdio[1]" option to "ignore" to use .iterable(1)', testIterable, {413- sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},414- from: 'fd1',415- message: ['stdio[1]', '\'ignore\''],416-});417-test('Cannot set "stdio[0]" option to "ignore" to use .pipe(0)', testPipeError, {418- destinationOptions: {stdio: ['ignore', 'pipe', 'pipe']},419- message: ['stdio[0]', '\'ignore\''],420- to: 'fd0',421-});422-test('Cannot set "stdio[0]" option to "ignore" to use .duplex(0)', testNodeStream, {423- sourceOptions: {stdio: ['ignore', 'pipe', 'pipe']},424- message: ['stdio[0]', '\'ignore\''],425- to: 'fd0',426-});427-test('Cannot set "stdio[1]" option to "ignore" to use .pipe("stdout")', testPipeError, {428- sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},429- from: 'stdout',430- message: ['stdio[1]', '\'ignore\''],431-});432-test('Cannot set "stdio[1]" option to "ignore" to use .duplex("stdout")', testNodeStream, {433- sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},434- from: 'stdout',435- message: ['stdio[1]', '\'ignore\''],436-});437-test('Cannot set "stdio[1]" option to "ignore" to use .iterable("stdout")', testIterable, {438- sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},439- from: 'stdout',440- message: ['stdio[1]', '\'ignore\''],441-});442-test('Cannot set "stdio[0]" option to "ignore" to use .pipe("stdin")', testPipeError, {443- destinationOptions: {stdio: ['ignore', 'pipe', 'pipe']},444- message: ['stdio[0]', '\'ignore\''],445- to: 'stdin',446-});447-test('Cannot set "stdio[0]" option to "ignore" to use .duplex("stdin")', testNodeStream, {448- sourceOptions: {stdio: ['ignore', 'pipe', 'pipe']},449- message: ['stdio[0]', '\'ignore\''],450- to: 'stdin',451-});452-test('Cannot set "stderr" option to "ignore" to use .pipe(2)', testPipeError, {453- sourceOptions: {stderr: 'ignore'},454- from: 'fd2',455- message: ['stderr', '\'ignore\''],456-});457-test('Cannot set "stderr" option to "ignore" to use .duplex(2)', testNodeStream, {458- sourceOptions: {stderr: 'ignore'},459- from: 'fd2',460- message: ['stderr', '\'ignore\''],461-});462-test('Cannot set "stderr" option to "ignore" to use .iterable(2)', testIterable, {463- sourceOptions: {stderr: 'ignore'},464- from: 'fd2',465- message: ['stderr', '\'ignore\''],466-});467-test('Cannot set "stderr" option to "ignore" to use .pipe("stderr")', testPipeError, {468- sourceOptions: {stderr: 'ignore'},469- from: 'stderr',470- message: ['stderr', '\'ignore\''],471-});472-test('Cannot set "stderr" option to "ignore" to use .duplex("stderr")', testNodeStream, {473- sourceOptions: {stderr: 'ignore'},474- from: 'stderr',475- message: ['stderr', '\'ignore\''],476-});477-test('Cannot set "stderr" option to "ignore" to use .iterable("stderr")', testIterable, {478- sourceOptions: {stderr: 'ignore'},479- from: 'stderr',480- message: ['stderr', '\'ignore\''],481-});482-test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe(2)', testPipeError, {483- sourceOptions: {stdout: 'ignore', stderr: 'ignore'},484- from: 'fd2',485- message: ['stderr', '\'ignore\''],486-});487-test('Cannot set "stdout" + "stderr" option to "ignore" to use .duplex(2)', testNodeStream, {488- sourceOptions: {stdout: 'ignore', stderr: 'ignore'},489- from: 'fd2',490- message: ['stderr', '\'ignore\''],491-});492-test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable(2)', testIterable, {493- sourceOptions: {stdout: 'ignore', stderr: 'ignore'},494- from: 'fd2',495- message: ['stderr', '\'ignore\''],496-});497-test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe("stderr")', testPipeError, {498- sourceOptions: {stdout: 'ignore', stderr: 'ignore'},499- from: 'stderr',500- message: ['stderr', '\'ignore\''],501-});502-test('Cannot set "stdout" + "stderr" option to "ignore" to use .duplex("stderr")', testNodeStream, {503- sourceOptions: {stdout: 'ignore', stderr: 'ignore'},504- from: 'stderr',505- message: ['stderr', '\'ignore\''],506-});507-test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable("stderr")', testIterable, {508- sourceOptions: {stdout: 'ignore', stderr: 'ignore'},509- from: 'stderr',510- message: ['stderr', '\'ignore\''],511-});512-test('Cannot set "stdio[2]" option to "ignore" to use .pipe(2)', testPipeError, {513- sourceOptions: {stdio: ['pipe', 'pipe', 'ignore']},514- from: 'fd2',515- message: ['stdio[2]', '\'ignore\''],516-});517-test('Cannot set "stdio[2]" option to "ignore" to use .duplex(2)', testNodeStream, {518- sourceOptions: {stdio: ['pipe', 'pipe', 'ignore']},519- from: 'fd2',520- message: ['stdio[2]', '\'ignore\''],521-});522-test('Cannot set "stdio[2]" option to "ignore" to use .iterable(2)', testIterable, {523- sourceOptions: {stdio: ['pipe', 'pipe', 'ignore']},524- from: 'fd2',525- message: ['stdio[2]', '\'ignore\''],526-});527-test('Cannot set "stdio[2]" option to "ignore" to use .pipe("stderr")', testPipeError, {528- sourceOptions: {stdio: ['pipe', 'pipe', 'ignore']},529- from: 'stderr',530- message: ['stdio[2]', '\'ignore\''],531-});532-test('Cannot set "stdio[2]" option to "ignore" to use .duplex("stderr")', testNodeStream, {533- sourceOptions: {stdio: ['pipe', 'pipe', 'ignore']},534- from: 'stderr',535- message: ['stdio[2]', '\'ignore\''],536-});537-test('Cannot set "stdio[2]" option to "ignore" to use .iterable("stderr")', testIterable, {538- sourceOptions: {stdio: ['pipe', 'pipe', 'ignore']},539- from: 'stderr',540- message: ['stdio[2]', '\'ignore\''],541-});542-test('Cannot set "stdio[3]" option to "ignore" to use .pipe(3)', testPipeError, {543- sourceOptions: getStdio(3, 'ignore'),544- from: 'fd3',545- message: ['stdio[3]', '\'ignore\''],546-});547-test('Cannot set "stdio[3]" option to "ignore" to use .duplex(3)', testNodeStream, {548- sourceOptions: getStdio(3, 'ignore'),549- from: 'fd3',550- message: ['stdio[3]', '\'ignore\''],551-});552-test('Cannot set "stdio[3]" option to "ignore" to use .iterable(3)', testIterable, {553- sourceOptions: getStdio(3, 'ignore'),554- from: 'fd3',555- message: ['stdio[3]', '\'ignore\''],556-});557-test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe("all")', testPipeError, {558- sourceOptions: {stdout: 'ignore', stderr: 'ignore', all: true},559- from: 'all',560- message: ['stdout', '\'ignore\''],561-});562-test('Cannot set "stdout" + "stderr" option to "ignore" to use .duplex("all")', testNodeStream, {563- sourceOptions: {stdout: 'ignore', stderr: 'ignore', all: true},564- from: 'all',565- message: ['stdout', '\'ignore\''],566-});567-test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable("all")', testIterable, {568- sourceOptions: {stdout: 'ignore', stderr: 'ignore', all: true},569- from: 'all',570- message: ['stdout', '\'ignore\''],571-});572-test('Cannot set "stdio[1]" + "stdio[2]" option to "ignore" to use .pipe("all")', testPipeError, {573- sourceOptions: {stdio: ['pipe', 'ignore', 'ignore'], all: true},574- from: 'all',575- message: ['stdio[1]', '\'ignore\''],576-});577-test('Cannot set "stdio[1]" + "stdio[2]" option to "ignore" to use .duplex("all")', testNodeStream, {578- sourceOptions: {stdio: ['pipe', 'ignore', 'ignore'], all: true},579- from: 'all',580- message: ['stdio[1]', '\'ignore\''],581-});582-test('Cannot set "stdio[1]" + "stdio[2]" option to "ignore" to use .iterable("all")', testIterable, {583- sourceOptions: {stdio: ['pipe', 'ignore', 'ignore'], all: true},584- from: 'all',585- message: ['stdio[1]', '\'ignore\''],586-});587-test('Cannot set "stdout" option to "inherit" to use .pipe()', testPipeError, {588- sourceOptions: {stdout: 'inherit'},589- message: ['stdout', '\'inherit\''],590-});591-test('Cannot set "stdout" option to "inherit" to use .duplex()', testNodeStream, {592- sourceOptions: {stdout: 'inherit'},593- message: ['stdout', '\'inherit\''],594-});595-test('Cannot set "stdout" option to "inherit" to use .iterable()', testIterable, {596- sourceOptions: {stdout: 'inherit'},597- message: ['stdout', '\'inherit\''],598-});599-test('Cannot set "stdin" option to "inherit" to use .pipe()', testPipeError, {600- destinationOptions: {stdin: 'inherit'},601- message: ['stdin', '\'inherit\''],602-});603-test('Cannot set "stdin" option to "inherit" to use .duplex()', testNodeStream, {604- sourceOptions: {stdin: 'inherit'},605- message: ['stdin', '\'inherit\''],606- writable: true,607-});608-test('Cannot set "stdout" option to "ipc" to use .pipe()', testPipeError, {609- sourceOptions: {stdout: 'ipc'},610- message: ['stdout', '\'ipc\''],611-});612-test('Cannot set "stdout" option to "ipc" to use .duplex()', testNodeStream, {613- sourceOptions: {stdout: 'ipc'},614- message: ['stdout', '\'ipc\''],615-});616-test('Cannot set "stdout" option to "ipc" to use .iterable()', testIterable, {617- sourceOptions: {stdout: 'ipc'},618- message: ['stdout', '\'ipc\''],619-});620-test('Cannot set "stdin" option to "ipc" to use .pipe()', testPipeError, {621- destinationOptions: {stdin: 'ipc'},622- message: ['stdin', '\'ipc\''],623-});624-test('Cannot set "stdin" option to "ipc" to use .duplex()', testNodeStream, {625- sourceOptions: {stdin: 'ipc'},626- message: ['stdin', '\'ipc\''],627- writable: true,628-});629-test('Cannot set "stdout" option to file descriptors to use .pipe()', testPipeError, {630- sourceOptions: {stdout: 1},631- message: ['stdout', '1'],632-});633-test('Cannot set "stdout" option to file descriptors to use .duplex()', testNodeStream, {634- sourceOptions: {stdout: 1},635- message: ['stdout', '1'],636-});637-test('Cannot set "stdout" option to file descriptors to use .iterable()', testIterable, {638- sourceOptions: {stdout: 1},639- message: ['stdout', '1'],640-});641-test('Cannot set "stdin" option to file descriptors to use .pipe()', testPipeError, {642- destinationOptions: {stdin: 0},643- message: ['stdin', '0'],644-});645-test('Cannot set "stdin" option to file descriptors to use .duplex()', testNodeStream, {646- sourceOptions: {stdin: 0},647- message: ['stdin', '0'],648- writable: true,649-});650-test('Cannot set "stdout" option to Node.js streams to use .pipe()', testPipeError, {651- sourceOptions: {stdout: process.stdout},652- message: ['stdout', 'Stream'],653-});654-test('Cannot set "stdout" option to Node.js streams to use .duplex()', testNodeStream, {655- sourceOptions: {stdout: process.stdout},656- message: ['stdout', 'Stream'],657-});658-test('Cannot set "stdout" option to Node.js streams to use .iterable()', testIterable, {659- sourceOptions: {stdout: process.stdout},660- message: ['stdout', 'Stream'],661-});662-test('Cannot set "stdin" option to Node.js streams to use .pipe()', testPipeError, {663- destinationOptions: {stdin: process.stdin},664- message: ['stdin', 'Stream'],665-});666-test('Cannot set "stdin" option to Node.js streams to use .duplex()', testNodeStream, {667- sourceOptions: {stdin: process.stdin},668- message: ['stdin', 'Stream'],669- writable: true,670-});671-test('Cannot set "stdio[3]" option to Node.js Writable streams to use .pipe()', testPipeError, {672- sourceOptions: getStdio(3, process.stdout),673- message: ['stdio[3]', 'Stream'],674- from: 'fd3',675-});676-test('Cannot set "stdio[3]" option to Node.js Writable streams to use .duplex()', testNodeStream, {677- sourceOptions: getStdio(3, process.stdout),678- message: ['stdio[3]', 'Stream'],679- from: 'fd3',680-});681-test('Cannot set "stdio[3]" option to Node.js Writable streams to use .iterable()', testIterable, {682- sourceOptions: getStdio(3, process.stdout),683- message: ['stdio[3]', 'Stream'],684- from: 'fd3',685-});686-test('Cannot set "stdio[3]" option to Node.js Readable streams to use .pipe()', testPipeError, {687- destinationOptions: getStdio(3, process.stdin),688- message: ['stdio[3]', 'Stream'],689- to: 'fd3',690-});691-test('Cannot set "stdio[3]" option to Node.js Readable streams to use .duplex()', testNodeStream, {692- sourceOptions: getStdio(3, process.stdin),693- message: ['stdio[3]', 'Stream'],694- to: 'fd3',695-});696-697-test('Sets the right error message when the "all" option is incompatible - execa.$', async t => {698- await assertPipeError(699- t,700- execa('empty.js')701- .pipe({all: false})`stdin.js`702- .pipe(execa('empty.js'), {from: 'all'}),703- '"all" option must be true',704- );705-});706-707-test('Sets the right error message when the "all" option is incompatible - execa.execa', async t => {708- await assertPipeError(709- t,710- execa('empty.js')711- .pipe(execa('stdin.js', {all: false}))712- .pipe(execa('empty.js'), {from: 'all'}),713- '"all" option must be true',714- );715-});716-717-test('Sets the right error message when the "all" option is incompatible - early error', async t => {718- await assertPipeError(719- t,720- getEarlyErrorSubprocess()721- .pipe(execa('stdin.js', {all: false}))722- .pipe(execa('empty.js'), {from: 'all'}),723- '"all" option must be true',724- );725-});deleted:test/convert/loop.js-201 removed
1-import {once} from 'node:events';2-import {getDefaultHighWaterMark} from 'node:stream';3-import test from 'ava';4-import {setFixtureDir} from '../helpers/fixtures-dir.js';5-import {6- assertStreamOutput,7- assertIterableChunks,8- assertStreamChunks,9- assertSubprocessOutput,10- getReadableSubprocess,11- getReadWriteSubprocess,12-} from '../helpers/convert.js';13-import {14- stringToUint8Arrays,15- simpleFull,16- simpleChunks,17- simpleChunksBuffer,18- simpleChunksUint8Array,19- simpleLines,20- noNewlinesFull,21- complexFull,22- complexFullUtf16,23- complexFullUtf16Uint8Array,24- singleComplexBuffer,25- singleComplexUtf16Buffer,26- singleComplexUint8Array,27- singleComplexHex,28- complexChunks,29- complexChunksEnd,30-} from '../helpers/lines.js';31-import {outputObjectGenerator, getOutputGenerator} from '../helpers/generator.js';32-import {foobarString, foobarObject} from '../helpers/input.js';33-import {multibyteChar, multibyteUint8Array, breakingLength, brokenSymbol} from '../helpers/encoding.js';34-35-setFixtureDir();36-37-const foobarObjectChunks = [foobarObject, foobarObject, foobarObject];38-39-const getSubprocess = (methodName, output, options) => {40- if (methodName !== 'duplex') {41- return getReadableSubprocess(output, options);42- }43-44- const subprocess = getReadWriteSubprocess(options);45- subprocess.stdin.end(output);46- return subprocess;47-};48-49-const assertChunks = async (t, streamOrIterable, expectedChunks, methodName) => {50- const assertMethod = methodName === 'iterable' ? assertIterableChunks : assertStreamChunks;51- await assertMethod(t, streamOrIterable, expectedChunks);52-};53-54-// eslint-disable-next-line max-params55-const testText = async (t, expectedChunks, methodName, binary, preserveNewlines, encoding) => {56- const subprocess = getReadWriteSubprocess({encoding});57- const input = encoding === 'utf16le' ? complexFullUtf16 : complexFull;58- subprocess.stdin.end(input);59- const stream = subprocess[methodName]({binary, preserveNewlines});60-61- await assertChunks(t, stream, expectedChunks, methodName);62- const expectedOutput = encoding === 'hex'63- ? singleComplexHex64- : stringToUint8Arrays(complexFull, encoding === 'buffer');65- await assertSubprocessOutput(t, subprocess, expectedOutput);66-};67-68-test('.iterable() can use "binary: true"', testText, [singleComplexUint8Array], 'iterable', true, undefined, 'utf8');69-test('.iterable() can use "binary: true" + "encoding: utf16le"', testText, [complexFullUtf16Uint8Array], 'iterable', true, undefined, 'utf16le');70-test('.iterable() can use "binary: true" + "encoding: "buffer"', testText, [singleComplexUint8Array], 'iterable', true, undefined, 'buffer');71-test('.iterable() can use "binary: true" + "encoding: "hex"', testText, [singleComplexUint8Array], 'iterable', true, undefined, 'hex');72-test('.iterable() can use "binary: undefined"', testText, complexChunks, 'iterable', undefined, undefined, 'utf8');73-test('.iterable() can use "binary: undefined" + "encoding: utf16le"', testText, complexChunks, 'iterable', undefined, undefined, 'utf16le');74-test('.iterable() can use "binary: undefined" + "encoding: buffer"', testText, [singleComplexUint8Array], 'iterable', undefined, undefined, 'buffer');75-test('.iterable() can use "binary: undefined" + "encoding: hex"', testText, [singleComplexUint8Array], 'iterable', undefined, undefined, 'hex');76-test('.iterable() can use "binary: false"', testText, complexChunks, 'iterable', false, undefined, 'utf8');77-test('.iterable() can use "binary: false" + "encoding: utf16le"', testText, complexChunks, 'iterable', false, undefined, 'utf16le');78-test('.iterable() can use "binary: false" + "encoding: buffer"', testText, [singleComplexUint8Array], 'iterable', false, undefined, 'buffer');79-test('.iterable() can use "binary: false" + "encoding: hex"', testText, [singleComplexUint8Array], 'iterable', false, undefined, 'hex');80-test('.iterable() can use "binary: false" + "preserveNewlines: true"', testText, complexChunksEnd, 'iterable', false, true, 'utf8');81-test('.iterable() can use "binary: false" + "preserveNewlines: false"', testText, complexChunks, 'iterable', false, false, 'utf8');82-test('.readable() can use "binary: true"', testText, singleComplexBuffer, 'readable', true, undefined, 'utf8');83-test('.readable() can use "binary: true" + "encoding: utf16le"', testText, singleComplexUtf16Buffer, 'readable', true, undefined, 'utf16le');84-test('.readable() can use "binary: true" + "encoding: buffer"', testText, singleComplexBuffer, 'readable', true, undefined, 'buffer');85-test('.readable() can use "binary: true" + "encoding: hex"', testText, singleComplexBuffer, 'readable', true, undefined, 'hex');86-test('.readable() can use "binary: undefined"', testText, singleComplexBuffer, 'readable', undefined, undefined, 'utf8');87-test('.readable() can use "binary: undefined" + "encoding: utf16le"', testText, singleComplexUtf16Buffer, 'readable', undefined, undefined, 'utf16le');88-test('.readable() can use "binary: undefined" + "encoding: buffer"', testText, singleComplexBuffer, 'readable', undefined, undefined, 'buffer');89-test('.readable() can use "binary: undefined" + "encoding: hex"', testText, singleComplexBuffer, 'readable', undefined, undefined, 'hex');90-test('.readable() can use "binary: false"', testText, complexChunksEnd, 'readable', false, undefined, 'utf8');91-test('.readable() can use "binary: false" + "encoding: utf16le"', testText, complexChunksEnd, 'readable', false, undefined, 'utf16le');92-test('.readable() can use "binary: false" + "encoding: buffer"', testText, singleComplexBuffer, 'readable', false, undefined, 'buffer');93-test('.readable() can use "binary: false" + "encoding: hex"', testText, singleComplexBuffer, 'readable', false, undefined, 'hex');94-test('.readable() can use "binary: false" + "preserveNewlines: true"', testText, complexChunksEnd, 'readable', false, true, 'utf8');95-test('.readable() can use "binary: false" + "preserveNewlines: false"', testText, complexChunks, 'readable', false, false, 'utf8');96-test('.duplex() can use "binary: true"', testText, singleComplexBuffer, 'duplex', true, undefined, 'utf8');97-test('.duplex() can use "binary: true" + "encoding: utf16le"', testText, singleComplexUtf16Buffer, 'duplex', true, undefined, 'utf16le');98-test('.duplex() can use "binary: true" + "encoding: buffer"', testText, singleComplexBuffer, 'duplex', true, undefined, 'buffer');99-test('.duplex() can use "binary: true" + "encoding: hex"', testText, singleComplexBuffer, 'duplex', true, undefined, 'hex');100-test('.duplex() can use "binary: undefined"', testText, singleComplexBuffer, 'duplex', undefined, undefined, 'utf8');101-test('.duplex() can use "binary: undefined" + "encoding: utf16le"', testText, singleComplexUtf16Buffer, 'duplex', undefined, undefined, 'utf16le');102-test('.duplex() can use "binary: undefined" + "encoding: "buffer"', testText, singleComplexBuffer, 'duplex', undefined, undefined, 'buffer');103-test('.duplex() can use "binary: undefined" + "encoding: "hex"', testText, singleComplexBuffer, 'duplex', undefined, undefined, 'hex');104-test('.duplex() can use "binary: false"', testText, complexChunksEnd, 'duplex', false, undefined, 'utf8');105-test('.duplex() can use "binary: false" + "encoding: utf16le"', testText, complexChunksEnd, 'duplex', false, undefined, 'utf16le');106-test('.duplex() can use "binary: false" + "encoding: buffer"', testText, singleComplexBuffer, 'duplex', false, undefined, 'buffer');107-test('.duplex() can use "binary: false" + "encoding: hex"', testText, singleComplexBuffer, 'duplex', false, undefined, 'hex');108-test('.duplex() can use "binary: false" + "preserveNewlines: true"', testText, complexChunksEnd, 'duplex', false, true, 'utf8');109-test('.duplex() can use "binary: false" + "preserveNewlines: false"', testText, complexChunks, 'duplex', false, false, 'utf8');110-111-const testTextOutput = async (t, expectedOutput, methodName, preserveNewlines) => {112- const subprocess = getSubprocess(methodName, complexFull);113- const stream = subprocess[methodName]({binary: false, preserveNewlines});114-115- await assertStreamOutput(t, stream, expectedOutput);116- await assertSubprocessOutput(t, subprocess, complexFull);117-};118-119-test('.readable() "binary: false" keeps output as is', testTextOutput, complexFull, 'readable', undefined);120-test('.readable() "binary: false" + "preserveNewlines: true" keeps output as is', testTextOutput, complexFull, 'readable', true);121-test('.readable() "binary: false" + "preserveNewlines: false" removes all newlines', testTextOutput, noNewlinesFull, 'readable', false);122-test('.duplex() "binary: false" keeps output as is', testTextOutput, complexFull, 'duplex', undefined);123-test('.duplex() "binary: false" + "preserveNewlines: true" keeps output as is', testTextOutput, complexFull, 'duplex', true);124-test('.duplex() "binary: false" + "preserveNewlines: false" removes all newlines', testTextOutput, noNewlinesFull, 'duplex', false);125-126-// eslint-disable-next-line max-params127-const testObjectMode = async (t, expectedChunks, methodName, encoding, initialObjectMode, finalObjectMode, binary, options) => {128- const subprocess = getSubprocess(methodName, simpleFull, options);129- if (encoding !== null) {130- subprocess.stdout.setEncoding(encoding);131- }132-133- t.is(subprocess.stdout.readableEncoding, encoding);134- t.is(subprocess.stdout.readableObjectMode, initialObjectMode);135- t.is(subprocess.stdout.readableHighWaterMark, getDefaultHighWaterMark(initialObjectMode));136-137- const stream = subprocess[methodName]({binary, preserveNewlines: true});138-139- if (methodName !== 'iterable') {140- t.is(stream.readableEncoding, encoding);141- t.is(stream.readableObjectMode, finalObjectMode);142- t.is(stream.readableHighWaterMark, getDefaultHighWaterMark(finalObjectMode));143- }144-145- t.is(subprocess.stdout.readableEncoding, encoding);146- t.is(subprocess.stdout.readableObjectMode, initialObjectMode);147- t.is(subprocess.stdout.readableHighWaterMark, getDefaultHighWaterMark(initialObjectMode));148-149- await assertChunks(t, stream, expectedChunks, methodName);150- await subprocess;151-};152-153-test('.iterable() uses Uint8Arrays with "binary: true"', testObjectMode, simpleChunksUint8Array, 'iterable', null, false, false, true);154-test('.iterable() uses Uint8Arrays with "binary: true" and .setEncoding("utf8")', testObjectMode, simpleChunksUint8Array, 'iterable', 'utf8', false, false, true);155-test('.iterable() uses Uint8Arrays with "binary: true", .setEncoding("utf8") and "encoding: buffer"', testObjectMode, simpleChunksUint8Array, 'iterable', 'utf8', false, false, true, {encoding: 'buffer'});156-test('.iterable() uses strings in objectMode with "binary: true" and object transforms', testObjectMode, foobarObjectChunks, 'iterable', null, true, true, true, {stdout: outputObjectGenerator()});157-test('.iterable() uses strings in objectMode with "binary: false"', testObjectMode, simpleLines, 'iterable', null, false, true, false);158-test('.iterable() uses strings in objectMode with "binary: false" and .setEncoding("utf8")', testObjectMode, simpleLines, 'iterable', 'utf8', false, true, false);159-test('.iterable() uses Uint8Arrays in objectMode with "binary: false", .setEncoding("utf8") and "encoding: buffer"', testObjectMode, simpleChunksUint8Array, 'iterable', 'utf8', false, true, false, {encoding: 'buffer'});160-test('.iterable() uses strings in objectMode with "binary: false" and object transforms', testObjectMode, foobarObjectChunks, 'iterable', null, true, true, false, {stdout: outputObjectGenerator()});161-test('.readable() uses Buffers with "binary: true"', testObjectMode, simpleChunksBuffer, 'readable', null, false, false, true);162-test('.readable() uses strings with "binary: true" and .setEncoding("utf8")', testObjectMode, simpleChunks, 'readable', 'utf8', false, false, true);163-test('.readable() uses strings with "binary: true", .setEncoding("utf8") and "encoding: buffer"', testObjectMode, simpleChunks, 'readable', 'utf8', false, false, true, {encoding: 'buffer'});164-test('.readable() uses strings in objectMode with "binary: true" and object transforms', testObjectMode, foobarObjectChunks, 'readable', null, true, true, true, {stdout: outputObjectGenerator()});165-test('.readable() uses strings in objectMode with "binary: false"', testObjectMode, simpleLines, 'readable', null, false, true, false);166-test('.readable() uses strings in objectMode with "binary: false" and .setEncoding("utf8")', testObjectMode, simpleLines, 'readable', 'utf8', false, true, false);167-test('.readable() uses strings in objectMode with "binary: false", .setEncoding("utf8") and "encoding: buffer"', testObjectMode, simpleChunks, 'readable', 'utf8', false, false, false, {encoding: 'buffer'});168-test('.readable() uses strings in objectMode with "binary: false" and object transforms', testObjectMode, foobarObjectChunks, 'readable', null, true, true, false, {stdout: outputObjectGenerator()});169-test('.duplex() uses Buffers with "binary: true"', testObjectMode, simpleChunksBuffer, 'duplex', null, false, false, true);170-test('.duplex() uses strings with "binary: true" and .setEncoding("utf8")', testObjectMode, simpleChunks, 'duplex', 'utf8', false, false, true);171-test('.duplex() uses strings with "binary: true", .setEncoding("utf8") and "encoding: buffer"', testObjectMode, simpleChunks, 'duplex', 'utf8', false, false, true, {encoding: 'buffer'});172-test('.duplex() uses strings in objectMode with "binary: true" and object transforms', testObjectMode, foobarObjectChunks, 'duplex', null, true, true, true, {stdout: outputObjectGenerator()});173-test('.duplex() uses strings in objectMode with "binary: false"', testObjectMode, simpleLines, 'duplex', null, false, true, false);174-test('.duplex() uses strings in objectMode with "binary: false" and .setEncoding("utf8")', testObjectMode, simpleLines, 'duplex', 'utf8', false, true, false);175-test('.duplex() uses strings in objectMode with "binary: false", .setEncoding("utf8") and "encoding: buffer"', testObjectMode, simpleChunks, 'duplex', 'utf8', false, false, false, {encoding: 'buffer'});176-test('.duplex() uses strings in objectMode with "binary: false" and object transforms', testObjectMode, foobarObjectChunks, 'duplex', null, true, true, false, {stdout: outputObjectGenerator()});177-178-const testObjectSplit = async (t, methodName) => {179- const subprocess = getSubprocess(methodName, foobarString, {stdout: getOutputGenerator(simpleFull)(true)});180- const stream = subprocess[methodName]({binary: false});181- await assertChunks(t, stream, [simpleFull], methodName);182- await subprocess;183-};184-185-test('.iterable() "binary: false" does not split lines of strings produced by object transforms', testObjectSplit, 'iterable');186-test('.readable() "binary: false" does not split lines of strings produced by object transforms', testObjectSplit, 'readable');187-test('.duplex() "binary: false" does not split lines of strings produced by object transforms', testObjectSplit, 'duplex');188-189-const testMultibyteCharacters = async (t, methodName) => {190- const subprocess = getReadWriteSubprocess();191- const stream = subprocess[methodName]({binary: false});192- const assertPromise = assertChunks(t, stream, [`${multibyteChar}${brokenSymbol}`], methodName);193- subprocess.stdin.write(multibyteUint8Array.slice(0, breakingLength));194- await once(subprocess.stdout, 'data');195- subprocess.stdin.end();196- await assertPromise;197-};198-199-test('.iterable() "binary: false" handles partial multibyte characters', testMultibyteCharacters, 'iterable');200-test('.readable() "binary: false" handles partial multibyte characters', testMultibyteCharacters, 'readable');201-test('.duplex() "binary: false" handles partial multibyte characters', testMultibyteCharacters, 'duplex');deleted:test/exit/cancel.js-92 removed
1-import {once} from 'node:events';2-import test from 'ava';3-import {execa, execaSync} from '../../index.js';4-import {setFixtureDir} from '../helpers/fixtures-dir.js';5-6-setFixtureDir();7-8-test('result.isCanceled is false when abort isn\'t called (success)', async t => {9- const {isCanceled} = await execa('noop.js');10- t.false(isCanceled);11-});12-13-test('result.isCanceled is false when abort isn\'t called (failure)', async t => {14- const {isCanceled} = await t.throwsAsync(execa('fail.js'));15- t.false(isCanceled);16-});17-18-test('result.isCanceled is false when abort isn\'t called in sync mode (success)', t => {19- const {isCanceled} = execaSync('noop.js');20- t.false(isCanceled);21-});22-23-test('result.isCanceled is false when abort isn\'t called in sync mode (failure)', t => {24- const {isCanceled} = t.throws(() => {25- execaSync('fail.js');26- });27- t.false(isCanceled);28-});29-30-test('error.isCanceled is true when abort is used', async t => {31- const abortController = new AbortController();32- const subprocess = execa('noop.js', {cancelSignal: abortController.signal});33- abortController.abort();34- const {isCanceled} = await t.throwsAsync(subprocess);35- t.true(isCanceled);36-});37-38-test('error.isCanceled is false when kill method is used', async t => {39- const abortController = new AbortController();40- const subprocess = execa('noop.js', {cancelSignal: abortController.signal});41- subprocess.kill();42- const {isCanceled} = await t.throwsAsync(subprocess);43- t.false(isCanceled);44-});45-46-test('calling abort is considered a signal termination', async t => {47- const abortController = new AbortController();48- const subprocess = execa('forever.js', {cancelSignal: abortController.signal});49- await once(subprocess, 'spawn');50- abortController.abort();51- const {isTerminated, signal} = await t.throwsAsync(subprocess);52- t.true(isTerminated);53- t.is(signal, 'SIGTERM');54-});55-56-test('calling abort throws an error with message "Command was canceled"', async t => {57- const abortController = new AbortController();58- const subprocess = execa('noop.js', {cancelSignal: abortController.signal});59- abortController.abort();60- await t.throwsAsync(subprocess, {message: /Command was canceled/});61-});62-63-test('calling abort twice should show the same behaviour as calling it once', async t => {64- const abortController = new AbortController();65- const subprocess = execa('noop.js', {cancelSignal: abortController.signal});66- abortController.abort();67- abortController.abort();68- const {isCanceled} = await t.throwsAsync(subprocess);69- t.true(isCanceled);70-});71-72-test('calling abort on a successfully completed subprocess does not make result.isCanceled true', async t => {73- const abortController = new AbortController();74- const subprocess = execa('noop.js', {cancelSignal: abortController.signal});75- const result = await subprocess;76- abortController.abort();77- t.false(result.isCanceled);78-});79-80-test('Throws when using the former "signal" option name', t => {81- const abortController = new AbortController();82- t.throws(() => {83- execa('empty.js', {signal: abortController.signal});84- }, {message: /renamed to "cancelSignal"/});85-});86-87-test('Cannot use cancelSignal, sync', t => {88- const abortController = new AbortController();89- t.throws(() => {90- execaSync('empty.js', {cancelSignal: abortController.signal});91- }, {message: /The "cancelSignal" option cannot be used/});92-});deleted:test/exit/cleanup.js-102 removed
1-import process from 'node:process';2-import {setTimeout} from 'node:timers/promises';3-import test from 'ava';4-import {pEvent} from 'p-event';5-import isRunning from 'is-running';6-import {execa, execaSync} from '../../index.js';7-import {setFixtureDir} from '../helpers/fixtures-dir.js';8-import {nestedExecaAsync, nestedWorker} from '../helpers/nested.js';9-import {foobarString} from '../helpers/input.js';10-11-setFixtureDir();12-13-const isWindows = process.platform === 'win32';14-15-// When subprocess exits before current process16-const spawnAndExit = async (t, execaMethod, cleanup, detached) => {17- const {stdout} = await execaMethod('noop-fd.js', ['1', foobarString], {cleanup, detached});18- t.is(stdout, foobarString);19-};20-21-test('spawnAndExit', spawnAndExit, nestedExecaAsync, false, false);22-test('spawnAndExit cleanup', spawnAndExit, nestedExecaAsync, true, false);23-test('spawnAndExit detached', spawnAndExit, nestedExecaAsync, false, true);24-test('spawnAndExit cleanup detached', spawnAndExit, nestedExecaAsync, true, true);25-test('spawnAndExit, worker', spawnAndExit, nestedWorker, false, false);26-test('spawnAndExit cleanup, worker', spawnAndExit, nestedWorker, true, false);27-test('spawnAndExit detached, worker', spawnAndExit, nestedWorker, false, true);28-test('spawnAndExit cleanup detached, worker', spawnAndExit, nestedWorker, true, true);29-30-// When current process exits before subprocess31-const spawnAndKill = async (t, [signal, cleanup, detached, isKilled]) => {32- const subprocess = execa('subprocess.js', [cleanup, detached], {stdio: 'ignore', ipc: true});33-34- const pid = await pEvent(subprocess, 'message');35- t.true(Number.isInteger(pid));36- t.true(isRunning(pid));37-38- process.kill(subprocess.pid, signal);39-40- await t.throwsAsync(subprocess);41- t.false(isRunning(subprocess.pid));42-43- if (isKilled) {44- await Promise.race([45- setTimeout(1e4, undefined, {ref: false}),46- pollForSubprocessExit(pid),47- ]);48- t.is(isRunning(pid), false);49- } else {50- t.is(isRunning(pid), true);51- process.kill(pid, 'SIGKILL');52- }53-};54-55-const pollForSubprocessExit = async pid => {56- while (isRunning(pid)) {57- // eslint-disable-next-line no-await-in-loop58- await setTimeout(100);59- }60-};61-62-// Without `options.cleanup`:63-// - on Windows subprocesses are killed if `options.detached: false`, but not64-// if `options.detached: true`65-// - on Linux subprocesses are never killed regardless of `options.detached`66-// With `options.cleanup`, subprocesses are always killed67-// - `options.cleanup` with SIGKILL is a noop, since it cannot be handled68-test('spawnAndKill SIGTERM', spawnAndKill, ['SIGTERM', false, false, isWindows]);69-test('spawnAndKill SIGKILL', spawnAndKill, ['SIGKILL', false, false, isWindows]);70-test('spawnAndKill cleanup SIGTERM', spawnAndKill, ['SIGTERM', true, false, true]);71-test('spawnAndKill cleanup SIGKILL', spawnAndKill, ['SIGKILL', true, false, isWindows]);72-test('spawnAndKill detached SIGTERM', spawnAndKill, ['SIGTERM', false, true, false]);73-test('spawnAndKill detached SIGKILL', spawnAndKill, ['SIGKILL', false, true, false]);74-test('spawnAndKill cleanup detached SIGTERM', spawnAndKill, ['SIGTERM', true, true, false]);75-test('spawnAndKill cleanup detached SIGKILL', spawnAndKill, ['SIGKILL', true, true, false]);76-77-// See #12878-test('removes exit handler on exit', async t => {79- // @todo this relies on `signal-exit` internals80- const exitListeners = globalThis[Symbol.for('signal-exit emitter')].listeners.exit;81-82- const subprocess = execa('noop.js');83- const listener = exitListeners.at(-1);84-85- await subprocess;86- t.false(exitListeners.includes(listener));87-});88-89-test('detach subprocess', async t => {90- const {stdout} = await execa('detach.js');91- const pid = Number(stdout);92- t.true(Number.isInteger(pid));93- t.true(isRunning(pid));94-95- process.kill(pid, 'SIGKILL');96-});97-98-test('Cannot use "detached" option, sync', t => {99- t.throws(() => {100- execaSync('empty.js', {detached: true});101- }, {message: /The "detached: true" option cannot be used/});102-});deleted:test/exit/kill-error.js-83 removed
1-import {once} from 'node:events';2-import {setImmediate} from 'node:timers/promises';3-import test from 'ava';4-import isRunning from 'is-running';5-import {execa} from '../../index.js';6-import {setFixtureDir} from '../helpers/fixtures-dir.js';7-8-setFixtureDir();9-10-test('.kill(error) propagates error', async t => {11- const subprocess = execa('forever.js');12- const originalMessage = 'test';13- const cause = new Error(originalMessage);14- t.true(subprocess.kill(cause));15- const error = await t.throwsAsync(subprocess);16- t.is(error.cause, cause);17- t.true(cause.stack.includes(import.meta.url));18- t.is(error.exitCode, undefined);19- t.is(error.signal, 'SIGTERM');20- t.true(error.isTerminated);21- t.is(error.originalMessage, originalMessage);22- t.true(error.message.includes(originalMessage));23- t.true(error.message.includes('was killed with SIGTERM'));24-});25-26-test('.kill(error) uses killSignal', async t => {27- const subprocess = execa('forever.js', {killSignal: 'SIGINT'});28- const cause = new Error('test');29- subprocess.kill(cause);30- const error = await t.throwsAsync(subprocess);31- t.is(error.cause, cause);32- t.is(error.signal, 'SIGINT');33-});34-35-test('.kill(signal, error) uses signal', async t => {36- const subprocess = execa('forever.js');37- const cause = new Error('test');38- subprocess.kill('SIGINT', cause);39- const error = await t.throwsAsync(subprocess);40- t.is(error.cause, cause);41- t.is(error.signal, 'SIGINT');42-});43-44-test('.kill(error) is a noop if subprocess already exited', async t => {45- const subprocess = execa('empty.js');46- await subprocess;47- t.false(isRunning(subprocess.pid));48- t.false(subprocess.kill(new Error('test')));49-});50-51-test('.kill(error) terminates but does not change the error if the subprocess already errored but did not exit yet', async t => {52- const subprocess = execa('forever.js');53- const cause = new Error('first');54- subprocess.stdout.destroy(cause);55- await setImmediate();56- const secondError = new Error('second');57- t.true(subprocess.kill(secondError));58- const error = await t.throwsAsync(subprocess);59- t.is(error.cause, cause);60- t.is(error.exitCode, undefined);61- t.is(error.signal, 'SIGTERM');62- t.true(error.isTerminated);63- t.false(error.message.includes(secondError.message));64-});65-66-test('.kill(error) twice in a row', async t => {67- const subprocess = execa('forever.js');68- const cause = new Error('first');69- subprocess.kill(cause);70- const secondCause = new Error('second');71- subprocess.kill(secondCause);72- const error = await t.throwsAsync(subprocess);73- t.is(error.cause, cause);74- t.false(error.message.includes(secondCause.message));75-});76-77-test('.kill(error) does not emit the "error" event', async t => {78- const subprocess = execa('forever.js');79- const cause = new Error('test');80- subprocess.kill(cause);81- const error = await Promise.race([t.throwsAsync(subprocess), once(subprocess, 'error')]);82- t.is(error.cause, cause);83-});deleted:test/exit/kill-force.js-140 removed
1-import process from 'node:process';2-import {once, defaultMaxListeners} from 'node:events';3-import {constants} from 'node:os';4-import {setTimeout} from 'node:timers/promises';5-import test from 'ava';6-import {pEvent} from 'p-event';7-import isRunning from 'is-running';8-import {execa} from '../../index.js';9-import {setFixtureDir} from '../helpers/fixtures-dir.js';10-import {assertMaxListeners} from '../helpers/listeners.js';11-12-setFixtureDir();13-14-const isWindows = process.platform === 'win32';15-16-const spawnNoKillable = async (forceKillAfterDelay, options) => {17- const subprocess = execa('no-killable.js', {18- ipc: true,19- forceKillAfterDelay,20- ...options,21- });22- await pEvent(subprocess, 'message');23- return {subprocess};24-};25-26-const spawnNoKillableSimple = options => execa('forever.js', {killSignal: 'SIGWINCH', forceKillAfterDelay: 1, ...options});27-28-test('kill("SIGKILL") should terminate cleanly', async t => {29- const {subprocess} = await spawnNoKillable();30-31- subprocess.kill('SIGKILL');32-33- const {isTerminated, signal} = await t.throwsAsync(subprocess);34- t.true(isTerminated);35- t.is(signal, 'SIGKILL');36-});37-38-const testInvalidForceKill = async (t, forceKillAfterDelay) => {39- t.throws(() => {40- execa('empty.js', {forceKillAfterDelay});41- }, {instanceOf: TypeError, message: /non-negative integer/});42-};43-44-test('`forceKillAfterDelay` should not be NaN', testInvalidForceKill, Number.NaN);45-test('`forceKillAfterDelay` should not be negative', testInvalidForceKill, -1);46-47-// `SIGTERM` cannot be caught on Windows, and it always aborts the subprocess (like `SIGKILL` on Unix).48-// Therefore, this feature and those tests must be different on Windows.49-if (isWindows) {50- test('Can call `.kill()` with `forceKillAfterDelay` on Windows', async t => {51- const {subprocess} = await spawnNoKillable(1);52- subprocess.kill();53-54- const {isTerminated, signal} = await t.throwsAsync(subprocess);55- t.true(isTerminated);56- t.is(signal, 'SIGTERM');57- });58-} else {59- const testNoForceKill = async (t, forceKillAfterDelay, killArgument, options) => {60- const {subprocess} = await spawnNoKillable(forceKillAfterDelay, options);61-62- subprocess.kill(killArgument);63-64- await setTimeout(6e3);65- t.true(isRunning(subprocess.pid));66- subprocess.kill('SIGKILL');67-68- const {isTerminated, signal} = await t.throwsAsync(subprocess);69- t.true(isTerminated);70- t.is(signal, 'SIGKILL');71- };72-73- test('`forceKillAfterDelay: false` should not kill after a timeout', testNoForceKill, false);74- test('`forceKillAfterDelay` should not kill after a timeout with other signals', testNoForceKill, true, 'SIGINT');75- test('`forceKillAfterDelay` should not kill after a timeout with wrong killSignal string', testNoForceKill, true, 'SIGTERM', {killSignal: 'SIGINT'});76- test('`forceKillAfterDelay` should not kill after a timeout with wrong killSignal number', testNoForceKill, true, constants.signals.SIGTERM, {killSignal: constants.signals.SIGINT});77-78- const testForceKill = async (t, forceKillAfterDelay, killArgument, options) => {79- const {subprocess} = await spawnNoKillable(forceKillAfterDelay, options);80-81- subprocess.kill(killArgument);82-83- const {isTerminated, signal} = await t.throwsAsync(subprocess);84- t.true(isTerminated);85- t.is(signal, 'SIGKILL');86- };87-88- test('`forceKillAfterDelay: number` should kill after a timeout', testForceKill, 50);89- test('`forceKillAfterDelay: true` should kill after a timeout', testForceKill, true);90- test('`forceKillAfterDelay: undefined` should kill after a timeout', testForceKill, undefined);91- test('`forceKillAfterDelay` should kill after a timeout with SIGTERM', testForceKill, 50, 'SIGTERM');92- test('`forceKillAfterDelay` should kill after a timeout with the killSignal string', testForceKill, 50, 'SIGINT', {killSignal: 'SIGINT'});93- test('`forceKillAfterDelay` should kill after a timeout with the killSignal number', testForceKill, 50, constants.signals.SIGINT, {killSignal: constants.signals.SIGINT});94- test('`forceKillAfterDelay` should kill after a timeout with an error', testForceKill, 50, new Error('test'));95- test('`forceKillAfterDelay` should kill after a timeout with an error and a killSignal', testForceKill, 50, new Error('test'), {killSignal: 'SIGINT'});96-97- test('`forceKillAfterDelay` works with the "signal" option', async t => {98- const abortController = new AbortController();99- const subprocess = spawnNoKillableSimple({cancelSignal: abortController.signal});100- await once(subprocess, 'spawn');101- abortController.abort();102- const {isTerminated, signal, isCanceled} = await t.throwsAsync(subprocess);103- t.true(isTerminated);104- t.is(signal, 'SIGKILL');105- t.true(isCanceled);106- });107-108- test('`forceKillAfterDelay` works with the "timeout" option', async t => {109- const subprocess = spawnNoKillableSimple({timeout: 1});110- const {isTerminated, signal, timedOut} = await t.throwsAsync(subprocess);111- t.true(isTerminated);112- t.is(signal, 'SIGKILL');113- t.true(timedOut);114- });115-116- test.serial('Can call `.kill()` with `forceKillAfterDelay` many times without triggering the maxListeners warning', async t => {117- const checkMaxListeners = assertMaxListeners(t);118-119- const subprocess = spawnNoKillableSimple();120- for (let index = 0; index < defaultMaxListeners + 1; index += 1) {121- subprocess.kill();122- }123-124- const {isTerminated, signal} = await t.throwsAsync(subprocess);125- t.true(isTerminated);126- t.is(signal, 'SIGKILL');127-128- checkMaxListeners();129- });130-131- test('Can call `.kill()` with `forceKillAfterDelay` multiple times', async t => {132- const subprocess = spawnNoKillableSimple();133- subprocess.kill();134- subprocess.kill();135-136- const {isTerminated, signal} = await t.throwsAsync(subprocess);137- t.true(isTerminated);138- t.is(signal, 'SIGKILL');139- });140-}deleted:test/exit/kill-signal.js-95 removed
1-import {once} from 'node:events';2-import {setImmediate} from 'node:timers/promises';3-import test from 'ava';4-import {execa} from '../../index.js';5-import {setFixtureDir} from '../helpers/fixtures-dir.js';6-7-setFixtureDir();8-9-test('Can call `.kill()` multiple times', async t => {10- const subprocess = execa('forever.js');11- subprocess.kill();12- subprocess.kill();13-14- const {isTerminated, signal} = await t.throwsAsync(subprocess);15- t.true(isTerminated);16- t.is(signal, 'SIGTERM');17-});18-19-test('execa() returns a promise with kill()', async t => {20- const subprocess = execa('noop.js', ['foo']);21- t.is(typeof subprocess.kill, 'function');22- await subprocess;23-});24-25-const testInvalidKillArgument = async (t, killArgument, secondKillArgument) => {26- const subprocess = execa('empty.js');27- const message = secondKillArgument instanceof Error || secondKillArgument === undefined28- ? /error instance or a signal name/29- : /second argument is optional/;30- t.throws(() => {31- subprocess.kill(killArgument, secondKillArgument);32- }, {message});33- await subprocess;34-};35-36-test('Cannot call .kill(null)', testInvalidKillArgument, null);37-test('Cannot call .kill(0n)', testInvalidKillArgument, 0n);38-test('Cannot call .kill(true)', testInvalidKillArgument, true);39-test('Cannot call .kill(errorObject)', testInvalidKillArgument, {name: '', message: '', stack: ''});40-test('Cannot call .kill(errorArray)', testInvalidKillArgument, [new Error('test')]);41-test('Cannot call .kill(undefined, true)', testInvalidKillArgument, undefined, true);42-test('Cannot call .kill("SIGTERM", true)', testInvalidKillArgument, 'SIGTERM', true);43-test('Cannot call .kill(true, error)', testInvalidKillArgument, true, new Error('test'));44-45-test('subprocess errors are handled before spawn', async t => {46- const subprocess = execa('forever.js');47- const cause = new Error('test');48- subprocess.emit('error', cause);49- subprocess.kill();50- const error = await t.throwsAsync(subprocess);51- t.is(error.cause, cause);52- t.is(error.exitCode, undefined);53- t.is(error.signal, undefined);54- t.false(error.isTerminated);55-});56-57-test('subprocess errors are handled after spawn', async t => {58- const subprocess = execa('forever.js');59- await once(subprocess, 'spawn');60- const cause = new Error('test');61- subprocess.emit('error', cause);62- subprocess.kill();63- const error = await t.throwsAsync(subprocess);64- t.is(error.cause, cause);65- t.is(error.exitCode, undefined);66- t.is(error.signal, 'SIGTERM');67- t.true(error.isTerminated);68-});69-70-test('subprocess double errors are handled after spawn', async t => {71- const abortController = new AbortController();72- const subprocess = execa('forever.js', {cancelSignal: abortController.signal});73- await once(subprocess, 'spawn');74- const cause = new Error('test');75- subprocess.emit('error', cause);76- await setImmediate();77- abortController.abort();78- const error = await t.throwsAsync(subprocess);79- t.is(error.cause, cause);80- t.is(error.exitCode, undefined);81- t.is(error.signal, 'SIGTERM');82- t.true(error.isTerminated);83-});84-85-test('subprocess errors use killSignal', async t => {86- const subprocess = execa('forever.js', {killSignal: 'SIGINT'});87- await once(subprocess, 'spawn');88- const cause = new Error('test');89- subprocess.emit('error', cause);90- subprocess.kill();91- const error = await t.throwsAsync(subprocess);92- t.is(error.cause, cause);93- t.true(error.isTerminated);94- t.is(error.signal, 'SIGINT');95-});deleted:test/exit/timeout.js-76 removed
1-import test from 'ava';2-import {execa, execaSync} from '../../index.js';3-import {setFixtureDir, FIXTURES_DIR} from '../helpers/fixtures-dir.js';4-5-setFixtureDir();6-7-test('timeout kills the subprocess if it times out', async t => {8- const {isTerminated, signal, timedOut, originalMessage, shortMessage, message} = await t.throwsAsync(execa('forever.js', {timeout: 1}));9- t.true(isTerminated);10- t.is(signal, 'SIGTERM');11- t.true(timedOut);12- t.is(originalMessage, '');13- t.is(shortMessage, 'Command timed out after 1 milliseconds: forever.js');14- t.is(message, shortMessage);15-});16-17-test('timeout kills the subprocess if it times out, in sync mode', async t => {18- const {isTerminated, signal, timedOut, originalMessage, shortMessage, message} = await t.throws(() => {19- execaSync('node', ['forever.js'], {timeout: 1, cwd: FIXTURES_DIR});20- });21- t.true(isTerminated);22- t.is(signal, 'SIGTERM');23- t.true(timedOut);24- t.is(originalMessage, 'spawnSync node ETIMEDOUT');25- t.is(shortMessage, `Command timed out after 1 milliseconds: node forever.js\n${originalMessage}`);26- t.is(message, shortMessage);27-});28-29-test('timeout does not kill the subprocess if it does not time out', async t => {30- const {timedOut} = await execa('delay.js', ['500'], {timeout: 1e8});31- t.false(timedOut);32-});33-34-test('timeout uses killSignal', async t => {35- const {isTerminated, signal, timedOut} = await t.throwsAsync(execa('forever.js', {timeout: 1, killSignal: 'SIGINT'}));36- t.true(isTerminated);37- t.is(signal, 'SIGINT');38- t.true(timedOut);39-});40-41-const INVALID_TIMEOUT_REGEXP = /`timeout` option to be a non-negative integer/;42-43-const testTimeoutValidation = (t, timeout, execaMethod) => {44- t.throws(() => {45- execaMethod('empty.js', {timeout});46- }, {message: INVALID_TIMEOUT_REGEXP});47-};48-49-test('timeout must not be negative', testTimeoutValidation, -1, execa);50-test('timeout must be an integer', testTimeoutValidation, false, execa);51-test('timeout must not be negative - sync', testTimeoutValidation, -1, execaSync);52-test('timeout must be an integer - sync', testTimeoutValidation, false, execaSync);53-54-test('timedOut is false if timeout is undefined', async t => {55- const {timedOut} = await execa('noop.js');56- t.false(timedOut);57-});58-59-test('timedOut is false if timeout is 0', async t => {60- const {timedOut} = await execa('noop.js', {timeout: 0});61- t.false(timedOut);62-});63-64-test('timedOut is false if timeout is undefined and exit code is 0 in sync mode', t => {65- const {timedOut} = execaSync('noop.js');66- t.false(timedOut);67-});68-69-test('timedOut is true if the timeout happened after a different error occurred', async t => {70- const subprocess = execa('forever.js', {timeout: 1e3});71- const cause = new Error('test');72- subprocess.emit('error', cause);73- const error = await t.throwsAsync(subprocess);74- t.is(error.cause, cause);75- t.true(error.timedOut);76-});added:test/io/input-option.js+43 added
1+import {Writable} from 'node:stream';2+import test from 'ava';3+import {execa, execaSync} from '../../index.js';4+import {setFixtureDir} from '../helpers/fixtures-dir.js';5+import {runExeca, runExecaSync, runScript, runScriptSync} from '../helpers/run.js';6+import {foobarUint8Array, foobarBuffer, foobarArrayBuffer, foobarUint16Array, foobarDataView} from '../helpers/input.js';7+8+setFixtureDir();9+10+const testInput = async (t, input, execaMethod) => {11+ const {stdout} = await execaMethod('stdin.js', {input});12+ t.is(stdout, 'foobar');13+};14+15+test('input option can be a String', testInput, 'foobar', runExeca);16+test('input option can be a Uint8Array', testInput, foobarUint8Array, runExeca);17+test('input option can be a String - sync', testInput, 'foobar', runExecaSync);18+test('input option can be a Uint8Array - sync', testInput, foobarUint8Array, runExecaSync);19+test('input option can be used with $', testInput, 'foobar', runScript);20+test('input option can be used with $.sync', testInput, 'foobar', runScriptSync);21+22+const testInvalidInput = async (t, input, execaMethod) => {23+ t.throws(() => {24+ execaMethod('empty.js', {input});25+ }, {message: /a string, a Uint8Array/});26+};27+28+test('input option cannot be a Buffer', testInvalidInput, foobarBuffer, execa);29+test('input option cannot be an ArrayBuffer', testInvalidInput, foobarArrayBuffer, execa);30+test('input option cannot be a DataView', testInvalidInput, foobarDataView, execa);31+test('input option cannot be a Uint16Array', testInvalidInput, foobarUint16Array, execa);32+test('input option cannot be 0', testInvalidInput, 0, execa);33+test('input option cannot be false', testInvalidInput, false, execa);34+test('input option cannot be null', testInvalidInput, null, execa);35+test('input option cannot be a non-Readable stream', testInvalidInput, new Writable(), execa);36+test('input option cannot be a Buffer - sync', testInvalidInput, foobarBuffer, execaSync);37+test('input option cannot be an ArrayBuffer - sync', testInvalidInput, foobarArrayBuffer, execaSync);38+test('input option cannot be a DataView - sync', testInvalidInput, foobarDataView, execaSync);39+test('input option cannot be a Uint16Array - sync', testInvalidInput, foobarUint16Array, execaSync);40+test('input option cannot be 0 - sync', testInvalidInput, 0, execaSync);41+test('input option cannot be false - sync', testInvalidInput, false, execaSync);42+test('input option cannot be null - sync', testInvalidInput, null, execaSync);43+test('input option cannot be a non-Readable stream - sync', testInvalidInput, new Writable(), execaSync);added:test/io/input-sync.js+18 added
1+import test from 'ava';2+import {execaSync} from '../../index.js';3+import {setFixtureDir} from '../helpers/fixtures-dir.js';4+import {getStdio} from '../helpers/stdio.js';5+6+setFixtureDir();7+8+const getFd3InputMessage = type => `not \`stdio[3]\`, can be ${type}`;9+10+const testFd3InputSync = (t, stdioOption, expectedMessage) => {11+ const {message} = t.throws(() => {12+ execaSync('empty.js', getStdio(3, stdioOption));13+ });14+ t.true(message.includes(expectedMessage));15+};16+17+test('Cannot use Uint8Array with stdio[*], sync', testFd3InputSync, new Uint8Array(), getFd3InputMessage('a Uint8Array'));18+test('Cannot use iterable with stdio[*], sync', testFd3InputSync, [[]], getFd3InputMessage('an iterable'));added:test/io/iterate.js+201 added
1+import {once} from 'node:events';2+import {getDefaultHighWaterMark} from 'node:stream';3+import test from 'ava';4+import {setFixtureDir} from '../helpers/fixtures-dir.js';5+import {6+ assertStreamOutput,7+ assertIterableChunks,8+ assertStreamChunks,9+ assertSubprocessOutput,10+ getReadableSubprocess,11+ getReadWriteSubprocess,12+} from '../helpers/convert.js';13+import {14+ stringToUint8Arrays,15+ simpleFull,16+ simpleChunks,17+ simpleChunksBuffer,18+ simpleChunksUint8Array,19+ simpleLines,20+ noNewlinesFull,21+ complexFull,22+ complexFullUtf16,23+ complexFullUtf16Uint8Array,24+ singleComplexBuffer,25+ singleComplexUtf16Buffer,26+ singleComplexUint8Array,27+ singleComplexHex,28+ complexChunks,29+ complexChunksEnd,30+} from '../helpers/lines.js';31+import {outputObjectGenerator, getOutputGenerator} from '../helpers/generator.js';32+import {foobarString, foobarObject} from '../helpers/input.js';33+import {multibyteChar, multibyteUint8Array, breakingLength, brokenSymbol} from '../helpers/encoding.js';34+35+setFixtureDir();36+37+const foobarObjectChunks = [foobarObject, foobarObject, foobarObject];38+39+const getSubprocess = (methodName, output, options) => {40+ if (methodName !== 'duplex') {41+ return getReadableSubprocess(output, options);42+ }43+44+ const subprocess = getReadWriteSubprocess(options);45+ subprocess.stdin.end(output);46+ return subprocess;47+};48+49+const assertChunks = async (t, streamOrIterable, expectedChunks, methodName) => {50+ const assertMethod = methodName === 'iterable' ? assertIterableChunks : assertStreamChunks;51+ await assertMethod(t, streamOrIterable, expectedChunks);52+};53+54+// eslint-disable-next-line max-params55+const testText = async (t, expectedChunks, methodName, binary, preserveNewlines, encoding) => {56+ const subprocess = getReadWriteSubprocess({encoding});57+ const input = encoding === 'utf16le' ? complexFullUtf16 : complexFull;58+ subprocess.stdin.end(input);59+ const stream = subprocess[methodName]({binary, preserveNewlines});60+61+ await assertChunks(t, stream, expectedChunks, methodName);62+ const expectedOutput = encoding === 'hex'63+ ? singleComplexHex64+ : stringToUint8Arrays(complexFull, encoding === 'buffer');65+ await assertSubprocessOutput(t, subprocess, expectedOutput);66+};67+68+test('.iterable() can use "binary: true"', testText, [singleComplexUint8Array], 'iterable', true, undefined, 'utf8');69+test('.iterable() can use "binary: true" + "encoding: utf16le"', testText, [complexFullUtf16Uint8Array], 'iterable', true, undefined, 'utf16le');70+test('.iterable() can use "binary: true" + "encoding: "buffer"', testText, [singleComplexUint8Array], 'iterable', true, undefined, 'buffer');71+test('.iterable() can use "binary: true" + "encoding: "hex"', testText, [singleComplexUint8Array], 'iterable', true, undefined, 'hex');72+test('.iterable() can use "binary: undefined"', testText, complexChunks, 'iterable', undefined, undefined, 'utf8');73+test('.iterable() can use "binary: undefined" + "encoding: utf16le"', testText, complexChunks, 'iterable', undefined, undefined, 'utf16le');74+test('.iterable() can use "binary: undefined" + "encoding: buffer"', testText, [singleComplexUint8Array], 'iterable', undefined, undefined, 'buffer');75+test('.iterable() can use "binary: undefined" + "encoding: hex"', testText, [singleComplexUint8Array], 'iterable', undefined, undefined, 'hex');76+test('.iterable() can use "binary: false"', testText, complexChunks, 'iterable', false, undefined, 'utf8');77+test('.iterable() can use "binary: false" + "encoding: utf16le"', testText, complexChunks, 'iterable', false, undefined, 'utf16le');78+test('.iterable() can use "binary: false" + "encoding: buffer"', testText, [singleComplexUint8Array], 'iterable', false, undefined, 'buffer');79+test('.iterable() can use "binary: false" + "encoding: hex"', testText, [singleComplexUint8Array], 'iterable', false, undefined, 'hex');80+test('.iterable() can use "binary: false" + "preserveNewlines: true"', testText, complexChunksEnd, 'iterable', false, true, 'utf8');81+test('.iterable() can use "binary: false" + "preserveNewlines: false"', testText, complexChunks, 'iterable', false, false, 'utf8');82+test('.readable() can use "binary: true"', testText, singleComplexBuffer, 'readable', true, undefined, 'utf8');83+test('.readable() can use "binary: true" + "encoding: utf16le"', testText, singleComplexUtf16Buffer, 'readable', true, undefined, 'utf16le');84+test('.readable() can use "binary: true" + "encoding: buffer"', testText, singleComplexBuffer, 'readable', true, undefined, 'buffer');85+test('.readable() can use "binary: true" + "encoding: hex"', testText, singleComplexBuffer, 'readable', true, undefined, 'hex');86+test('.readable() can use "binary: undefined"', testText, singleComplexBuffer, 'readable', undefined, undefined, 'utf8');87+test('.readable() can use "binary: undefined" + "encoding: utf16le"', testText, singleComplexUtf16Buffer, 'readable', undefined, undefined, 'utf16le');88+test('.readable() can use "binary: undefined" + "encoding: buffer"', testText, singleComplexBuffer, 'readable', undefined, undefined, 'buffer');89+test('.readable() can use "binary: undefined" + "encoding: hex"', testText, singleComplexBuffer, 'readable', undefined, undefined, 'hex');90+test('.readable() can use "binary: false"', testText, complexChunksEnd, 'readable', false, undefined, 'utf8');91+test('.readable() can use "binary: false" + "encoding: utf16le"', testText, complexChunksEnd, 'readable', false, undefined, 'utf16le');92+test('.readable() can use "binary: false" + "encoding: buffer"', testText, singleComplexBuffer, 'readable', false, undefined, 'buffer');93+test('.readable() can use "binary: false" + "encoding: hex"', testText, singleComplexBuffer, 'readable', false, undefined, 'hex');94+test('.readable() can use "binary: false" + "preserveNewlines: true"', testText, complexChunksEnd, 'readable', false, true, 'utf8');95+test('.readable() can use "binary: false" + "preserveNewlines: false"', testText, complexChunks, 'readable', false, false, 'utf8');96+test('.duplex() can use "binary: true"', testText, singleComplexBuffer, 'duplex', true, undefined, 'utf8');97+test('.duplex() can use "binary: true" + "encoding: utf16le"', testText, singleComplexUtf16Buffer, 'duplex', true, undefined, 'utf16le');98+test('.duplex() can use "binary: true" + "encoding: buffer"', testText, singleComplexBuffer, 'duplex', true, undefined, 'buffer');99+test('.duplex() can use "binary: true" + "encoding: hex"', testText, singleComplexBuffer, 'duplex', true, undefined, 'hex');100+test('.duplex() can use "binary: undefined"', testText, singleComplexBuffer, 'duplex', undefined, undefined, 'utf8');101+test('.duplex() can use "binary: undefined" + "encoding: utf16le"', testText, singleComplexUtf16Buffer, 'duplex', undefined, undefined, 'utf16le');102+test('.duplex() can use "binary: undefined" + "encoding: "buffer"', testText, singleComplexBuffer, 'duplex', undefined, undefined, 'buffer');103+test('.duplex() can use "binary: undefined" + "encoding: "hex"', testText, singleComplexBuffer, 'duplex', undefined, undefined, 'hex');104+test('.duplex() can use "binary: false"', testText, complexChunksEnd, 'duplex', false, undefined, 'utf8');105+test('.duplex() can use "binary: false" + "encoding: utf16le"', testText, complexChunksEnd, 'duplex', false, undefined, 'utf16le');106+test('.duplex() can use "binary: false" + "encoding: buffer"', testText, singleComplexBuffer, 'duplex', false, undefined, 'buffer');107+test('.duplex() can use "binary: false" + "encoding: hex"', testText, singleComplexBuffer, 'duplex', false, undefined, 'hex');108+test('.duplex() can use "binary: false" + "preserveNewlines: true"', testText, complexChunksEnd, 'duplex', false, true, 'utf8');109+test('.duplex() can use "binary: false" + "preserveNewlines: false"', testText, complexChunks, 'duplex', false, false, 'utf8');110+111+const testTextOutput = async (t, expectedOutput, methodName, preserveNewlines) => {112+ const subprocess = getSubprocess(methodName, complexFull);113+ const stream = subprocess[methodName]({binary: false, preserveNewlines});114+115+ await assertStreamOutput(t, stream, expectedOutput);116+ await assertSubprocessOutput(t, subprocess, complexFull);117+};118+119+test('.readable() "binary: false" keeps output as is', testTextOutput, complexFull, 'readable', undefined);120+test('.readable() "binary: false" + "preserveNewlines: true" keeps output as is', testTextOutput, complexFull, 'readable', true);121+test('.readable() "binary: false" + "preserveNewlines: false" removes all newlines', testTextOutput, noNewlinesFull, 'readable', false);122+test('.duplex() "binary: false" keeps output as is', testTextOutput, complexFull, 'duplex', undefined);123+test('.duplex() "binary: false" + "preserveNewlines: true" keeps output as is', testTextOutput, complexFull, 'duplex', true);124+test('.duplex() "binary: false" + "preserveNewlines: false" removes all newlines', testTextOutput, noNewlinesFull, 'duplex', false);125+126+// eslint-disable-next-line max-params127+const testObjectMode = async (t, expectedChunks, methodName, encoding, initialObjectMode, finalObjectMode, binary, options) => {128+ const subprocess = getSubprocess(methodName, simpleFull, options);129+ if (encoding !== null) {130+ subprocess.stdout.setEncoding(encoding);131+ }132+133+ t.is(subprocess.stdout.readableEncoding, encoding);134+ t.is(subprocess.stdout.readableObjectMode, initialObjectMode);135+ t.is(subprocess.stdout.readableHighWaterMark, getDefaultHighWaterMark(initialObjectMode));136+137+ const stream = subprocess[methodName]({binary, preserveNewlines: true});138+139+ if (methodName !== 'iterable') {140+ t.is(stream.readableEncoding, encoding);141+ t.is(stream.readableObjectMode, finalObjectMode);142+ t.is(stream.readableHighWaterMark, getDefaultHighWaterMark(finalObjectMode));143+ }144+145+ t.is(subprocess.stdout.readableEncoding, encoding);146+ t.is(subprocess.stdout.readableObjectMode, initialObjectMode);147+ t.is(subprocess.stdout.readableHighWaterMark, getDefaultHighWaterMark(initialObjectMode));148+149+ await assertChunks(t, stream, expectedChunks, methodName);150+ await subprocess;151+};152+153+test('.iterable() uses Uint8Arrays with "binary: true"', testObjectMode, simpleChunksUint8Array, 'iterable', null, false, false, true);154+test('.iterable() uses Uint8Arrays with "binary: true" and .setEncoding("utf8")', testObjectMode, simpleChunksUint8Array, 'iterable', 'utf8', false, false, true);155+test('.iterable() uses Uint8Arrays with "binary: true", .setEncoding("utf8") and "encoding: buffer"', testObjectMode, simpleChunksUint8Array, 'iterable', 'utf8', false, false, true, {encoding: 'buffer'});156+test('.iterable() uses strings in objectMode with "binary: true" and object transforms', testObjectMode, foobarObjectChunks, 'iterable', null, true, true, true, {stdout: outputObjectGenerator()});157+test('.iterable() uses strings in objectMode with "binary: false"', testObjectMode, simpleLines, 'iterable', null, false, true, false);158+test('.iterable() uses strings in objectMode with "binary: false" and .setEncoding("utf8")', testObjectMode, simpleLines, 'iterable', 'utf8', false, true, false);159+test('.iterable() uses Uint8Arrays in objectMode with "binary: false", .setEncoding("utf8") and "encoding: buffer"', testObjectMode, simpleChunksUint8Array, 'iterable', 'utf8', false, true, false, {encoding: 'buffer'});160+test('.iterable() uses strings in objectMode with "binary: false" and object transforms', testObjectMode, foobarObjectChunks, 'iterable', null, true, true, false, {stdout: outputObjectGenerator()});161+test('.readable() uses Buffers with "binary: true"', testObjectMode, simpleChunksBuffer, 'readable', null, false, false, true);162+test('.readable() uses strings with "binary: true" and .setEncoding("utf8")', testObjectMode, simpleChunks, 'readable', 'utf8', false, false, true);163+test('.readable() uses strings with "binary: true", .setEncoding("utf8") and "encoding: buffer"', testObjectMode, simpleChunks, 'readable', 'utf8', false, false, true, {encoding: 'buffer'});164+test('.readable() uses strings in objectMode with "binary: true" and object transforms', testObjectMode, foobarObjectChunks, 'readable', null, true, true, true, {stdout: outputObjectGenerator()});165+test('.readable() uses strings in objectMode with "binary: false"', testObjectMode, simpleLines, 'readable', null, false, true, false);166+test('.readable() uses strings in objectMode with "binary: false" and .setEncoding("utf8")', testObjectMode, simpleLines, 'readable', 'utf8', false, true, false);167+test('.readable() uses strings in objectMode with "binary: false", .setEncoding("utf8") and "encoding: buffer"', testObjectMode, simpleChunks, 'readable', 'utf8', false, false, false, {encoding: 'buffer'});168+test('.readable() uses strings in objectMode with "binary: false" and object transforms', testObjectMode, foobarObjectChunks, 'readable', null, true, true, false, {stdout: outputObjectGenerator()});169+test('.duplex() uses Buffers with "binary: true"', testObjectMode, simpleChunksBuffer, 'duplex', null, false, false, true);170+test('.duplex() uses strings with "binary: true" and .setEncoding("utf8")', testObjectMode, simpleChunks, 'duplex', 'utf8', false, false, true);171+test('.duplex() uses strings with "binary: true", .setEncoding("utf8") and "encoding: buffer"', testObjectMode, simpleChunks, 'duplex', 'utf8', false, false, true, {encoding: 'buffer'});172+test('.duplex() uses strings in objectMode with "binary: true" and object transforms', testObjectMode, foobarObjectChunks, 'duplex', null, true, true, true, {stdout: outputObjectGenerator()});173+test('.duplex() uses strings in objectMode with "binary: false"', testObjectMode, simpleLines, 'duplex', null, false, true, false);174+test('.duplex() uses strings in objectMode with "binary: false" and .setEncoding("utf8")', testObjectMode, simpleLines, 'duplex', 'utf8', false, true, false);175+test('.duplex() uses strings in objectMode with "binary: false", .setEncoding("utf8") and "encoding: buffer"', testObjectMode, simpleChunks, 'duplex', 'utf8', false, false, false, {encoding: 'buffer'});176+test('.duplex() uses strings in objectMode with "binary: false" and object transforms', testObjectMode, foobarObjectChunks, 'duplex', null, true, true, false, {stdout: outputObjectGenerator()});177+178+const testObjectSplit = async (t, methodName) => {179+ const subprocess = getSubprocess(methodName, foobarString, {stdout: getOutputGenerator(simpleFull)(true)});180+ const stream = subprocess[methodName]({binary: false});181+ await assertChunks(t, stream, [simpleFull], methodName);182+ await subprocess;183+};184+185+test('.iterable() "binary: false" does not split lines of strings produced by object transforms', testObjectSplit, 'iterable');186+test('.readable() "binary: false" does not split lines of strings produced by object transforms', testObjectSplit, 'readable');187+test('.duplex() "binary: false" does not split lines of strings produced by object transforms', testObjectSplit, 'duplex');188+189+const testMultibyteCharacters = async (t, methodName) => {190+ const subprocess = getReadWriteSubprocess();191+ const stream = subprocess[methodName]({binary: false});192+ const assertPromise = assertChunks(t, stream, [`${multibyteChar}${brokenSymbol}`], methodName);193+ subprocess.stdin.write(multibyteUint8Array.slice(0, breakingLength));194+ await once(subprocess.stdout, 'data');195+ subprocess.stdin.end();196+ await assertPromise;197+};198+199+test('.iterable() "binary: false" handles partial multibyte characters', testMultibyteCharacters, 'iterable');200+test('.readable() "binary: false" handles partial multibyte characters', testMultibyteCharacters, 'readable');201+test('.duplex() "binary: false" handles partial multibyte characters', testMultibyteCharacters, 'duplex');added:test/io/max-buffer.js+265 added
1+import {Buffer} from 'node:buffer';2+import test from 'ava';3+import getStream from 'get-stream';4+import {execa, execaSync} from '../../index.js';5+import {setFixtureDir} from '../helpers/fixtures-dir.js';6+import {fullStdio} from '../helpers/stdio.js';7+import {getEarlyErrorSubprocess, getEarlyErrorSubprocessSync} from '../helpers/early-error.js';8+import {maxBuffer, assertErrorMessage} from '../helpers/max-buffer.js';9+10+setFixtureDir();11+12+const maxBufferMessage = {message: /maxBuffer exceeded/};13+const maxBufferCodeSync = {code: 'ENOBUFS'};14+15+const runMaxBuffer = async (t, execaMethod, fdNumber, options) => {16+ const error = execaMethod === execa17+ ? await t.throwsAsync(getMaxBufferSubprocess(execaMethod, fdNumber, options), maxBufferMessage)18+ : t.throws(() => {19+ getMaxBufferSubprocess(execaMethod, fdNumber, options);20+ }, maxBufferCodeSync);21+ t.true(error.isMaxBuffer);22+ t.is(error.maxBufferInfo, undefined);23+ return error;24+};25+26+const getMaxBufferSubprocess = (execaMethod, fdNumber, {length = maxBuffer, ...options} = {}) =>27+ execaMethod('max-buffer.js', [`${fdNumber}`, `${length + 1}`], {...fullStdio, maxBuffer, ...options});28+29+const getExpectedOutput = (length = maxBuffer) => '.'.repeat(length);30+31+const testMaxBufferSuccess = async (t, execaMethod, fdNumber, all) => {32+ const {isMaxBuffer} = await getMaxBufferSubprocess(execaMethod, fdNumber, {all, length: maxBuffer - 1});33+ t.false(isMaxBuffer);34+};35+36+test('maxBuffer does not affect stdout if too high', testMaxBufferSuccess, execa, 1, false);37+test('maxBuffer does not affect stderr if too high', testMaxBufferSuccess, execa, 2, false);38+test('maxBuffer does not affect stdio[*] if too high', testMaxBufferSuccess, execa, 3, false);39+test('maxBuffer does not affect all if too high', testMaxBufferSuccess, execa, 1, true);40+test('maxBuffer does not affect stdout if too high, sync', testMaxBufferSuccess, execaSync, 1, false);41+test('maxBuffer does not affect stderr if too high, sync', testMaxBufferSuccess, execaSync, 2, false);42+test('maxBuffer does not affect stdio[*] if too high, sync', testMaxBufferSuccess, execaSync, 3, false);43+test('maxBuffer does not affect all if too high, sync', testMaxBufferSuccess, execaSync, 1, true);44+45+const testGracefulExit = async (t, fixtureName, expectedExitCode) => {46+ const {isMaxBuffer, shortMessage, exitCode, signal, stdout} = await t.throwsAsync(47+ execa(fixtureName, ['1', '.'.repeat(maxBuffer + 1)], {maxBuffer}),48+ maxBufferMessage,49+ );50+ t.true(isMaxBuffer);51+ assertErrorMessage(t, shortMessage);52+ t.is(exitCode, expectedExitCode);53+ t.is(signal, undefined);54+ t.is(stdout, getExpectedOutput());55+};56+57+test('maxBuffer terminates stream gracefully, more writes', testGracefulExit, 'noop-repeat.js', 1);58+test('maxBuffer terminates stream gracefully, no more writes', testGracefulExit, 'noop-fd.js', 0);59+60+const testGracefulExitSync = (t, fixtureName) => {61+ const {isMaxBuffer, shortMessage, exitCode, signal, stdout} = t.throws(() => {62+ execaSync(fixtureName, ['1', '.'.repeat(maxBuffer + 1)], {maxBuffer, killSignal: 'SIGINT'});63+ }, maxBufferCodeSync);64+ t.true(isMaxBuffer);65+ assertErrorMessage(t, shortMessage, {execaMethod: execaSync});66+ t.is(exitCode, undefined);67+ t.is(signal, 'SIGINT');68+ t.is(stdout, getExpectedOutput());69+};70+71+test('maxBuffer terminate stream with killSignal, more writes, sync', testGracefulExitSync, 'noop-repeat.js');72+test('maxBuffer terminate stream with killSignal, no more writes, sync', testGracefulExitSync, 'noop-fd.js');73+74+const testMaxBufferLimit = async (t, execaMethod, fdNumber, all) => {75+ const length = all && execaMethod === execa ? maxBuffer * 2 : maxBuffer;76+ const {shortMessage, all: allOutput, stdio} = await runMaxBuffer(t, execaMethod, fdNumber, {all, length});77+ assertErrorMessage(t, shortMessage, {execaMethod, fdNumber});78+ t.is(all ? allOutput : stdio[fdNumber], getExpectedOutput(length));79+};80+81+test('maxBuffer truncates stdout', testMaxBufferLimit, execa, 1, false);82+test('maxBuffer truncates stderr', testMaxBufferLimit, execa, 2, false);83+test('maxBuffer truncates stdio[*]', testMaxBufferLimit, execa, 3, false);84+test('maxBuffer truncates all', testMaxBufferLimit, execa, 1, true);85+test('maxBuffer truncates stdout, sync', testMaxBufferLimit, execaSync, 1, false);86+test('maxBuffer truncates stderr, sync', testMaxBufferLimit, execaSync, 2, false);87+test('maxBuffer truncates stdio[*], sync', testMaxBufferLimit, execaSync, 3, false);88+test('maxBuffer truncates all, sync', testMaxBufferLimit, execaSync, 1, true);89+90+const MAX_BUFFER_DEFAULT = 1e8;91+92+const testMaxBufferDefault = async (t, execaMethod, fdNumber, maxBuffer) => {93+ const length = MAX_BUFFER_DEFAULT;94+ const {shortMessage, stdio} = await runMaxBuffer(t, execaMethod, fdNumber, {length: MAX_BUFFER_DEFAULT + 1, maxBuffer});95+ assertErrorMessage(t, shortMessage, {execaMethod, fdNumber, length});96+ t.is(stdio[fdNumber], getExpectedOutput(length));97+};98+99+test('maxBuffer has a default value with stdout', testMaxBufferDefault, execa, 1, undefined);100+test('maxBuffer has a default value with stderr', testMaxBufferDefault, execa, 2, undefined);101+test('maxBuffer has a default value with stdio[*]', testMaxBufferDefault, execa, 3, undefined);102+test('maxBuffer has a default value with stdout, sync', testMaxBufferDefault, execaSync, 1, undefined);103+test('maxBuffer has a default value with stderr, sync', testMaxBufferDefault, execaSync, 2, undefined);104+test('maxBuffer has a default value with stdio[*], sync', testMaxBufferDefault, execaSync, 3, undefined);105+test('maxBuffer has a default value with stdout with fd-specific options', testMaxBufferDefault, execa, 1, {stderr: 1e9});106+test('maxBuffer has a default value with stderr with fd-specific options', testMaxBufferDefault, execa, 2, {stdout: 1e9});107+test('maxBuffer has a default value with stdio[*] with fd-specific options', testMaxBufferDefault, execa, 3, {stdout: 1e9});108+test('maxBuffer has a default value with stdout with empty fd-specific options', testMaxBufferDefault, execa, 1, {});109+110+const testFdSpecific = async (t, fdNumber, fdName, execaMethod) => {111+ const length = 1;112+ const {shortMessage, stdio} = await runMaxBuffer(t, execaMethod, fdNumber, {maxBuffer: {[fdName]: length}});113+ assertErrorMessage(t, shortMessage, {execaMethod, fdNumber, length});114+ t.is(stdio[fdNumber], getExpectedOutput(length));115+};116+117+test('maxBuffer truncates file descriptors with fd-specific options, stdout', testFdSpecific, 1, 'stdout', execa);118+test('maxBuffer truncates file descriptors with fd-specific options, fd1', testFdSpecific, 1, 'fd1', execa);119+test('maxBuffer truncates file descriptors with fd-specific options, stderr', testFdSpecific, 2, 'stderr', execa);120+test('maxBuffer truncates file descriptors with fd-specific options, fd2', testFdSpecific, 2, 'fd2', execa);121+test('maxBuffer truncates file descriptors with fd-specific options, stdout, all', testFdSpecific, 1, 'all', execa);122+test('maxBuffer truncates file descriptors with fd-specific options, stderr, all', testFdSpecific, 2, 'all', execa);123+test('maxBuffer truncates file descriptors with fd-specific options, fd3', testFdSpecific, 3, 'fd3', execa);124+test('maxBuffer.stdout is used for stdout with fd-specific options, stdout, sync', testFdSpecific, 1, 'stdout', execaSync);125+126+test('maxBuffer does not affect other file descriptors with fd-specific options', async t => {127+ const {isMaxBuffer} = await getMaxBufferSubprocess(execa, 2, {maxBuffer: {stdout: 1}});128+ t.false(isMaxBuffer);129+});130+131+test('maxBuffer.stdout is used for other file descriptors with fd-specific options, sync', async t => {132+ const length = 1;133+ const {shortMessage, stderr} = await runMaxBuffer(t, execaSync, 2, {maxBuffer: {stdout: length}});134+ assertErrorMessage(t, shortMessage, {execaMethod: execaSync, fdNumber: 2, length});135+ t.is(stderr, getExpectedOutput(length));136+});137+138+const testAll = async (t, shouldFail) => {139+ const difference = shouldFail ? 0 : 1;140+ const maxBufferStdout = 2;141+ const maxBufferStderr = 4 - difference;142+ const {isMaxBuffer, shortMessage, stdout, stderr, all} = await execa(143+ 'noop-both.js',144+ ['\n'.repeat(maxBufferStdout - 1), '\n'.repeat(maxBufferStderr - difference)],145+ {maxBuffer: {stdout: maxBufferStdout, stderr: maxBufferStderr}, all: true, stripFinalNewline: false, reject: false},146+ );147+ t.is(isMaxBuffer, shouldFail);148+ if (shouldFail) {149+ assertErrorMessage(t, shortMessage, {fdNumber: 2, length: maxBufferStderr});150+ }151+152+ t.is(stdout, '\n'.repeat(maxBufferStdout));153+ t.is(stderr, '\n'.repeat(maxBufferStderr));154+ t.is(all, '\n'.repeat(maxBufferStdout + maxBufferStderr));155+};156+157+test('maxBuffer.stdout can differ from maxBuffer.stderr, combined with all, below threshold', testAll, false);158+test('maxBuffer.stdout can differ from maxBuffer.stderr, combined with all, above threshold', testAll, true);159+160+const testInvalidFd = async (t, fdName, execaMethod) => {161+ const {message} = t.throws(() => {162+ execaMethod('empty.js', {maxBuffer: {[fdName]: 0}});163+ });164+ t.true(message.includes(`"maxBuffer.${fdName}" is invalid`));165+};166+167+test('maxBuffer.stdin is invalid', testInvalidFd, 'stdin', execa);168+test('maxBuffer.fd0 is invalid', testInvalidFd, 'fd0', execa);169+test('maxBuffer.other is invalid', testInvalidFd, 'other', execa);170+test('maxBuffer.fd10 is invalid', testInvalidFd, 'fd10', execa);171+test('maxBuffer.stdin is invalid, sync', testInvalidFd, 'stdin', execaSync);172+test('maxBuffer.fd0 is invalid, sync', testInvalidFd, 'fd0', execaSync);173+test('maxBuffer.other is invalid, sync', testInvalidFd, 'other', execaSync);174+test('maxBuffer.fd10 is invalid, sync', testInvalidFd, 'fd10', execaSync);175+176+const testMaxBufferEncoding = async (t, execaMethod, fdNumber) => {177+ const {shortMessage, stdio} = await runMaxBuffer(t, execaMethod, fdNumber, {encoding: 'buffer'});178+ assertErrorMessage(t, shortMessage, {execaMethod, fdNumber, unit: 'bytes'});179+ const stream = stdio[fdNumber];180+ t.true(stream instanceof Uint8Array);181+ t.is(Buffer.from(stream).toString(), getExpectedOutput());182+};183+184+test('maxBuffer works with encoding buffer and stdout', testMaxBufferEncoding, execa, 1);185+test('maxBuffer works with encoding buffer and stderr', testMaxBufferEncoding, execa, 2);186+test('maxBuffer works with encoding buffer and stdio[*]', testMaxBufferEncoding, execa, 3);187+test('maxBuffer works with encoding buffer and stdout, sync', testMaxBufferEncoding, execaSync, 1);188+test('maxBuffer works with encoding buffer and stderr, sync', testMaxBufferEncoding, execaSync, 2);189+test('maxBuffer works with encoding buffer and stdio[*], sync', testMaxBufferEncoding, execaSync, 3);190+191+const testMaxBufferHex = async (t, fdNumber) => {192+ const length = maxBuffer / 2;193+ const {shortMessage, stdio} = await runMaxBuffer(t, execa, fdNumber, {length, encoding: 'hex'});194+ assertErrorMessage(t, shortMessage, {fdNumber});195+ t.is(stdio[fdNumber], Buffer.from(getExpectedOutput(length)).toString('hex'));196+};197+198+test('maxBuffer works with other encodings and stdout', testMaxBufferHex, 1);199+test('maxBuffer works with other encodings and stderr', testMaxBufferHex, 2);200+test('maxBuffer works with other encodings and stdio[*]', testMaxBufferHex, 3);201+202+const testMaxBufferHexSync = async (t, fdNumber) => {203+ const length = maxBuffer / 2;204+ const {isMaxBuffer, stdio} = await getMaxBufferSubprocess(execaSync, fdNumber, {length, encoding: 'hex'});205+ t.false(isMaxBuffer);206+ t.is(stdio[fdNumber], Buffer.from(getExpectedOutput(length + 1)).toString('hex'));207+};208+209+test('maxBuffer ignores other encodings and stdout, sync', testMaxBufferHexSync, 1);210+test('maxBuffer ignores other encodings and stderr, sync', testMaxBufferHexSync, 2);211+test('maxBuffer ignores other encodings and stdio[*], sync', testMaxBufferHexSync, 3);212+213+const testNoMaxBuffer = async (t, fdNumber, buffer) => {214+ const subprocess = getMaxBufferSubprocess(execa, fdNumber, {buffer});215+ const [{isMaxBuffer, stdio}, output] = await Promise.all([216+ subprocess,217+ getStream(subprocess.stdio[fdNumber]),218+ ]);219+ t.false(isMaxBuffer);220+ t.is(stdio[fdNumber], undefined);221+ t.is(output, getExpectedOutput(maxBuffer + 1));222+};223+224+test('do not buffer stdout when `buffer` set to `false`', testNoMaxBuffer, 1, false);225+test('do not buffer stdout when `buffer` set to `false`, fd-specific', testNoMaxBuffer, 1, {stdout: false});226+test('do not buffer stderr when `buffer` set to `false`', testNoMaxBuffer, 2, false);227+test('do not buffer stderr when `buffer` set to `false`, fd-specific', testNoMaxBuffer, 2, {stderr: false});228+test('do not buffer stdio[*] when `buffer` set to `false`', testNoMaxBuffer, 3, false);229+test('do not buffer stdio[*] when `buffer` set to `false`, fd-specific', testNoMaxBuffer, 3, {fd3: false});230+231+const testNoMaxBufferSync = (t, fdNumber, buffer) => {232+ const {isMaxBuffer, stdio} = getMaxBufferSubprocess(execaSync, fdNumber, {buffer});233+ t.false(isMaxBuffer);234+ t.is(stdio[fdNumber], undefined);235+};236+237+// @todo: add tests for fd3 once the following Node.js bug is fixed.238+// https://github.com/nodejs/node/issues/52422239+test('do not buffer stdout when `buffer` set to `false`, sync', testNoMaxBufferSync, 1, false);240+test('do not buffer stdout when `buffer` set to `false`, fd-specific, sync', testNoMaxBufferSync, 1, {stdout: false});241+test('do not buffer stderr when `buffer` set to `false`, sync', testNoMaxBufferSync, 2, false);242+test('do not buffer stderr when `buffer` set to `false`, fd-specific, sync', testNoMaxBufferSync, 2, {stderr: false});243+244+const testMaxBufferAbort = async (t, fdNumber) => {245+ const subprocess = getMaxBufferSubprocess(execa, fdNumber);246+ const [{isMaxBuffer, shortMessage}] = await Promise.all([247+ t.throwsAsync(subprocess, maxBufferMessage),248+ t.throwsAsync(getStream(subprocess.stdio[fdNumber]), {code: 'ERR_STREAM_PREMATURE_CLOSE'}),249+ ]);250+ t.true(isMaxBuffer);251+ assertErrorMessage(t, shortMessage, {execaMethod: execa, fdNumber});252+};253+254+test('abort stream when hitting maxBuffer with stdout', testMaxBufferAbort, 1);255+test('abort stream when hitting maxBuffer with stderr', testMaxBufferAbort, 2);256+test('abort stream when hitting maxBuffer with stdio[*]', testMaxBufferAbort, 3);257+258+const testEarlyError = async (t, getSubprocess) => {259+ const {failed, isMaxBuffer} = await getSubprocess({reject: false, maxBuffer: 1});260+ t.true(failed);261+ t.false(isMaxBuffer);262+};263+264+test('error.isMaxBuffer is false on early errors', testEarlyError, getEarlyErrorSubprocess);265+test('error.isMaxBuffer is false on early errors, sync', testEarlyError, getEarlyErrorSubprocessSync);added:test/io/output-async.js+84 added
1+import {once, defaultMaxListeners} from 'node:events';2+import process from 'node:process';3+import {setImmediate} from 'node:timers/promises';4+import test from 'ava';5+import {execa} from '../../index.js';6+import {STANDARD_STREAMS} from '../helpers/stdio.js';7+import {foobarString} from '../helpers/input.js';8+import {setFixtureDir} from '../helpers/fixtures-dir.js';9+import {assertMaxListeners} from '../helpers/listeners.js';10+11+setFixtureDir();12+13+const getStandardStreamListeners = stream => Object.fromEntries(stream.eventNames().map(eventName => [eventName, stream.listeners(eventName)]));14+const getStandardStreamsListeners = () => STANDARD_STREAMS.map(stream => getStandardStreamListeners(stream));15+16+const getComplexStdio = isMultiple => ({17+ stdin: ['pipe', 'inherit', ...(isMultiple ? [0, process.stdin] : [])],18+ stdout: ['pipe', 'inherit', ...(isMultiple ? [1, process.stdout] : [])],19+ stderr: ['pipe', 'inherit', ...(isMultiple ? [2, process.stderr] : [])],20+});21+22+const onStdinRemoveListener = () => once(process.stdin, 'removeListener');23+24+const testListenersCleanup = async (t, isMultiple) => {25+ const streamsPreviousListeners = getStandardStreamsListeners();26+ const subprocess = execa('empty.js', getComplexStdio(isMultiple));27+ t.notDeepEqual(getStandardStreamsListeners(), streamsPreviousListeners);28+ await Promise.all([subprocess, onStdinRemoveListener()]);29+ if (isMultiple) {30+ await onStdinRemoveListener();31+ }32+33+ for (const [fdNumber, streamNewListeners] of Object.entries(getStandardStreamsListeners())) {34+ const defaultListeners = Object.fromEntries(Reflect.ownKeys(streamNewListeners).map(eventName => [eventName, []]));35+ t.deepEqual(streamNewListeners, {...defaultListeners, ...streamsPreviousListeners[fdNumber]});36+ }37+};38+39+test.serial('process.std* listeners are cleaned up on success with a single input', testListenersCleanup, false);40+test.serial('process.std* listeners are cleaned up on success with multiple inputs', testListenersCleanup, true);41+42+const subprocessesCount = 100;43+44+test.serial('Can spawn many subprocesses in parallel', async t => {45+ const results = await Promise.all(46+ Array.from({length: subprocessesCount}, () => execa('noop.js', [foobarString])),47+ );48+ t.true(results.every(({stdout}) => stdout === foobarString));49+});50+51+const testMaxListeners = async (t, isMultiple, maxListenersCount) => {52+ const checkMaxListeners = assertMaxListeners(t);53+54+ for (const standardStream of STANDARD_STREAMS) {55+ standardStream.setMaxListeners(maxListenersCount);56+ }57+58+ try {59+ const results = await Promise.all(60+ Array.from({length: subprocessesCount}, () => execa('empty.js', getComplexStdio(isMultiple))),61+ );62+ t.true(results.every(({exitCode}) => exitCode === 0));63+ } finally {64+ await setImmediate();65+ await setImmediate();66+ checkMaxListeners();67+68+ for (const standardStream of STANDARD_STREAMS) {69+ t.is(standardStream.getMaxListeners(), maxListenersCount);70+ standardStream.setMaxListeners(defaultMaxListeners);71+ }72+ }73+};74+75+test.serial('No warning with maxListeners 1 and ["pipe", "inherit"]', testMaxListeners, false, 1);76+test.serial('No warning with maxListeners default and ["pipe", "inherit"]', testMaxListeners, false, defaultMaxListeners);77+test.serial('No warning with maxListeners 100 and ["pipe", "inherit"]', testMaxListeners, false, 100);78+test.serial('No warning with maxListeners Infinity and ["pipe", "inherit"]', testMaxListeners, false, Number.POSITIVE_INFINITY);79+test.serial('No warning with maxListeners 0 and ["pipe", "inherit"]', testMaxListeners, false, 0);80+test.serial('No warning with maxListeners 1 and ["pipe", "inherit"], multiple inputs', testMaxListeners, true, 1);81+test.serial('No warning with maxListeners default and ["pipe", "inherit"], multiple inputs', testMaxListeners, true, defaultMaxListeners);82+test.serial('No warning with maxListeners 100 and ["pipe", "inherit"], multiple inputs', testMaxListeners, true, 100);83+test.serial('No warning with maxListeners Infinity and ["pipe", "inherit"], multiple inputs', testMaxListeners, true, Number.POSITIVE_INFINITY);84+test.serial('No warning with maxListeners 0 and ["pipe", "inherit"], multiple inputs', testMaxListeners, true, 0);added:test/io/output-sync.js+33 added
1+import test from 'ava';2+import {execaSync} from '../../index.js';3+import {setFixtureDir} from '../helpers/fixtures-dir.js';4+import {throwingGenerator} from '../helpers/generator.js';5+import {foobarString} from '../helpers/input.js';6+7+setFixtureDir();8+9+test('Handles errors with stdout generator, sync', t => {10+ const cause = new Error(foobarString);11+ const error = t.throws(() => {12+ execaSync('noop.js', {stdout: throwingGenerator(cause)()});13+ });14+ t.is(error.cause, cause);15+});16+17+test('Handles errors with stdout generator, spawn failure, sync', t => {18+ const cause = new Error(foobarString);19+ const error = t.throws(() => {20+ execaSync('noop.js', {cwd: 'does_not_exist', stdout: throwingGenerator(cause)()});21+ });22+ t.true(error.failed);23+ t.is(error.cause.code, 'ENOENT');24+});25+26+test('Handles errors with stdout generator, subprocess failure, sync', t => {27+ const cause = new Error(foobarString);28+ const error = t.throws(() => {29+ execaSync('noop-fail.js', ['1'], {stdout: throwingGenerator(cause)()});30+ });31+ t.true(error.failed);32+ t.is(error.cause, cause);33+});added:test/io/pipeline.js+38 added
1+import test from 'ava';2+import {execa} from '../../index.js';3+import {getStdio, STANDARD_STREAMS} from '../helpers/stdio.js';4+import {setFixtureDir} from '../helpers/fixtures-dir.js';5+6+setFixtureDir();7+8+const testDestroyStandard = async (t, fdNumber) => {9+ const subprocess = execa('forever.js', {...getStdio(fdNumber, [STANDARD_STREAMS[fdNumber], 'pipe']), timeout: 1});10+ await t.throwsAsync(subprocess, {message: /timed out/});11+ t.false(STANDARD_STREAMS[fdNumber].destroyed);12+};13+14+test('Does not destroy process.stdin on subprocess errors', testDestroyStandard, 0);15+test('Does not destroy process.stdout on subprocess errors', testDestroyStandard, 1);16+test('Does not destroy process.stderr on subprocess errors', testDestroyStandard, 2);17+18+const testDestroyStandardSpawn = async (t, fdNumber) => {19+ await t.throwsAsync(execa('forever.js', {...getStdio(fdNumber, [STANDARD_STREAMS[fdNumber], 'pipe']), uid: -1}));20+ t.false(STANDARD_STREAMS[fdNumber].destroyed);21+};22+23+test('Does not destroy process.stdin on subprocess early errors', testDestroyStandardSpawn, 0);24+test('Does not destroy process.stdout on subprocess early errors', testDestroyStandardSpawn, 1);25+test('Does not destroy process.stderr on subprocess early errors', testDestroyStandardSpawn, 2);26+27+const testDestroyStandardStream = async (t, fdNumber) => {28+ const subprocess = execa('forever.js', getStdio(fdNumber, [STANDARD_STREAMS[fdNumber], 'pipe']));29+ const cause = new Error('test');30+ subprocess.stdio[fdNumber].destroy(cause);31+ subprocess.kill();32+ t.like(await t.throwsAsync(subprocess), {cause});33+ t.false(STANDARD_STREAMS[fdNumber].destroyed);34+};35+36+test('Does not destroy process.stdin on stream subprocess errors', testDestroyStandardStream, 0);37+test('Does not destroy process.stdout on stream subprocess errors', testDestroyStandardStream, 1);38+test('Does not destroy process.stderr on stream subprocess errors', testDestroyStandardStream, 2);added:test/io/strip-newline.js+56 added
1+import test from 'ava';2+import {execa, execaSync} from '../../index.js';3+import {setFixtureDir} from '../helpers/fixtures-dir.js';4+import {fullStdio} from '../helpers/stdio.js';5+import {noopGenerator} from '../helpers/generator.js';6+import {foobarString} from '../helpers/input.js';7+8+setFixtureDir();9+10+// eslint-disable-next-line max-params11+const testStripFinalNewline = async (t, fdNumber, stripFinalNewline, shouldStrip, execaMethod) => {12+ const {stdio} = await execaMethod('noop-fd.js', [`${fdNumber}`, `${foobarString}\n`], {...fullStdio, stripFinalNewline});13+ t.is(stdio[fdNumber], `${foobarString}${shouldStrip ? '' : '\n'}`);14+};15+16+test('stripFinalNewline: default with stdout', testStripFinalNewline, 1, undefined, true, execa);17+test('stripFinalNewline: true with stdout', testStripFinalNewline, 1, true, true, execa);18+test('stripFinalNewline: false with stdout', testStripFinalNewline, 1, false, false, execa);19+test('stripFinalNewline: default with stderr', testStripFinalNewline, 2, undefined, true, execa);20+test('stripFinalNewline: true with stderr', testStripFinalNewline, 2, true, true, execa);21+test('stripFinalNewline: false with stderr', testStripFinalNewline, 2, false, false, execa);22+test('stripFinalNewline: default with stdio[*]', testStripFinalNewline, 3, undefined, true, execa);23+test('stripFinalNewline: true with stdio[*]', testStripFinalNewline, 3, true, true, execa);24+test('stripFinalNewline: false with stdio[*]', testStripFinalNewline, 3, false, false, execa);25+test('stripFinalNewline: default with stdout, fd-specific', testStripFinalNewline, 1, {}, true, execa);26+test('stripFinalNewline: true with stdout, fd-specific', testStripFinalNewline, 1, {stdout: true}, true, execa);27+test('stripFinalNewline: false with stdout, fd-specific', testStripFinalNewline, 1, {stdout: false}, false, execa);28+test('stripFinalNewline: default with stderr, fd-specific', testStripFinalNewline, 2, {}, true, execa);29+test('stripFinalNewline: true with stderr, fd-specific', testStripFinalNewline, 2, {stderr: true}, true, execa);30+test('stripFinalNewline: false with stderr, fd-specific', testStripFinalNewline, 2, {stderr: false}, false, execa);31+test('stripFinalNewline: default with stdio[*], fd-specific', testStripFinalNewline, 3, {}, true, execa);32+test('stripFinalNewline: true with stdio[*], fd-specific', testStripFinalNewline, 3, {fd3: true}, true, execa);33+test('stripFinalNewline: false with stdio[*], fd-specific', testStripFinalNewline, 3, {fd3: false}, false, execa);34+test('stripFinalNewline: default with stdout, sync', testStripFinalNewline, 1, undefined, true, execaSync);35+test('stripFinalNewline: true with stdout, sync', testStripFinalNewline, 1, true, true, execaSync);36+test('stripFinalNewline: false with stdout, sync', testStripFinalNewline, 1, false, false, execaSync);37+test('stripFinalNewline: default with stderr, sync', testStripFinalNewline, 2, undefined, true, execaSync);38+test('stripFinalNewline: true with stderr, sync', testStripFinalNewline, 2, true, true, execaSync);39+test('stripFinalNewline: false with stderr, sync', testStripFinalNewline, 2, false, false, execaSync);40+test('stripFinalNewline: default with stdio[*], sync', testStripFinalNewline, 3, undefined, true, execaSync);41+test('stripFinalNewline: true with stdio[*], sync', testStripFinalNewline, 3, true, true, execaSync);42+test('stripFinalNewline: false with stdio[*], sync', testStripFinalNewline, 3, false, false, execaSync);43+test('stripFinalNewline: default with stdout, fd-specific, sync', testStripFinalNewline, 1, {}, true, execaSync);44+test('stripFinalNewline: true with stdout, fd-specific, sync', testStripFinalNewline, 1, {stdout: true}, true, execaSync);45+test('stripFinalNewline: false with stdout, fd-specific, sync', testStripFinalNewline, 1, {stdout: false}, false, execaSync);46+test('stripFinalNewline: default with stderr, fd-specific, sync', testStripFinalNewline, 2, {}, true, execaSync);47+test('stripFinalNewline: true with stderr, fd-specific, sync', testStripFinalNewline, 2, {stderr: true}, true, execaSync);48+test('stripFinalNewline: false with stderr, fd-specific, sync', testStripFinalNewline, 2, {stderr: false}, false, execaSync);49+test('stripFinalNewline: default with stdio[*], fd-specific, sync', testStripFinalNewline, 3, {}, true, execaSync);50+test('stripFinalNewline: true with stdio[*], fd-specific, sync', testStripFinalNewline, 3, {fd3: true}, true, execaSync);51+test('stripFinalNewline: false with stdio[*], fd-specific, sync', testStripFinalNewline, 3, {fd3: false}, false, execaSync);52+53+test('stripFinalNewline is not used in objectMode', async t => {54+ const {stdout} = await execa('noop-fd.js', ['1', `${foobarString}\n`], {stripFinalNewline: true, stdout: noopGenerator(true, false, true)});55+ t.deepEqual(stdout, [`${foobarString}\n`]);56+});added:test/methods/command.js+112 added
1+import {join} from 'node:path';2+import test from 'ava';3+import {execaCommand, execaCommandSync} from '../../index.js';4+import {setFixtureDir, FIXTURES_DIR} from '../helpers/fixtures-dir.js';5+import {QUOTE} from '../helpers/verbose.js';6+7+setFixtureDir();8+const STDIN_FIXTURE = join(FIXTURES_DIR, 'stdin.js');9+10+test('execaCommand()', async t => {11+ const {stdout} = await execaCommand('echo.js foo bar');12+ t.is(stdout, 'foo\nbar');13+});14+15+test('execaCommandSync()', t => {16+ const {stdout} = execaCommandSync('echo.js foo bar');17+ t.is(stdout, 'foo\nbar');18+});19+20+test('execaCommand`...`', async t => {21+ const {stdout} = await execaCommand`${'echo.js foo bar'}`;22+ t.is(stdout, 'foo\nbar');23+});24+25+test('execaCommandSync`...`', t => {26+ const {stdout} = execaCommandSync`${'echo.js foo bar'}`;27+ t.is(stdout, 'foo\nbar');28+});29+30+test('execaCommand(options)`...`', async t => {31+ const {stdout} = await execaCommand({stripFinalNewline: false})`${'echo.js foo bar'}`;32+ t.is(stdout, 'foo\nbar\n');33+});34+35+test('execaCommandSync(options)`...`', t => {36+ const {stdout} = execaCommandSync({stripFinalNewline: false})`${'echo.js foo bar'}`;37+ t.is(stdout, 'foo\nbar\n');38+});39+40+test('execaCommand(options)()', async t => {41+ const {stdout} = await execaCommand({stripFinalNewline: false})('echo.js foo bar');42+ t.is(stdout, 'foo\nbar\n');43+});44+45+test('execaCommandSync(options)()', t => {46+ const {stdout} = execaCommandSync({stripFinalNewline: false})('echo.js foo bar');47+ t.is(stdout, 'foo\nbar\n');48+});49+50+test('execaCommand().pipe(execaCommand())', async t => {51+ const {stdout} = await execaCommand('echo.js foo bar').pipe(execaCommand(`node ${STDIN_FIXTURE}`));52+ t.is(stdout, 'foo\nbar');53+});54+55+test('execaCommand().pipe(...) does not use execaCommand', async t => {56+ const {escapedCommand} = await execaCommand('echo.js foo bar').pipe(`node ${STDIN_FIXTURE}`, {reject: false});57+ t.true(escapedCommand.startsWith(`${QUOTE}node `));58+});59+60+test('execaCommand() bound options have lower priority', async t => {61+ const {stdout} = await execaCommand({stripFinalNewline: false})('echo.js foo bar', {stripFinalNewline: true});62+ t.is(stdout, 'foo\nbar');63+});64+65+test('execaCommandSync() bound options have lower priority', t => {66+ const {stdout} = execaCommandSync({stripFinalNewline: false})('echo.js foo bar', {stripFinalNewline: true});67+ t.is(stdout, 'foo\nbar');68+});69+70+test('execaCommand() ignores consecutive spaces', async t => {71+ const {stdout} = await execaCommand('echo.js foo bar');72+ t.is(stdout, 'foo\nbar');73+});74+75+test('execaCommand() allows escaping spaces in commands', async t => {76+ const {stdout} = await execaCommand('command\\ with\\ space.js foo bar');77+ t.is(stdout, 'foo\nbar');78+});79+80+test('execaCommand() allows escaping spaces in arguments', async t => {81+ const {stdout} = await execaCommand('echo.js foo\\ bar');82+ t.is(stdout, 'foo bar');83+});84+85+test('execaCommand() escapes other whitespaces', async t => {86+ const {stdout} = await execaCommand('echo.js foo\tbar');87+ t.is(stdout, 'foo\tbar');88+});89+90+test('execaCommand() trims', async t => {91+ const {stdout} = await execaCommand(' echo.js foo bar ');92+ t.is(stdout, 'foo\nbar');93+});94+95+const testInvalidArgsArray = (t, execaMethod) => {96+ t.throws(() => {97+ execaMethod('echo', ['foo']);98+ }, {message: /The command and its arguments must be passed as a single string/});99+};100+101+test('execaCommand() must not pass an array of arguments', testInvalidArgsArray, execaCommand);102+test('execaCommandSync() must not pass an array of arguments', testInvalidArgsArray, execaCommandSync);103+104+const testInvalidArgsTemplate = (t, execaMethod) => {105+ t.throws(() => {106+ // eslint-disable-next-line no-unused-expressions107+ execaMethod`echo foo`;108+ }, {message: /The command and its arguments must be passed as a single string/});109+};110+111+test('execaCommand() must not pass an array of arguments with a template string', testInvalidArgsTemplate, execaCommand);112+test('execaCommandSync() must not pass an array of arguments with a template string', testInvalidArgsTemplate, execaCommandSync);added:test/methods/create-bind.js+104 added
1+import {join} from 'node:path';2+import test from 'ava';3+import {execa, execaSync, execaNode, $} from '../../index.js';4+import {foobarString, foobarUppercase} from '../helpers/input.js';5+import {uppercaseGenerator} from '../helpers/generator.js';6+import {setFixtureDir, FIXTURES_DIR} from '../helpers/fixtures-dir.js';7+8+setFixtureDir();9+10+const NOOP_PATH = join(FIXTURES_DIR, 'noop.js');11+const PRINT_ENV_PATH = join(FIXTURES_DIR, 'environment.js');12+13+const testBindOptions = async (t, execaMethod) => {14+ const {stdout} = await execaMethod({stripFinalNewline: false})(NOOP_PATH, [foobarString]);15+ t.is(stdout, `${foobarString}\n`);16+};17+18+test('execa() can bind options', testBindOptions, execa);19+test('execaNode() can bind options', testBindOptions, execaNode);20+test('$ can bind options', testBindOptions, $);21+22+const testBindOptionsSync = (t, execaMethod) => {23+ const {stdout} = execaMethod({stripFinalNewline: false})(NOOP_PATH, [foobarString]);24+ t.is(stdout, `${foobarString}\n`);25+};26+27+test('execaSync() can bind options', testBindOptionsSync, execaSync);28+test('$.sync can bind options', testBindOptionsSync, $.sync);29+30+const testBindPriority = async (t, execaMethod) => {31+ const {stdout} = await execaMethod({stripFinalNewline: false})(NOOP_PATH, [foobarString], {stripFinalNewline: true});32+ t.is(stdout, foobarString);33+};34+35+test('execa() bound options have lower priority', testBindPriority, execa);36+test('execaSync() bound options have lower priority', testBindPriority, execaSync);37+test('execaNode() bound options have lower priority', testBindPriority, execaNode);38+test('$ bound options have lower priority', testBindPriority, $);39+test('$.sync bound options have lower priority', testBindPriority, $.sync);40+41+const testBindUndefined = async (t, execaMethod) => {42+ const {stdout} = await execaMethod({stripFinalNewline: false})(NOOP_PATH, [foobarString], {stripFinalNewline: undefined});43+ t.is(stdout, foobarString);44+};45+46+test('execa() undefined options use default value', testBindUndefined, execa);47+test('execaSync() undefined options use default value', testBindUndefined, execaSync);48+test('execaNode() undefined options use default value', testBindUndefined, execaNode);49+test('$ undefined options use default value', testBindUndefined, $);50+test('$.sync undefined options use default value', testBindUndefined, $.sync);51+52+const testMergeEnv = async (t, execaMethod) => {53+ const {stdout} = await execaMethod({env: {FOO: 'foo'}})(PRINT_ENV_PATH, {env: {BAR: 'bar'}});54+ t.is(stdout, 'foo\nbar');55+};56+57+test('execa() bound options are merged', testMergeEnv, execa);58+test('execaSync() bound options are merged', testMergeEnv, execaSync);59+test('execaNode() bound options are merged', testMergeEnv, execaNode);60+test('$ bound options are merged', testMergeEnv, $);61+test('$.sync bound options are merged', testMergeEnv, $.sync);62+63+const testMergeMultiple = async (t, execaMethod) => {64+ const {stdout} = await execaMethod({env: {FOO: 'baz'}})({env: {BAR: 'bar'}})(PRINT_ENV_PATH, {env: {FOO: 'foo'}});65+ t.is(stdout, 'foo\nbar');66+};67+68+test('execa() bound options are merged multiple times', testMergeMultiple, execa);69+test('execaSync() bound options are merged multiple times', testMergeMultiple, execaSync);70+test('execaNode() bound options are merged multiple times', testMergeMultiple, execaNode);71+test('$ bound options are merged multiple times', testMergeMultiple, $);72+test('$.sync bound options are merged multiple times', testMergeMultiple, $.sync);73+74+const testMergeFdSpecific = async (t, execaMethod) => {75+ const {isMaxBuffer, shortMessage} = await t.throwsAsync(execaMethod({maxBuffer: {stdout: 1}})(NOOP_PATH, [foobarString], {maxBuffer: {stderr: 100}}));76+ t.true(isMaxBuffer);77+ t.true(shortMessage.includes('Command\'s stdout was larger than 1'));78+};79+80+test('execa() bound options merge fd-specific ones', testMergeFdSpecific, execa);81+test('execaNode() bound options merge fd-specific ones', testMergeFdSpecific, execaNode);82+test('$ bound options merge fd-specific ones', testMergeFdSpecific, $);83+84+const testMergeEnvUndefined = async (t, execaMethod) => {85+ const {stdout} = await execaMethod({env: {FOO: 'foo'}})(PRINT_ENV_PATH, {env: {BAR: undefined}});86+ t.is(stdout, 'foo\nundefined');87+};88+89+test('execa() bound options are merged even if undefined', testMergeEnvUndefined, execa);90+test('execaSync() bound options are merged even if undefined', testMergeEnvUndefined, execaSync);91+test('execaNode() bound options are merged even if undefined', testMergeEnvUndefined, execaNode);92+test('$ bound options are merged even if undefined', testMergeEnvUndefined, $);93+test('$.sync bound options are merged even if undefined', testMergeEnvUndefined, $.sync);94+95+const testMergeSpecific = async (t, execaMethod) => {96+ const {stdout} = await execaMethod({stdout: {transform: uppercaseGenerator().transform, objectMode: true}})(NOOP_PATH, {stdout: {transform: uppercaseGenerator().transform}});97+ t.is(stdout, foobarUppercase);98+};99+100+test('execa() bound options only merge specific ones', testMergeSpecific, execa);101+test('execaSync() bound options only merge specific ones', testMergeSpecific, execaSync);102+test('execaNode() bound options only merge specific ones', testMergeSpecific, execaNode);103+test('$ bound options only merge specific ones', testMergeSpecific, $);104+test('$.sync bound options only merge specific ones', testMergeSpecific, $.sync);added:test/methods/create-main.js+58 added
1+import {join} from 'node:path';2+import test from 'ava';3+import {execa, execaSync, execaNode, $} from '../../index.js';4+import {foobarString, foobarArray} from '../helpers/input.js';5+import {setFixtureDir, FIXTURES_DIR} from '../helpers/fixtures-dir.js';6+7+setFixtureDir();8+9+const NOOP_PATH = join(FIXTURES_DIR, 'noop.js');10+11+const testTemplate = async (t, execaMethod) => {12+ const {stdout} = await execaMethod`${NOOP_PATH} ${foobarString}`;13+ t.is(stdout, foobarString);14+};15+16+test('execa() can use template strings', testTemplate, execa);17+test('execaNode() can use template strings', testTemplate, execaNode);18+test('$ can use template strings', testTemplate, $);19+20+const testTemplateSync = (t, execaMethod) => {21+ const {stdout} = execaMethod`${NOOP_PATH} ${foobarString}`;22+ t.is(stdout, foobarString);23+};24+25+test('execaSync() can use template strings', testTemplateSync, execaSync);26+test('$.sync can use template strings', testTemplateSync, $.sync);27+28+const testTemplateOptions = async (t, execaMethod) => {29+ const {stdout} = await execaMethod({stripFinalNewline: false})`${NOOP_PATH} ${foobarString}`;30+ t.is(stdout, `${foobarString}\n`);31+};32+33+test('execa() can use template strings with options', testTemplateOptions, execa);34+test('execaNode() can use template strings with options', testTemplateOptions, execaNode);35+test('$ can use template strings with options', testTemplateOptions, $);36+37+const testTemplateOptionsSync = (t, execaMethod) => {38+ const {stdout} = execaMethod({stripFinalNewline: false})`${NOOP_PATH} ${foobarString}`;39+ t.is(stdout, `${foobarString}\n`);40+};41+42+test('execaSync() can use template strings with options', testTemplateOptionsSync, execaSync);43+test('$.sync can use template strings with options', testTemplateOptionsSync, $.sync);44+45+const testSpacedCommand = async (t, args, execaMethod) => {46+ const {stdout} = await execaMethod('command with space.js', args);47+ const expectedStdout = args === undefined ? '' : args.join('\n');48+ t.is(stdout, expectedStdout);49+};50+51+test('allow commands with spaces and no array arguments', testSpacedCommand, undefined, execa);52+test('allow commands with spaces and array arguments', testSpacedCommand, foobarArray, execa);53+test('allow commands with spaces and no array arguments, execaSync', testSpacedCommand, undefined, execaSync);54+test('allow commands with spaces and array arguments, execaSync', testSpacedCommand, foobarArray, execaSync);55+test('allow commands with spaces and no array arguments, $', testSpacedCommand, undefined, $);56+test('allow commands with spaces and array arguments, $', testSpacedCommand, foobarArray, $);57+test('allow commands with spaces and no array arguments, $.sync', testSpacedCommand, undefined, $.sync);58+test('allow commands with spaces and array arguments, $.sync', testSpacedCommand, foobarArray, $.sync);added:test/methods/main-async.js+26 added
1+import process from 'node:process';2+import test from 'ava';3+import {execa} from '../../index.js';4+import {setFixtureDir} from '../helpers/fixtures-dir.js';5+6+setFixtureDir();7+8+const isWindows = process.platform === 'win32';9+10+if (isWindows) {11+ test('execa() - cmd file', async t => {12+ const {stdout} = await execa('hello.cmd');13+ t.is(stdout, 'Hello World');14+ });15+16+ test('execa() - run cmd command', async t => {17+ const {stdout} = await execa('cmd', ['/c', 'hello.cmd']);18+ t.is(stdout, 'Hello World');19+ });20+}21+22+test('execa() returns a promise with pid', async t => {23+ const subprocess = execa('noop.js', ['foo']);24+ t.is(typeof subprocess.pid, 'number');25+ await subprocess;26+});added:test/methods/node.js+305 added
1+import {once} from 'node:events';2+import {dirname, relative} from 'node:path';3+import process, {version} from 'node:process';4+import {pathToFileURL} from 'node:url';5+import test from 'ava';6+import getNode from 'get-node';7+import {pEvent} from 'p-event';8+import {execa, execaSync, execaNode} from '../../index.js';9+import {FIXTURES_DIR} from '../helpers/fixtures-dir.js';10+import {identity, fullStdio} from '../helpers/stdio.js';11+import {foobarString} from '../helpers/input.js';12+13+process.chdir(FIXTURES_DIR);14+15+const runWithNodeOption = (file, args, options) => Array.isArray(args)16+ ? execa(file, args, {...options, node: true})17+ : execa(file, {...options, node: true});18+const runWithNodeOptionSync = (file, args, options) => Array.isArray(args)19+ ? execaSync(file, args, {...options, node: true})20+ : execaSync(file, {...options, node: true});21+const runWithIpc = (file, options) => execa('node', [file], {...options, ipc: true});22+23+const testNodeSuccess = async (t, execaMethod) => {24+ const {exitCode, stdout} = await execaMethod('noop.js', [foobarString]);25+ t.is(exitCode, 0);26+ t.is(stdout, foobarString);27+};28+29+test('execaNode() succeeds', testNodeSuccess, execaNode);30+test('The "node" option succeeds', testNodeSuccess, runWithNodeOption);31+test('The "node" option succeeds - sync', testNodeSuccess, runWithNodeOptionSync);32+33+test('execaNode(options) succeeds', async t => {34+ const {stdout} = await execaNode({stripFinalNewline: false})('noop.js', [foobarString]);35+ t.is(stdout, `${foobarString}\n`);36+});37+38+test('execaNode`...` succeeds', async t => {39+ const {stdout} = await execaNode`noop.js ${foobarString}`;40+ t.is(stdout, foobarString);41+});42+43+test('execaNode().pipe(execaNode()) succeeds', async t => {44+ const {stdout} = await execaNode('noop.js').pipe(execaNode('--version'));45+ t.is(stdout, version);46+});47+48+test('execaNode().pipe(execa()) requires using "node"', async t => {49+ await t.throwsAsync(execaNode('noop.js').pipe(execa('--version')));50+});51+52+test('execaNode().pipe(...) requires using "node"', async t => {53+ await t.throwsAsync(execaNode('noop.js').pipe('--version'));54+});55+56+test('execaNode().pipe`...` requires using "node"', async t => {57+ await t.throwsAsync(execaNode('noop.js').pipe`--version`);58+});59+60+test('execaNode() cannot set the "node" option to false', t => {61+ t.throws(() => {62+ execaNode('empty.js', {node: false});63+ }, {message: /The "node" option cannot be false/});64+});65+66+const testDoubleNode = (t, nodePath, execaMethod) => {67+ t.throws(() => {68+ execaMethod(nodePath, ['noop.js']);69+ }, {message: /does not need to be "node"/});70+};71+72+test('Cannot use "node" as binary - execaNode()', testDoubleNode, 'node', execaNode);73+test('Cannot use "node" as binary - "node" option', testDoubleNode, 'node', runWithNodeOption);74+test('Cannot use "node" as binary - "node" option sync', testDoubleNode, 'node', runWithNodeOptionSync);75+test('Cannot use path to "node" as binary - execaNode()', testDoubleNode, process.execPath, execaNode);76+test('Cannot use path to "node" as binary - "node" option', testDoubleNode, process.execPath, runWithNodeOption);77+test('Cannot use path to "node" as binary - "node" option sync', testDoubleNode, process.execPath, runWithNodeOptionSync);78+79+const getNodePath = async () => {80+ const {path} = await getNode(TEST_NODE_VERSION);81+ return path;82+};83+84+const TEST_NODE_VERSION = '16.0.0';85+86+const testNodePath = async (t, execaMethod, mapPath) => {87+ const nodePath = mapPath(await getNodePath());88+ const {stdout} = await execaMethod('--version', [], {nodePath});89+ t.is(stdout, `v${TEST_NODE_VERSION}`);90+};91+92+test.serial('The "nodePath" option can be used - execaNode()', testNodePath, execaNode, identity);93+test.serial('The "nodePath" option can be a file URL - execaNode()', testNodePath, execaNode, pathToFileURL);94+test.serial('The "nodePath" option can be used - "node" option', testNodePath, runWithNodeOption, identity);95+test.serial('The "nodePath" option can be a file URL - "node" option', testNodePath, runWithNodeOption, pathToFileURL);96+test.serial('The "nodePath" option can be used - "node" option sync', testNodePath, runWithNodeOptionSync, identity);97+test.serial('The "nodePath" option can be a file URL - "node" option sync', testNodePath, runWithNodeOptionSync, pathToFileURL);98+99+const testNodePathDefault = async (t, execaMethod) => {100+ const {stdout} = await execaMethod('--version');101+ t.is(stdout, process.version);102+};103+104+test('The "nodePath" option defaults to the current Node.js binary - execaNode()', testNodePathDefault, execaNode);105+test('The "nodePath" option defaults to the current Node.js binary - "node" option', testNodePathDefault, runWithNodeOption);106+test('The "nodePath" option defaults to the current Node.js binary - "node" option sync', testNodePathDefault, runWithNodeOptionSync);107+108+const testNodePathInvalid = (t, execaMethod) => {109+ t.throws(() => {110+ execaMethod('noop.js', [], {nodePath: true});111+ }, {message: /The "nodePath" option must be a string or a file URL/});112+};113+114+test('The "nodePath" option must be a string or URL - execaNode()', testNodePathInvalid, execaNode);115+test('The "nodePath" option must be a string or URL - "node" option', testNodePathInvalid, runWithNodeOption);116+test('The "nodePath" option must be a string or URL - "node" option sync', testNodePathInvalid, runWithNodeOptionSync);117+118+const testFormerNodePath = (t, execaMethod) => {119+ t.throws(() => {120+ execaMethod('noop.js', [], {execPath: process.execPath});121+ }, {message: /The "execPath" option has been removed/});122+};123+124+test('The "execPath" option cannot be used - execaNode()', testFormerNodePath, execaNode);125+test('The "execPath" option cannot be used - "node" option', testFormerNodePath, runWithNodeOption);126+test('The "execPath" option cannot be used - "node" option sync', testFormerNodePath, runWithNodeOptionSync);127+128+const nodePathArguments = ['-p', ['process.env.Path || process.env.PATH']];129+130+const testSubprocessNodePath = async (t, execaMethod, mapPath) => {131+ const nodePath = mapPath(await getNodePath());132+ const {stdout} = await execaMethod(...nodePathArguments, {nodePath});133+ t.true(stdout.includes(TEST_NODE_VERSION));134+};135+136+test.serial('The "nodePath" option impacts the subprocess - execaNode()', testSubprocessNodePath, execaNode, identity);137+test.serial('The "nodePath" option impacts the subprocess - "node" option', testSubprocessNodePath, runWithNodeOption, identity);138+test.serial('The "nodePath" option impacts the subprocess - "node" option sync', testSubprocessNodePath, runWithNodeOptionSync, identity);139+140+const testSubprocessNodePathDefault = async (t, execaMethod) => {141+ const {stdout} = await execaMethod(...nodePathArguments);142+ t.true(stdout.includes(dirname(process.execPath)));143+};144+145+test('The "nodePath" option defaults to the current Node.js binary in the subprocess - execaNode()', testSubprocessNodePathDefault, execaNode);146+test('The "nodePath" option defaults to the current Node.js binary in the subprocess - "node" option', testSubprocessNodePathDefault, runWithNodeOption);147+test('The "nodePath" option defaults to the current Node.js binary in the subprocess - "node" option sync', testSubprocessNodePathDefault, runWithNodeOptionSync);148+149+test.serial('The "nodePath" option requires "node: true" to impact the subprocess', async t => {150+ const nodePath = await getNodePath();151+ const {stdout} = await execa('node', nodePathArguments.flat(), {nodePath});152+ t.false(stdout.includes(TEST_NODE_VERSION));153+});154+155+const testSubprocessNodePathCwd = async (t, execaMethod) => {156+ const nodePath = await getNodePath();157+ const cwd = dirname(dirname(nodePath));158+ const relativeExecPath = relative(cwd, nodePath);159+ const {stdout} = await execaMethod(...nodePathArguments, {nodePath: relativeExecPath, cwd});160+ t.true(stdout.includes(TEST_NODE_VERSION));161+};162+163+test.serial('The "nodePath" option is relative to "cwd" when used in the subprocess - execaNode()', testSubprocessNodePathCwd, execaNode);164+test.serial('The "nodePath" option is relative to "cwd" when used in the subprocess - "node" option', testSubprocessNodePathCwd, runWithNodeOption);165+test.serial('The "nodePath" option is relative to "cwd" when used in the subprocess - "node" option sync', testSubprocessNodePathCwd, runWithNodeOptionSync);166+167+const testCwdNodePath = async (t, execaMethod) => {168+ const nodePath = await getNodePath();169+ const cwd = dirname(dirname(nodePath));170+ const relativeExecPath = relative(cwd, nodePath);171+ const {stdout} = await execaMethod('--version', [], {nodePath: relativeExecPath, cwd});172+ t.is(stdout, `v${TEST_NODE_VERSION}`);173+};174+175+test.serial('The "nodePath" option is relative to "cwd" - execaNode()', testCwdNodePath, execaNode);176+test.serial('The "nodePath" option is relative to "cwd" - "node" option', testCwdNodePath, runWithNodeOption);177+test.serial('The "nodePath" option is relative to "cwd" - "node" option sync', testCwdNodePath, runWithNodeOptionSync);178+179+const testNodeOptions = async (t, execaMethod) => {180+ const {stdout} = await execaMethod('empty.js', [], {nodeOptions: ['--version']});181+ t.is(stdout, process.version);182+};183+184+test('The "nodeOptions" option can be used - execaNode()', testNodeOptions, execaNode);185+test('The "nodeOptions" option can be used - "node" option', testNodeOptions, runWithNodeOption);186+test('The "nodeOptions" option can be used - "node" option sync', testNodeOptions, runWithNodeOptionSync);187+188+const spawnNestedExecaNode = (realExecArgv, fakeExecArgv, execaMethod, nodeOptions) => execa(189+ 'node',190+ [...realExecArgv, 'nested-node.js', fakeExecArgv, execaMethod, nodeOptions, 'noop.js', foobarString],191+ {...fullStdio, cwd: FIXTURES_DIR},192+);193+194+const testInspectRemoval = async (t, fakeExecArgv, execaMethod) => {195+ const {stdout, stdio} = await spawnNestedExecaNode([], fakeExecArgv, execaMethod, '');196+ t.is(stdout, foobarString);197+ t.is(stdio[3], '');198+};199+200+test('The "nodeOptions" option removes --inspect without a port when defined by current process - execaNode()', testInspectRemoval, '--inspect', 'execaNode');201+test('The "nodeOptions" option removes --inspect without a port when defined by current process - "node" option', testInspectRemoval, '--inspect', 'nodeOption');202+test('The "nodeOptions" option removes --inspect with a port when defined by current process - execaNode()', testInspectRemoval, '--inspect=9222', 'execaNode');203+test('The "nodeOptions" option removes --inspect with a port when defined by current process - "node" option', testInspectRemoval, '--inspect=9222', 'nodeOption');204+test('The "nodeOptions" option removes --inspect-brk without a port when defined by current process - execaNode()', testInspectRemoval, '--inspect-brk', 'execaNode');205+test('The "nodeOptions" option removes --inspect-brk without a port when defined by current process - "node" option', testInspectRemoval, '--inspect-brk', 'nodeOption');206+test('The "nodeOptions" option removes --inspect-brk with a port when defined by current process - execaNode()', testInspectRemoval, '--inspect-brk=9223', 'execaNode');207+test('The "nodeOptions" option removes --inspect-brk with a port when defined by current process - "node" option', testInspectRemoval, '--inspect-brk=9223', 'nodeOption');208+209+const testInspectDifferentPort = async (t, execaMethod) => {210+ const {stdout, stdio} = await spawnNestedExecaNode(['--inspect=9225'], '', execaMethod, '--inspect=9224');211+ t.is(stdout, foobarString);212+ t.true(stdio[3].includes('Debugger listening'));213+};214+215+test.serial('The "nodeOptions" option allows --inspect with a different port even when defined by current process - execaNode()', testInspectDifferentPort, 'execaNode');216+test.serial('The "nodeOptions" option allows --inspect with a different port even when defined by current process - "node" option', testInspectDifferentPort, 'nodeOption');217+218+const testInspectSamePort = async (t, execaMethod) => {219+ const {stdout, stdio} = await spawnNestedExecaNode(['--inspect=9226'], '', execaMethod, '--inspect=9226');220+ t.is(stdout, foobarString);221+ t.true(stdio[3].includes('address already in use'));222+};223+224+test.serial('The "nodeOptions" option forbids --inspect with the same port when defined by current process - execaNode()', testInspectSamePort, 'execaNode');225+test.serial('The "nodeOptions" option forbids --inspect with the same port when defined by current process - "node" option', testInspectSamePort, 'nodeOption');226+227+const testIpc = async (t, execaMethod, options) => {228+ const subprocess = execaMethod('send.js', [], options);229+ await pEvent(subprocess, 'message');230+ subprocess.send(foobarString);231+ const {stdout, stdio} = await subprocess;232+ t.is(stdout, foobarString);233+ t.is(stdio.length, 4);234+ t.is(stdio[3], undefined);235+};236+237+test('execaNode() adds an ipc channel', testIpc, execaNode, {});238+test('The "node" option adds an ipc channel', testIpc, runWithNodeOption, {});239+test('The "ipc" option adds an ipc channel', testIpc, runWithIpc, {});240+test('The "ipc" option works with "stdio: \'pipe\'"', testIpc, runWithIpc, {stdio: 'pipe'});241+test('The "ipc" option works with "stdio: [\'pipe\', \'pipe\', \'pipe\']"', testIpc, runWithIpc, {stdio: ['pipe', 'pipe', 'pipe']});242+test('The "ipc" option works with "stdio: [\'pipe\', \'pipe\', \'pipe\', \'ipc\']"', testIpc, runWithIpc, {stdio: ['pipe', 'pipe', 'pipe', 'ipc']});243+test('The "ipc" option works with "stdout: \'pipe\'"', testIpc, runWithIpc, {stdout: 'pipe'});244+245+test('No ipc channel is added by default', async t => {246+ const {stdio} = await t.throwsAsync(execa('node', ['send.js']), {message: /process.send is not a function/});247+ t.is(stdio.length, 3);248+});249+250+const testDisableIpc = async (t, execaMethod) => {251+ const {failed, message, stdio} = await execaMethod('send.js', [], {ipc: false, reject: false});252+ t.true(failed);253+ t.true(message.includes('process.send is not a function'));254+ t.is(stdio.length, 3);255+};256+257+test('Can disable "ipc" - execaNode()', testDisableIpc, execaNode);258+test('Can disable "ipc" - "node" option', testDisableIpc, runWithNodeOption);259+test('Can disable "ipc" - "node" option sync', testDisableIpc, runWithNodeOptionSync);260+261+const NO_IPC_MESSAGE = /The "ipc: true" option cannot be used/;262+263+const testNoIpcSync = (t, node) => {264+ t.throws(() => {265+ execaSync('node', ['send.js'], {ipc: true, node});266+ }, {message: NO_IPC_MESSAGE});267+};268+269+test('Cannot use "ipc: true" with execaSync()', testNoIpcSync, undefined);270+test('Cannot use "ipc: true" with execaSync() - "node: false"', testNoIpcSync, false);271+272+test('Cannot use "ipc: true" with execaSync() - "node: true"', t => {273+ t.throws(() => {274+ execaSync('send.js', {ipc: true, node: true});275+ }, {message: NO_IPC_MESSAGE});276+});277+278+const testNoShell = async (t, execaMethod) => {279+ const {failed, message} = await execaMethod('node --version', [], {shell: true, reject: false});280+ t.true(failed);281+ t.true(message.includes('MODULE_NOT_FOUND'));282+};283+284+test('Cannot use "shell: true" - execaNode()', testNoShell, execaNode);285+test('Cannot use "shell: true" - "node" option', testNoShell, runWithNodeOption);286+test('Cannot use "shell: true" - "node" option sync', testNoShell, runWithNodeOptionSync);287+288+test('The "serialization" option defaults to "advanced"', async t => {289+ const subprocess = execa('node', ['ipc-echo.js'], {ipc: true});290+ subprocess.send([0n]);291+ const [message] = await once(subprocess, 'message');292+ t.is(message[0], 0n);293+ await subprocess;294+});295+296+test('The "serialization" option can be set to "json"', async t => {297+ const subprocess = execa('node', ['ipc-echo.js'], {ipc: true, serialization: 'json'});298+ t.throws(() => {299+ subprocess.send([0n]);300+ }, {message: /serialize a BigInt/});301+ subprocess.send(0);302+ const [message] = await once(subprocess, 'message');303+ t.is(message, 0);304+ await subprocess;305+});added:test/methods/override-promise.js+13 added
1+import test from 'ava';2+// The helper module overrides Promise on import so has to be imported before `execa`.3+import {restorePromise} from '../helpers/override-promise.js';4+import {execa} from '../../index.js';5+import {setFixtureDir} from '../helpers/fixtures-dir.js';6+7+restorePromise();8+setFixtureDir();9+10+test('should work with third-party Promise', async t => {11+ const {stdout} = await execa('noop.js', ['foo']);12+ t.is(stdout, 'foo');13+});added:test/methods/parameters-args.js+47 added
1+import test from 'ava';2+import {execa, execaSync, execaCommand, execaCommandSync, execaNode, $} from '../../index.js';3+import {setFixtureDir} from '../helpers/fixtures-dir.js';4+5+setFixtureDir();6+7+const testInvalidArgs = async (t, execaMethod) => {8+ t.throws(() => {9+ execaMethod('echo', true);10+ }, {message: /Second argument must be either/});11+};12+13+test('execa()\'s second argument must be valid', testInvalidArgs, execa);14+test('execaSync()\'s second argument must be valid', testInvalidArgs, execaSync);15+test('execaCommand()\'s second argument must be valid', testInvalidArgs, execaCommand);16+test('execaCommandSync()\'s second argument must be valid', testInvalidArgs, execaCommandSync);17+test('execaNode()\'s second argument must be valid', testInvalidArgs, execaNode);18+test('$\'s second argument must be valid', testInvalidArgs, $);19+test('$.sync\'s second argument must be valid', testInvalidArgs, $.sync);20+21+const testInvalidArgsItems = async (t, execaMethod) => {22+ t.throws(() => {23+ execaMethod('echo', [{}]);24+ }, {message: 'Second argument must be an array of strings: [object Object]'});25+};26+27+test('execa()\'s second argument must not be objects', testInvalidArgsItems, execa);28+test('execaSync()\'s second argument must not be objects', testInvalidArgsItems, execaSync);29+test('execaCommand()\'s second argument must not be objects', testInvalidArgsItems, execaCommand);30+test('execaCommandSync()\'s second argument must not be objects', testInvalidArgsItems, execaCommandSync);31+test('execaNode()\'s second argument must not be objects', testInvalidArgsItems, execaNode);32+test('$\'s second argument must not be objects', testInvalidArgsItems, $);33+test('$.sync\'s second argument must not be objects', testInvalidArgsItems, $.sync);34+35+const testNullByteArg = async (t, execaMethod) => {36+ t.throws(() => {37+ execaMethod('echo', ['a\0b']);38+ }, {message: /null bytes/});39+};40+41+test('execa()\'s second argument must not include \\0', testNullByteArg, execa);42+test('execaSync()\'s second argument must not include \\0', testNullByteArg, execaSync);43+test('execaCommand()\'s second argument must not include \\0', testNullByteArg, execaCommand);44+test('execaCommandSync()\'s second argument must not include \\0', testNullByteArg, execaCommandSync);45+test('execaNode()\'s second argument must not include \\0', testNullByteArg, execaNode);46+test('$\'s second argument must not include \\0', testNullByteArg, $);47+test('$.sync\'s second argument must not include \\0', testNullByteArg, $.sync);added:test/methods/parameters-command.js+80 added
1+import {join, basename} from 'node:path';2+import {fileURLToPath} from 'node:url';3+import test from 'ava';4+import {execa, execaSync, execaCommand, execaCommandSync, execaNode, $} from '../../index.js';5+import {setFixtureDir, FIXTURES_DIR_URL} from '../helpers/fixtures-dir.js';6+import {foobarString} from '../helpers/input.js';7+8+setFixtureDir();9+10+const testFileUrl = async (t, execaMethod) => {11+ const command = new URL('noop.js', FIXTURES_DIR_URL);12+ const {stdout} = await execaMethod(command);13+ t.is(stdout, foobarString);14+};15+16+test('execa()\'s command argument can be a file URL', testFileUrl, execa);17+test('execaSync()\'s command argument can be a file URL', testFileUrl, execaSync);18+test('execaCommand()\'s command argument can be a file URL', testFileUrl, execaCommand);19+test('execaCommandSync()\'s command argument can be a file URL', testFileUrl, execaCommandSync);20+test('execaNode()\'s command argument can be a file URL', testFileUrl, execaNode);21+test('$\'s command argument can be a file URL', testFileUrl, $);22+test('$.sync\'s command argument can be a file URL', testFileUrl, $.sync);23+24+const testInvalidFileUrl = async (t, execaMethod) => {25+ const invalidUrl = new URL('https://invalid.com');26+ t.throws(() => {27+ execaMethod(invalidUrl);28+ }, {code: 'ERR_INVALID_URL_SCHEME'});29+};30+31+test('execa()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execa);32+test('execaSync()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execaSync);33+test('execaCommand()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execaCommand);34+test('execaCommandSync()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execaCommandSync);35+test('execaNode()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execaNode);36+test('$\'s command argument cannot be a non-file URL', testInvalidFileUrl, $);37+test('$.sync\'s command argument cannot be a non-file URL', testInvalidFileUrl, $.sync);38+39+const testInvalidCommand = async (t, arg, execaMethod) => {40+ t.throws(() => {41+ execaMethod(arg);42+ }, {message: /First argument must be a string or a file URL/});43+};44+45+test('execa()\'s first argument must be defined', testInvalidCommand, undefined, execa);46+test('execaSync()\'s first argument must be defined', testInvalidCommand, undefined, execaSync);47+test('execaCommand()\'s first argument must be defined', testInvalidCommand, undefined, execaCommand);48+test('execaCommandSync()\'s first argument must be defined', testInvalidCommand, undefined, execaCommandSync);49+test('execaNode()\'s first argument must be defined', testInvalidCommand, undefined, execaNode);50+test('$\'s first argument must be defined', testInvalidCommand, undefined, $);51+test('$.sync\'s first argument must be defined', testInvalidCommand, undefined, $.sync);52+test('execa()\'s first argument must be valid', testInvalidCommand, true, execa);53+test('execaSync()\'s first argument must be valid', testInvalidCommand, true, execaSync);54+test('execaCommand()\'s first argument must be valid', testInvalidCommand, true, execaCommand);55+test('execaCommandSync()\'s first argument must be valid', testInvalidCommand, true, execaCommandSync);56+test('execaNode()\'s first argument must be valid', testInvalidCommand, true, execaNode);57+test('$\'s first argument must be valid', testInvalidCommand, true, $);58+test('$.sync\'s first argument must be valid', testInvalidCommand, true, $.sync);59+test('execa()\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], execa);60+test('execaSync()\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], execaSync);61+test('execaCommand()\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], execaCommand);62+test('execaCommandSync()\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], execaCommandSync);63+test('execaNode()\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], execaNode);64+test('$\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], $);65+test('$.sync\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], $.sync);66+67+const testRelativePath = async (t, execaMethod) => {68+ const rootDir = basename(fileURLToPath(new URL('../..', import.meta.url)));69+ const pathViaParentDir = join('..', rootDir, 'test', 'fixtures', 'noop.js');70+ const {stdout} = await execaMethod(pathViaParentDir);71+ t.is(stdout, foobarString);72+};73+74+test('execa() use relative path with \'..\' chars', testRelativePath, execa);75+test('execaSync() use relative path with \'..\' chars', testRelativePath, execaSync);76+test('execaCommand() use relative path with \'..\' chars', testRelativePath, execaCommand);77+test('execaCommandSync() use relative path with \'..\' chars', testRelativePath, execaCommandSync);78+test('execaNode() use relative path with \'..\' chars', testRelativePath, execaNode);79+test('$ use relative path with \'..\' chars', testRelativePath, $);80+test('$.sync use relative path with \'..\' chars', testRelativePath, $.sync);added:test/methods/parameters-options.js+68 added
1+import {join} from 'node:path';2+import test from 'ava';3+import {execa, execaSync, execaCommand, execaCommandSync, execaNode, $} from '../../index.js';4+import {setFixtureDir, FIXTURES_DIR} from '../helpers/fixtures-dir.js';5+6+setFixtureDir();7+8+const NOOP_PATH = join(FIXTURES_DIR, 'noop.js');9+10+const testSerializeArg = async (t, arg, execaMethod) => {11+ const {stdout} = await execaMethod(NOOP_PATH, [arg]);12+ t.is(stdout, String(arg));13+};14+15+test('execa()\'s arguments can be numbers', testSerializeArg, 1, execa);16+test('execa()\'s arguments can be booleans', testSerializeArg, true, execa);17+test('execa()\'s arguments can be NaN', testSerializeArg, Number.NaN, execa);18+test('execa()\'s arguments can be Infinity', testSerializeArg, Number.POSITIVE_INFINITY, execa);19+test('execa()\'s arguments can be null', testSerializeArg, null, execa);20+test('execa()\'s arguments can be undefined', testSerializeArg, undefined, execa);21+test('execa()\'s arguments can be bigints', testSerializeArg, 1n, execa);22+test('execa()\'s arguments can be symbols', testSerializeArg, Symbol('test'), execa);23+test('execaSync()\'s arguments can be numbers', testSerializeArg, 1, execaSync);24+test('execaSync()\'s arguments can be booleans', testSerializeArg, true, execaSync);25+test('execaSync()\'s arguments can be NaN', testSerializeArg, Number.NaN, execaSync);26+test('execaSync()\'s arguments can be Infinity', testSerializeArg, Number.POSITIVE_INFINITY, execaSync);27+test('execaSync()\'s arguments can be null', testSerializeArg, null, execaSync);28+test('execaSync()\'s arguments can be undefined', testSerializeArg, undefined, execaSync);29+test('execaSync()\'s arguments can be bigints', testSerializeArg, 1n, execaSync);30+test('execaSync()\'s arguments can be symbols', testSerializeArg, Symbol('test'), execaSync);31+test('execaNode()\'s arguments can be numbers', testSerializeArg, 1, execaNode);32+test('execaNode()\'s arguments can be booleans', testSerializeArg, true, execaNode);33+test('execaNode()\'s arguments can be NaN', testSerializeArg, Number.NaN, execaNode);34+test('execaNode()\'s arguments can be Infinity', testSerializeArg, Number.POSITIVE_INFINITY, execaNode);35+test('execaNode()\'s arguments can be null', testSerializeArg, null, execaNode);36+test('execaNode()\'s arguments can be undefined', testSerializeArg, undefined, execaNode);37+test('execaNode()\'s arguments can be bigints', testSerializeArg, 1n, execaNode);38+test('execaNode()\'s arguments can be symbols', testSerializeArg, Symbol('test'), execaNode);39+test('$\'s arguments can be numbers', testSerializeArg, 1, $);40+test('$\'s arguments can be booleans', testSerializeArg, true, $);41+test('$\'s arguments can be NaN', testSerializeArg, Number.NaN, $);42+test('$\'s arguments can be Infinity', testSerializeArg, Number.POSITIVE_INFINITY, $);43+test('$\'s arguments can be null', testSerializeArg, null, $);44+test('$\'s arguments can be undefined', testSerializeArg, undefined, $);45+test('$\'s arguments can be bigints', testSerializeArg, 1n, $);46+test('$\'s arguments can be symbols', testSerializeArg, Symbol('test'), $);47+test('$.sync\'s arguments can be numbers', testSerializeArg, 1, $.sync);48+test('$.sync\'s arguments can be booleans', testSerializeArg, true, $.sync);49+test('$.sync\'s arguments can be NaN', testSerializeArg, Number.NaN, $.sync);50+test('$.sync\'s arguments can be Infinity', testSerializeArg, Number.POSITIVE_INFINITY, $.sync);51+test('$.sync\'s arguments can be null', testSerializeArg, null, $.sync);52+test('$.sync\'s arguments can be undefined', testSerializeArg, undefined, $.sync);53+test('$.sync\'s arguments can be bigints', testSerializeArg, 1n, $.sync);54+test('$.sync\'s arguments can be symbols', testSerializeArg, Symbol('test'), $.sync);55+56+const testInvalidOptions = async (t, execaMethod) => {57+ t.throws(() => {58+ execaMethod('echo', [], new Map());59+ }, {message: /Last argument must be an options object/});60+};61+62+test('execa()\'s third argument must be a plain object', testInvalidOptions, execa);63+test('execaSync()\'s third argument must be a plain object', testInvalidOptions, execaSync);64+test('execaCommand()\'s third argument must be a plain object', testInvalidOptions, execaCommand);65+test('execaCommandSync()\'s third argument must be a plain object', testInvalidOptions, execaCommandSync);66+test('execaNode()\'s third argument must be a plain object', testInvalidOptions, execaNode);67+test('$\'s third argument must be a plain object', testInvalidOptions, $);68+test('$.sync\'s third argument must be a plain object', testInvalidOptions, $.sync);added:test/methods/promise.js+53 added
1+import test from 'ava';2+import {execa} from '../../index.js';3+import {setFixtureDir} from '../helpers/fixtures-dir.js';4+5+setFixtureDir();6+7+test('promise methods are not enumerable', t => {8+ const descriptors = Object.getOwnPropertyDescriptors(execa('noop.js'));9+ t.false(descriptors.then.enumerable);10+ t.false(descriptors.catch.enumerable);11+ t.false(descriptors.finally.enumerable);12+});13+14+test('finally function is executed on success', async t => {15+ let isCalled = false;16+ const {stdout} = await execa('noop.js', ['foo']).finally(() => {17+ isCalled = true;18+ });19+ t.is(isCalled, true);20+ t.is(stdout, 'foo');21+});22+23+test('finally function is executed on failure', async t => {24+ let isError = false;25+ const {stdout, stderr} = await t.throwsAsync(execa('exit.js', ['2']).finally(() => {26+ isError = true;27+ }));28+ t.is(isError, true);29+ t.is(typeof stdout, 'string');30+ t.is(typeof stderr, 'string');31+});32+33+test('throw in finally function bubbles up on success', async t => {34+ const {message} = await t.throwsAsync(execa('noop.js', ['foo']).finally(() => {35+ throw new Error('called');36+ }));37+ t.is(message, 'called');38+});39+40+test('throw in finally bubbles up on error', async t => {41+ const {message} = await t.throwsAsync(execa('exit.js', ['2']).finally(() => {42+ throw new Error('called');43+ }));44+ t.is(message, 'called');45+});46+47+const testNoAwait = async (t, fixtureName, options, message) => {48+ const {stdout} = await execa('no-await.js', [JSON.stringify(options), fixtureName]);49+ t.true(stdout.includes(message));50+};51+52+test('Throws if promise is not awaited and subprocess fails', testNoAwait, 'fail.js', {}, 'exit code 2');53+test('Throws if promise is not awaited and subprocess times out', testNoAwait, 'forever.js', {timeout: 1}, 'timed out');added:test/methods/script.js+59 added
1+import test from 'ava';2+import {isStream} from 'is-stream';3+import {$} from '../../index.js';4+import {setFixtureDir} from '../helpers/fixtures-dir.js';5+import {foobarString} from '../helpers/input.js';6+7+setFixtureDir();8+9+const testScriptStdoutSync = (t, getSubprocess, expectedStdout) => {10+ const {stdout} = getSubprocess();11+ t.is(stdout, expectedStdout);12+};13+14+test('$.sync`...`', testScriptStdoutSync, () => $.sync`echo.js foo bar`, 'foo\nbar');15+test('$.s`...`', testScriptStdoutSync, () => $.s`echo.js foo bar`, 'foo\nbar');16+test('$(options).sync`...`', testScriptStdoutSync, () => $({stripFinalNewline: false}).sync`echo.js ${foobarString}`, `${foobarString}\n`);17+test('$.sync(options)`...`', testScriptStdoutSync, () => $.sync({stripFinalNewline: false})`echo.js ${foobarString}`, `${foobarString}\n`);18+19+test('Cannot call $.sync.sync', t => {20+ t.false('sync' in $.sync);21+});22+23+test('Cannot call $.sync(options).sync', t => {24+ t.false('sync' in $.sync({}));25+});26+27+test('$(options)() stdin defaults to "inherit"', async t => {28+ const {stdout} = await $({input: foobarString})('stdin-script.js');29+ t.is(stdout, foobarString);30+});31+32+test('$.sync(options)() stdin defaults to "inherit"', t => {33+ const {stdout} = $.sync({input: foobarString})('stdin-script.js');34+ t.is(stdout, foobarString);35+});36+37+test('$(options).sync() stdin defaults to "inherit"', t => {38+ const {stdout} = $({input: foobarString}).sync('stdin-script.js');39+ t.is(stdout, foobarString);40+});41+42+test('$(options)`...` stdin defaults to "inherit"', async t => {43+ const {stdout} = await $({input: foobarString})`stdin-script.js`;44+ t.is(stdout, foobarString);45+});46+47+test('$.sync(options)`...` stdin defaults to "inherit"', t => {48+ const {stdout} = $.sync({input: foobarString})`stdin-script.js`;49+ t.is(stdout, foobarString);50+});51+52+test('$(options).sync`...` stdin defaults to "inherit"', t => {53+ const {stdout} = $({input: foobarString}).sync`stdin-script.js`;54+ t.is(stdout, foobarString);55+});56+57+test('$ stdin has no default value when stdio is set', t => {58+ t.true(isStream($({stdio: 'pipe'})`noop.js`.stdin));59+});added:test/methods/template.js+329 added
1+import test from 'ava';2+import {$} from '../../index.js';3+import {setFixtureDir} from '../helpers/fixtures-dir.js';4+5+setFixtureDir();6+7+// Workaround since some text editors or IDEs do not allow inputting \r directly8+const escapedCall = string => {9+ const templates = [string];10+ templates.raw = [string];11+ return $(templates);12+};13+14+const testScriptStdout = async (t, getSubprocess, expectedStdout) => {15+ const {stdout} = await getSubprocess();16+ t.is(stdout, expectedStdout);17+};18+19+test('$ allows number interpolation', testScriptStdout, () => $`echo.js 1 ${2}`, '1\n2');20+test('$ can concatenate multiple tokens', testScriptStdout, () => $`echo.js ${'foo'}bar${'foo'}`, 'foobarfoo');21+test('$ can use newlines and tab indentations', testScriptStdout, () => $`echo.js foo22+ bar`, 'foo\nbar');23+test('$ can use newlines and space indentations', testScriptStdout, () => $`echo.js foo24+ bar`, 'foo\nbar');25+test('$ can use Windows newlines and tab indentations', testScriptStdout, () => escapedCall('echo.js foo\r\n\tbar'), 'foo\nbar');26+test('$ can use Windows newlines and space indentations', testScriptStdout, () => escapedCall('echo.js foo\r\n bar'), 'foo\nbar');27+test('$ does not ignore comments in expressions', testScriptStdout, () => $`echo.js foo28+ ${/* This is a comment */''}29+ bar30+ ${/* This is another comment */''}31+ baz32+`, 'foo\n\nbar\n\nbaz');33+test('$ allows escaping spaces with interpolation', testScriptStdout, () => $`echo.js ${'foo bar'}`, 'foo bar');34+test('$ allows escaping spaces in commands with interpolation', testScriptStdout, () => $`${'command with space.js'} foo bar`, 'foo\nbar');35+test('$ trims', testScriptStdout, () => $` echo.js foo bar `, 'foo\nbar');36+test('$ allows array interpolation', testScriptStdout, () => $`echo.js ${['foo', 'bar']}`, 'foo\nbar');37+test('$ allows empty array interpolation', testScriptStdout, () => $`echo.js foo ${[]} bar`, 'foo\nbar');38+test('$ allows space escaped values in array interpolation', testScriptStdout, () => $`echo.js ${['foo', 'bar baz']}`, 'foo\nbar baz');39+test('$ can concatenate at the end of tokens followed by an array', testScriptStdout, () => $`echo.js foo${['bar', 'foo']}`, 'foobar\nfoo');40+test('$ can concatenate at the start of tokens followed by an array', testScriptStdout, () => $`echo.js ${['foo', 'bar']}foo`, 'foo\nbarfoo');41+test('$ can concatenate at the start and end of tokens followed by an array', testScriptStdout, () => $`echo.js foo${['bar', 'foo']}bar`, 'foobar\nfoobar');42+test('$ handles escaped newlines', testScriptStdout, () => $`echo.js a\43+b`, 'ab');44+test('$ handles backslashes at end of lines', testScriptStdout, () => $`echo.js a\\45+ b`, 'a\\\nb');46+test('$ handles double backslashes at end of lines', testScriptStdout, () => $`echo.js a\\\\47+ b`, 'a\\\\\nb');48+test('$ handles tokens - a', testScriptStdout, () => $`echo.js a`, 'a');49+test('$ handles expressions - a', testScriptStdout, () => $`echo.js ${'a'}`, 'a');50+test('$ handles tokens - abc', testScriptStdout, () => $`echo.js abc`, 'abc');51+test('$ handles expressions - abc', testScriptStdout, () => $`echo.js ${'abc'}`, 'abc');52+test('$ handles tokens - ""', testScriptStdout, () => $`echo.js`, '');53+test('$ handles expressions - ""', testScriptStdout, () => $`echo.js a ${''} b`, 'a\n\nb');54+test('$ splits tokens - ""', testScriptStdout, () => $`echo.js ab`, 'ab');55+test('$ splits expressions - ""', testScriptStdout, () => $`echo.js ${'a'}${'b'}`, 'ab');56+test('$ concatenates expressions - ""', testScriptStdout, () => $`echo.js a${'b'}c`, 'abc');57+test('$ handles tokens - " "', testScriptStdout, () => $`echo.js `, '');58+test('$ handles expressions - " "', testScriptStdout, () => $`echo.js ${' '}`, ' ');59+test('$ splits tokens - " "', testScriptStdout, () => $`echo.js a b`, 'a\nb');60+test('$ splits expressions - " "', testScriptStdout, () => $`echo.js ${'a'} ${'b'}`, 'a\nb');61+test('$ concatenates tokens - " "', testScriptStdout, () => $`echo.js a `, 'a');62+test('$ concatenates expressions - " "', testScriptStdout, () => $`echo.js ${'a'} `, 'a');63+test('$ handles tokens - " " (2 spaces)', testScriptStdout, () => $`echo.js `, '');64+test('$ handles expressions - " " (2 spaces)', testScriptStdout, () => $`echo.js ${' '}`, ' ');65+test('$ splits tokens - " " (2 spaces)', testScriptStdout, () => $`echo.js a b`, 'a\nb');66+test('$ splits expressions - " " (2 spaces)', testScriptStdout, () => $`echo.js ${'a'} ${'b'}`, 'a\nb');67+test('$ concatenates tokens - " " (2 spaces)', testScriptStdout, () => $`echo.js a `, 'a');68+test('$ concatenates expressions - " " (2 spaces)', testScriptStdout, () => $`echo.js ${'a'} `, 'a');69+test('$ handles tokens - " " (3 spaces)', testScriptStdout, () => $`echo.js `, '');70+test('$ handles expressions - " " (3 spaces)', testScriptStdout, () => $`echo.js ${' '}`, ' ');71+test('$ splits tokens - " " (3 spaces)', testScriptStdout, () => $`echo.js a b`, 'a\nb');72+test('$ splits expressions - " " (3 spaces)', testScriptStdout, () => $`echo.js ${'a'} ${'b'}`, 'a\nb');73+test('$ concatenates tokens - " " (3 spaces)', testScriptStdout, () => $`echo.js a `, 'a');74+test('$ concatenates expressions - " " (3 spaces)', testScriptStdout, () => $`echo.js ${'a'} `, 'a');75+test('$ handles tokens - \\t (no escape)', testScriptStdout, () => $`echo.js `, '');76+test('$ handles expressions - \\t (no escape)', testScriptStdout, () => $`echo.js ${' '}`, '\t');77+test('$ splits tokens - \\t (no escape)', testScriptStdout, () => $`echo.js a b`, 'a\nb');78+test('$ splits expressions - \\t (no escape)', testScriptStdout, () => $`echo.js ${'a'} ${'b'}`, 'a\nb');79+test('$ concatenates tokens - \\t (no escape)', testScriptStdout, () => $`echo.js a b`, 'a\nb');80+test('$ concatenates expressions - \\t (no escape)', testScriptStdout, () => $`echo.js ${'a'} b`, 'a\nb');81+test('$ handles tokens - \\t (escape)', testScriptStdout, () => $`echo.js \t`, '\t');82+test('$ handles expressions - \\t (escape)', testScriptStdout, () => $`echo.js ${'\t'}`, '\t');83+test('$ splits tokens - \\t (escape)', testScriptStdout, () => $`echo.js a\tb`, 'a\tb');84+test('$ splits expressions - \\t (escape)', testScriptStdout, () => $`echo.js ${'a'}\t${'b'}`, 'a\tb');85+test('$ concatenates tokens - \\t (escape)', testScriptStdout, () => $`echo.js \ta\t b`, '\ta\t\nb');86+test('$ concatenates expressions - \\t (escape)', testScriptStdout, () => $`echo.js \t${'a'}\t b`, '\ta\t\nb');87+test('$ handles tokens - \\n (no escape)', testScriptStdout, () => $`echo.js88+ `, '');89+test('$ handles expressions - \\n (no escape)', testScriptStdout, () => $`echo.js ${`90+`} `, '\n');91+test('$ splits tokens - \\n (no escape)', testScriptStdout, () => $`echo.js a92+ b`, 'a\nb');93+test('$ splits expressions - \\n (no escape)', testScriptStdout, () => $`echo.js ${'a'}94+ ${'b'}`, 'a\nb');95+test('$ concatenates tokens - \\n (no escape)', testScriptStdout, () => $`echo.js96+a97+ b`, 'a\nb');98+test('$ concatenates expressions - \\n (no escape)', testScriptStdout, () => $`echo.js99+${'a'}100+ b`, 'a\nb');101+test('$ handles tokens - \\n (escape)', testScriptStdout, () => $`echo.js \n `, '\n');102+test('$ handles expressions - \\n (escape)', testScriptStdout, () => $`echo.js ${'\n'} `, '\n');103+test('$ splits tokens - \\n (escape)', testScriptStdout, () => $`echo.js a\n b`, 'a\n\nb');104+test('$ splits expressions - \\n (escape)', testScriptStdout, () => $`echo.js ${'a'}\n ${'b'}`, 'a\n\nb');105+test('$ concatenates tokens - \\n (escape)', testScriptStdout, () => $`echo.js \na\n b`, '\na\n\nb');106+test('$ concatenates expressions - \\n (escape)', testScriptStdout, () => $`echo.js \n${'a'}\n b`, '\na\n\nb');107+test('$ handles tokens - \\r (no escape)', testScriptStdout, () => escapedCall('echo.js \r '), '');108+test('$ splits tokens - \\r (no escape)', testScriptStdout, () => escapedCall('echo.js a\rb'), 'a\nb');109+test('$ splits expressions - \\r (no escape)', testScriptStdout, () => escapedCall(`echo.js ${'a'}\r${'b'}`), 'a\nb');110+test('$ concatenates tokens - \\r (no escape)', testScriptStdout, () => escapedCall('echo.js \ra\r b'), 'a\nb');111+test('$ concatenates expressions - \\r (no escape)', testScriptStdout, () => escapedCall(`echo.js \r${'a'}\r b`), 'a\nb');112+test('$ splits tokens - \\r (escape)', testScriptStdout, () => $`echo.js a\r b`, 'a\r\nb');113+test('$ splits expressions - \\r (escape)', testScriptStdout, () => $`echo.js ${'a'}\r ${'b'}`, 'a\r\nb');114+test('$ concatenates tokens - \\r (escape)', testScriptStdout, () => $`echo.js \ra\r b`, '\ra\r\nb');115+test('$ concatenates expressions - \\r (escape)', testScriptStdout, () => $`echo.js \r${'a'}\r b`, '\ra\r\nb');116+test('$ handles tokens - \\r\\n (no escape)', testScriptStdout, () => escapedCall('echo.js \r\n '), '');117+test('$ splits tokens - \\r\\n (no escape)', testScriptStdout, () => escapedCall('echo.js a\r\nb'), 'a\nb');118+test('$ splits expressions - \\r\\n (no escape)', testScriptStdout, () => escapedCall(`echo.js ${'a'}\r\n${'b'}`), 'a\nb');119+test('$ concatenates tokens - \\r\\n (no escape)', testScriptStdout, () => escapedCall('echo.js \r\na\r\n b'), 'a\nb');120+test('$ concatenates expressions - \\r\\n (no escape)', testScriptStdout, () => escapedCall(`echo.js \r\n${'a'}\r\n b`), 'a\nb');121+test('$ handles tokens - \\r\\n (escape)', testScriptStdout, () => $`echo.js \r\n `, '\r\n');122+test('$ handles expressions - \\r\\n (escape)', testScriptStdout, () => $`echo.js ${'\r\n'} `, '\r\n');123+test('$ splits tokens - \\r\\n (escape)', testScriptStdout, () => $`echo.js a\r\n b`, 'a\r\n\nb');124+test('$ splits expressions - \\r\\n (escape)', testScriptStdout, () => $`echo.js ${'a'}\r\n ${'b'}`, 'a\r\n\nb');125+test('$ concatenates tokens - \\r\\n (escape)', testScriptStdout, () => $`echo.js \r\na\r\n b`, '\r\na\r\n\nb');126+test('$ concatenates expressions - \\r\\n (escape)', testScriptStdout, () => $`echo.js \r\n${'a'}\r\n b`, '\r\na\r\n\nb');127+/* eslint-disable no-irregular-whitespace */128+test('$ handles expressions - \\f (no escape)', testScriptStdout, () => $`echo.js ${''}`, '\f');129+test('$ splits tokens - \\f (no escape)', testScriptStdout, () => $`echo.js ab`, 'a\fb');130+test('$ splits expressions - \\f (no escape)', testScriptStdout, () => $`echo.js ${'a'}${'b'}`, 'a\fb');131+test('$ concatenates tokens - \\f (no escape)', testScriptStdout, () => $`echo.js a b`, '\fa\f\nb');132+test('$ concatenates expressions - \\f (no escape)', testScriptStdout, () => $`echo.js ${'a'} b`, '\fa\f\nb');133+/* eslint-enable no-irregular-whitespace */134+test('$ handles tokens - \\f (escape)', testScriptStdout, () => $`echo.js \f`, '\f');135+test('$ handles expressions - \\f (escape)', testScriptStdout, () => $`echo.js ${'\f'}`, '\f');136+test('$ splits tokens - \\f (escape)', testScriptStdout, () => $`echo.js a\fb`, 'a\fb');137+test('$ splits expressions - \\f (escape)', testScriptStdout, () => $`echo.js ${'a'}\f${'b'}`, 'a\fb');138+test('$ concatenates tokens - \\f (escape)', testScriptStdout, () => $`echo.js \fa\f b`, '\fa\f\nb');139+test('$ concatenates expressions - \\f (escape)', testScriptStdout, () => $`echo.js \f${'a'}\f b`, '\fa\f\nb');140+test('$ handles tokens - \\', testScriptStdout, () => $`echo.js \\`, '\\');141+test('$ handles expressions - \\', testScriptStdout, () => $`echo.js ${'\\'}`, '\\');142+test('$ splits tokens - \\', testScriptStdout, () => $`echo.js a\\b`, 'a\\b');143+test('$ splits expressions - \\', testScriptStdout, () => $`echo.js ${'a'}\\${'b'}`, 'a\\b');144+test('$ concatenates tokens - \\', testScriptStdout, () => $`echo.js \\a\\ b`, '\\a\\\nb');145+test('$ concatenates expressions - \\', testScriptStdout, () => $`echo.js \\${'a'}\\ b`, '\\a\\\nb');146+test('$ handles tokens - \\\\', testScriptStdout, () => $`echo.js \\\\`, '\\\\');147+test('$ handles expressions - \\\\', testScriptStdout, () => $`echo.js ${'\\\\'}`, '\\\\');148+test('$ splits tokens - \\\\', testScriptStdout, () => $`echo.js a\\\\b`, 'a\\\\b');149+test('$ splits expressions - \\\\', testScriptStdout, () => $`echo.js ${'a'}\\\\${'b'}`, 'a\\\\b');150+test('$ concatenates tokens - \\\\', testScriptStdout, () => $`echo.js \\\\a\\\\ b`, '\\\\a\\\\\nb');151+test('$ concatenates expressions - \\\\', testScriptStdout, () => $`echo.js \\\\${'a'}\\\\ b`, '\\\\a\\\\\nb');152+test('$ handles tokens - `', testScriptStdout, () => $`echo.js \``, '`');153+test('$ handles expressions - `', testScriptStdout, () => $`echo.js ${'`'}`, '`');154+test('$ splits tokens - `', testScriptStdout, () => $`echo.js a\`b`, 'a`b');155+test('$ splits expressions - `', testScriptStdout, () => $`echo.js ${'a'}\`${'b'}`, 'a`b');156+test('$ concatenates tokens - `', testScriptStdout, () => $`echo.js \`a\` b`, '`a`\nb');157+test('$ concatenates expressions - `', testScriptStdout, () => $`echo.js \`${'a'}\` b`, '`a`\nb');158+test('$ handles tokens - \\v', testScriptStdout, () => $`echo.js \v`, '\v');159+test('$ handles expressions - \\v', testScriptStdout, () => $`echo.js ${'\v'}`, '\v');160+test('$ splits tokens - \\v', testScriptStdout, () => $`echo.js a\vb`, 'a\vb');161+test('$ splits expressions - \\v', testScriptStdout, () => $`echo.js ${'a'}\v${'b'}`, 'a\vb');162+test('$ concatenates tokens - \\v', testScriptStdout, () => $`echo.js \va\v b`, '\va\v\nb');163+test('$ concatenates expressions - \\v', testScriptStdout, () => $`echo.js \v${'a'}\v b`, '\va\v\nb');164+test('$ handles tokens - \\u2028', testScriptStdout, () => $`echo.js \u2028`, '\u2028');165+test('$ handles expressions - \\u2028', testScriptStdout, () => $`echo.js ${'\u2028'}`, '\u2028');166+test('$ splits tokens - \\u2028', testScriptStdout, () => $`echo.js a\u2028b`, 'a\u2028b');167+test('$ splits expressions - \\u2028', testScriptStdout, () => $`echo.js ${'a'}\u2028${'b'}`, 'a\u2028b');168+test('$ concatenates tokens - \\u2028', testScriptStdout, () => $`echo.js \u2028a\u2028 b`, '\u2028a\u2028\nb');169+test('$ concatenates expressions - \\u2028', testScriptStdout, () => $`echo.js \u2028${'a'}\u2028 b`, '\u2028a\u2028\nb');170+test('$ handles tokens - \\a', testScriptStdout, () => $`echo.js \a`, 'a');171+test('$ splits tokens - \\a', testScriptStdout, () => $`echo.js a\ab`, 'aab');172+test('$ splits expressions - \\a', testScriptStdout, () => $`echo.js ${'a'}\a${'b'}`, 'aab');173+test('$ concatenates tokens - \\a', testScriptStdout, () => $`echo.js \aa\a b`, 'aaa\nb');174+test('$ concatenates expressions - \\a', testScriptStdout, () => $`echo.js \a${'a'}\a b`, 'aaa\nb');175+test('$ handles tokens - \\cJ', testScriptStdout, () => $`echo.js \cJ`, 'cJ');176+test('$ splits tokens - \\cJ', testScriptStdout, () => $`echo.js a\cJb`, 'acJb');177+test('$ splits expressions - \\cJ', testScriptStdout, () => $`echo.js ${'a'}\cJ${'b'}`, 'acJb');178+test('$ concatenates tokens - \\cJ', testScriptStdout, () => $`echo.js \cJa\cJ b`, 'cJacJ\nb');179+test('$ concatenates expressions - \\cJ', testScriptStdout, () => $`echo.js \cJ${'a'}\cJ b`, 'cJacJ\nb');180+test('$ handles tokens - \\.', testScriptStdout, () => $`echo.js \.`, '.');181+test('$ splits tokens - \\.', testScriptStdout, () => $`echo.js a\.b`, 'a.b');182+test('$ splits expressions - \\.', testScriptStdout, () => $`echo.js ${'a'}\.${'b'}`, 'a.b');183+test('$ concatenates tokens - \\.', testScriptStdout, () => $`echo.js \.a\. b`, '.a.\nb');184+test('$ concatenates expressions - \\.', testScriptStdout, () => $`echo.js \.${'a'}\. b`, '.a.\nb');185+/* eslint-disable unicorn/no-hex-escape */186+test('$ handles tokens - \\x63', testScriptStdout, () => $`echo.js \x63`, 'c');187+test('$ splits tokens - \\x63', testScriptStdout, () => $`echo.js a\x63b`, 'acb');188+test('$ splits expressions - \\x63', testScriptStdout, () => $`echo.js ${'a'}\x63${'b'}`, 'acb');189+test('$ concatenates tokens - \\x63', testScriptStdout, () => $`echo.js \x63a\x63 b`, 'cac\nb');190+test('$ concatenates expressions - \\x63', testScriptStdout, () => $`echo.js \x63${'a'}\x63 b`, 'cac\nb');191+/* eslint-enable unicorn/no-hex-escape */192+test('$ handles tokens - \\u0063', testScriptStdout, () => $`echo.js \u0063`, 'c');193+test('$ splits tokens - \\u0063', testScriptStdout, () => $`echo.js a\u0063b`, 'acb');194+test('$ splits expressions - \\u0063', testScriptStdout, () => $`echo.js ${'a'}\u0063${'b'}`, 'acb');195+test('$ concatenates tokens - \\u0063', testScriptStdout, () => $`echo.js \u0063a\u0063 b`, 'cac\nb');196+test('$ concatenates expressions - \\u0063', testScriptStdout, () => $`echo.js \u0063${'a'}\u0063 b`, 'cac\nb');197+test('$ handles tokens - \\u{1}', testScriptStdout, () => $`echo.js \u{1}`, '\u0001');198+test('$ splits tokens - \\u{1}', testScriptStdout, () => $`echo.js a\u{1}b`, 'a\u0001b');199+test('$ splits expressions - \\u{1}', testScriptStdout, () => $`echo.js ${'a'}\u{1}${'b'}`, 'a\u0001b');200+test('$ concatenates tokens - \\u{1}', testScriptStdout, () => $`echo.js \u{1}a\u{1} b`, '\u0001a\u0001\nb');201+test('$ concatenates expressions - \\u{1}', testScriptStdout, () => $`echo.js \u{1}${'a'}\u{1} b`, '\u0001a\u0001\nb');202+test('$ handles tokens - \\u{63}', testScriptStdout, () => $`echo.js \u{63}`, 'c');203+test('$ splits tokens - \\u{63}', testScriptStdout, () => $`echo.js a\u{63}b`, 'acb');204+test('$ splits expressions - \\u{63}', testScriptStdout, () => $`echo.js ${'a'}\u{63}${'b'}`, 'acb');205+test('$ concatenates tokens - \\u{63}', testScriptStdout, () => $`echo.js \u{63}a\u{63} b`, 'cac\nb');206+test('$ concatenates expressions - \\u{63}', testScriptStdout, () => $`echo.js \u{63}${'a'}\u{63} b`, 'cac\nb');207+test('$ handles tokens - \\u{063}', testScriptStdout, () => $`echo.js \u{063}`, 'c');208+test('$ splits tokens - \\u{063}', testScriptStdout, () => $`echo.js a\u{063}b`, 'acb');209+test('$ splits expressions - \\u{063}', testScriptStdout, () => $`echo.js ${'a'}\u{063}${'b'}`, 'acb');210+test('$ concatenates tokens - \\u{063}', testScriptStdout, () => $`echo.js \u{063}a\u{063} b`, 'cac\nb');211+test('$ concatenates expressions - \\u{063}', testScriptStdout, () => $`echo.js \u{063}${'a'}\u{063} b`, 'cac\nb');212+test('$ handles tokens - \\u{0063}', testScriptStdout, () => $`echo.js \u{0063}`, 'c');213+test('$ splits tokens - \\u{0063}', testScriptStdout, () => $`echo.js a\u{0063}b`, 'acb');214+test('$ splits expressions - \\u{0063}', testScriptStdout, () => $`echo.js ${'a'}\u{0063}${'b'}`, 'acb');215+test('$ concatenates tokens - \\u{0063}', testScriptStdout, () => $`echo.js \u{0063}a\u{0063} b`, 'cac\nb');216+test('$ concatenates expressions - \\u{0063}', testScriptStdout, () => $`echo.js \u{0063}${'a'}\u{0063} b`, 'cac\nb');217+test('$ handles tokens - \\u{00063}', testScriptStdout, () => $`echo.js \u{00063}`, 'c');218+test('$ splits tokens - \\u{00063}', testScriptStdout, () => $`echo.js a\u{00063}b`, 'acb');219+test('$ splits expressions - \\u{00063}', testScriptStdout, () => $`echo.js ${'a'}\u{00063}${'b'}`, 'acb');220+test('$ concatenates tokens - \\u{00063}', testScriptStdout, () => $`echo.js \u{00063}a\u{00063} b`, 'cac\nb');221+test('$ concatenates expressions - \\u{00063}', testScriptStdout, () => $`echo.js \u{00063}${'a'}\u{00063} b`, 'cac\nb');222+test('$ handles tokens - \\u{000063}', testScriptStdout, () => $`echo.js \u{000063}`, 'c');223+test('$ splits tokens - \\u{000063}', testScriptStdout, () => $`echo.js a\u{000063}b`, 'acb');224+test('$ splits expressions - \\u{000063}', testScriptStdout, () => $`echo.js ${'a'}\u{000063}${'b'}`, 'acb');225+test('$ concatenates tokens - \\u{000063}', testScriptStdout, () => $`echo.js \u{000063}a\u{000063} b`, 'cac\nb');226+test('$ concatenates expressions - \\u{000063}', testScriptStdout, () => $`echo.js \u{000063}${'a'}\u{000063} b`, 'cac\nb');227+test('$ handles tokens - \\u{0000063}', testScriptStdout, () => $`echo.js \u{0000063}`, 'c');228+test('$ splits tokens - \\u{0000063}', testScriptStdout, () => $`echo.js a\u{0000063}b`, 'acb');229+test('$ splits expressions - \\u{0000063}', testScriptStdout, () => $`echo.js ${'a'}\u{0000063}${'b'}`, 'acb');230+test('$ concatenates tokens - \\u{0000063}', testScriptStdout, () => $`echo.js \u{0000063}a\u{0000063} b`, 'cac\nb');231+test('$ concatenates expressions - \\u{0000063}', testScriptStdout, () => $`echo.js \u{0000063}${'a'}\u{0000063} b`, 'cac\nb');232+test('$ handles tokens - \\u{0063}}', testScriptStdout, () => $`echo.js \u{0063}}`, 'c}');233+test('$ splits tokens - \\u{0063}}', testScriptStdout, () => $`echo.js a\u{0063}}b`, 'ac}b');234+test('$ splits expressions - \\u{0063}}', testScriptStdout, () => $`echo.js ${'a'}\u{0063}}${'b'}`, 'ac}b');235+test('$ concatenates tokens - \\u{0063}}', testScriptStdout, () => $`echo.js \u{0063}}a\u{0063}} b`, 'c}ac}\nb');236+test('$ concatenates expressions - \\u{0063}}', testScriptStdout, () => $`echo.js \u{0063}}${'a'}\u{0063}} b`, 'c}ac}\nb');237+238+const testScriptErrorStdout = async (t, getSubprocess) => {239+ t.throws(getSubprocess, {message: /null bytes/});240+};241+242+test('$ handles tokens - \\0', testScriptErrorStdout, () => $`echo.js \0`);243+test('$ splits tokens - \\0', testScriptErrorStdout, () => $`echo.js a\0b`);244+test('$ splits expressions - \\0', testScriptErrorStdout, () => $`echo.js ${'a'}\0${'b'}`);245+test('$ concatenates tokens - \\0', testScriptErrorStdout, () => $`echo.js \0a\0 b`);246+test('$ concatenates expressions - \\0', testScriptErrorStdout, () => $`echo.js \0${'a'}\0 b`);247+248+const testReturnInterpolate = async (t, getSubprocess, expectedStdout, options = {}) => {249+ const foo = await $(options)`echo.js foo`;250+ const {stdout} = await getSubprocess(foo);251+ t.is(stdout, expectedStdout);252+};253+254+test('$ allows execa return value interpolation', testReturnInterpolate, foo => $`echo.js ${foo} bar`, 'foo\nbar');255+test('$ allows execa return value buffer interpolation', testReturnInterpolate, foo => $`echo.js ${foo} bar`, 'foo\nbar', {encoding: 'buffer'});256+test('$ allows execa return value array interpolation', testReturnInterpolate, foo => $`echo.js ${[foo, 'bar']}`, 'foo\nbar');257+test('$ allows execa return value buffer array interpolation', testReturnInterpolate, foo => $`echo.js ${[foo, 'bar']}`, 'foo\nbar', {encoding: 'buffer'});258+259+const testReturnInterpolateSync = (t, getSubprocess, expectedStdout, options = {}) => {260+ const foo = $(options).sync`echo.js foo`;261+ const {stdout} = getSubprocess(foo);262+ t.is(stdout, expectedStdout);263+};264+265+test('$.sync allows execa return value interpolation', testReturnInterpolateSync, foo => $.sync`echo.js ${foo} bar`, 'foo\nbar');266+test('$.sync allows execa return value buffer interpolation', testReturnInterpolateSync, foo => $.sync`echo.js ${foo} bar`, 'foo\nbar', {encoding: 'buffer'});267+test('$.sync allows execa return value array interpolation', testReturnInterpolateSync, foo => $.sync`echo.js ${[foo, 'bar']}`, 'foo\nbar');268+test('$.sync allows execa return value buffer array interpolation', testReturnInterpolateSync, foo => $.sync`echo.js ${[foo, 'bar']}`, 'foo\nbar', {encoding: 'buffer'});269+270+const testInvalidSequence = (t, getSubprocess) => {271+ t.throws(getSubprocess, {message: /Invalid backslash sequence/});272+};273+274+test('$ handles invalid escape sequence - \\1', testInvalidSequence, () => $`echo.js \1`);275+test('$ handles invalid escape sequence - \\u', testInvalidSequence, () => $`echo.js \u`);276+test('$ handles invalid escape sequence - \\u0', testInvalidSequence, () => $`echo.js \u0`);277+test('$ handles invalid escape sequence - \\u00', testInvalidSequence, () => $`echo.js \u00`);278+test('$ handles invalid escape sequence - \\u000', testInvalidSequence, () => $`echo.js \u000`);279+test('$ handles invalid escape sequence - \\ug', testInvalidSequence, () => $`echo.js \ug`);280+test('$ handles invalid escape sequence - \\u{', testInvalidSequence, () => $`echo.js \u{`);281+test('$ handles invalid escape sequence - \\u{0000', testInvalidSequence, () => $`echo.js \u{0000`);282+test('$ handles invalid escape sequence - \\u{g}', testInvalidSequence, () => $`echo.js \u{g}`);283+/* eslint-disable unicorn/no-hex-escape */284+test('$ handles invalid escape sequence - \\x', testInvalidSequence, () => $`echo.js \x`);285+test('$ handles invalid escape sequence - \\x0', testInvalidSequence, () => $`echo.js \x0`);286+test('$ handles invalid escape sequence - \\xgg', testInvalidSequence, () => $`echo.js \xgg`);287+/* eslint-enable unicorn/no-hex-escape */288+289+const testEmptyScript = (t, getSubprocess) => {290+ t.throws(getSubprocess, {message: /Template script must not be empty/});291+};292+293+test('$``', testEmptyScript, () => $``);294+test('$` `', testEmptyScript, () => $` `);295+test('$` ` (2 spaces)', testEmptyScript, () => $` `);296+test('$`\\t`', testEmptyScript, () => $` `);297+test('$`\\n`', testEmptyScript, () => $`298+`);299+300+const testInvalidExpression = (t, invalidExpression, execaMethod) => {301+ const expression = typeof invalidExpression === 'function' ? invalidExpression() : invalidExpression;302+ t.throws(303+ () => execaMethod`echo.js ${expression}`,304+ {message: /in template expression/},305+ );306+};307+308+test('$ throws on invalid expression - undefined', testInvalidExpression, undefined, $);309+test('$ throws on invalid expression - null', testInvalidExpression, null, $);310+test('$ throws on invalid expression - true', testInvalidExpression, true, $);311+test('$ throws on invalid expression - {}', testInvalidExpression, {}, $);312+test('$ throws on invalid expression - {foo: "bar"}', testInvalidExpression, {foo: 'bar'}, $);313+test('$ throws on invalid expression - {stdout: undefined}', testInvalidExpression, {stdout: undefined}, $);314+test('$ throws on invalid expression - {stdout: 1}', testInvalidExpression, {stdout: 1}, $);315+test('$ throws on invalid expression - Promise.resolve()', testInvalidExpression, Promise.resolve(), $);316+test('$ throws on invalid expression - Promise.resolve({stdout: "foo"})', testInvalidExpression, Promise.resolve({foo: 'bar'}), $);317+test('$ throws on invalid expression - $', testInvalidExpression, () => $`noop.js`, $);318+test('$ throws on invalid expression - $(options).sync', testInvalidExpression, () => $({stdio: 'ignore'}).sync`noop.js`, $);319+test('$ throws on invalid expression - [undefined]', testInvalidExpression, [undefined], $);320+test('$ throws on invalid expression - [null]', testInvalidExpression, [null], $);321+test('$ throws on invalid expression - [true]', testInvalidExpression, [true], $);322+test('$ throws on invalid expression - [{}]', testInvalidExpression, [{}], $);323+test('$ throws on invalid expression - [{foo: "bar"}]', testInvalidExpression, [{foo: 'bar'}], $);324+test('$ throws on invalid expression - [{stdout: undefined}]', testInvalidExpression, [{stdout: undefined}], $);325+test('$ throws on invalid expression - [{stdout: 1}]', testInvalidExpression, [{stdout: 1}], $);326+test('$ throws on invalid expression - [Promise.resolve()]', testInvalidExpression, [Promise.resolve()], $);327+test('$ throws on invalid expression - [Promise.resolve({stdout: "foo"})]', testInvalidExpression, [Promise.resolve({stdout: 'foo'})], $);328+test('$ throws on invalid expression - [$]', testInvalidExpression, () => [$`noop.js`], $);329+test('$ throws on invalid expression - [$(options).sync]', testInvalidExpression, () => [$({stdio: 'ignore'}).sync`noop.js`], $);added:test/pipe/pipe-arguments.js+272 added
1+import {spawn} from 'node:child_process';2+import {pathToFileURL} from 'node:url';3+import test from 'ava';4+import {$, execa} from '../../index.js';5+import {setFixtureDir, FIXTURES_DIR} from '../helpers/fixtures-dir.js';6+import {foobarString} from '../helpers/input.js';7+8+setFixtureDir();9+10+test('$.pipe(subprocess)', async t => {11+ const {stdout} = await $`noop.js ${foobarString}`.pipe($({stdin: 'pipe'})`stdin.js`);12+ t.is(stdout, foobarString);13+});14+15+test('execa.$.pipe(subprocess)', async t => {16+ const {stdout} = await execa('noop.js', [foobarString]).pipe($({stdin: 'pipe'})`stdin.js`);17+ t.is(stdout, foobarString);18+});19+20+test('$.pipe.pipe(subprocess)', async t => {21+ const {stdout} = await $`noop.js ${foobarString}`22+ .pipe($({stdin: 'pipe'})`stdin.js`)23+ .pipe($({stdin: 'pipe'})`stdin.js`);24+ t.is(stdout, foobarString);25+});26+27+test('$.pipe`command`', async t => {28+ const {stdout} = await $`noop.js ${foobarString}`.pipe`stdin.js`;29+ t.is(stdout, foobarString);30+});31+32+test('execa.$.pipe`command`', async t => {33+ const {stdout} = await execa('noop.js', [foobarString]).pipe`stdin.js`;34+ t.is(stdout, foobarString);35+});36+37+test('$.pipe.pipe`command`', async t => {38+ const {stdout} = await $`noop.js ${foobarString}`39+ .pipe`stdin.js`40+ .pipe`stdin.js`;41+ t.is(stdout, foobarString);42+});43+44+test('$.pipe("file")', async t => {45+ const {stdout} = await $`noop.js ${foobarString}`.pipe('stdin.js');46+ t.is(stdout, foobarString);47+});48+49+test('execa.$.pipe("file")`', async t => {50+ const {stdout} = await execa('noop.js', [foobarString]).pipe('stdin.js');51+ t.is(stdout, foobarString);52+});53+54+test('$.pipe.pipe("file")', async t => {55+ const {stdout} = await $`noop.js ${foobarString}`56+ .pipe`stdin.js`57+ .pipe('stdin.js');58+ t.is(stdout, foobarString);59+});60+61+test('execa.$.pipe(fileUrl)`', async t => {62+ const {stdout} = await execa('noop.js', [foobarString]).pipe(pathToFileURL(`${FIXTURES_DIR}/stdin.js`));63+ t.is(stdout, foobarString);64+});65+66+test('$.pipe("file", args, options)', async t => {67+ const {stdout} = await $`noop.js ${foobarString}`.pipe('node', ['stdin.js'], {cwd: FIXTURES_DIR});68+ t.is(stdout, foobarString);69+});70+71+test('execa.$.pipe("file", args, options)`', async t => {72+ const {stdout} = await execa('noop.js', [foobarString]).pipe('node', ['stdin.js'], {cwd: FIXTURES_DIR});73+ t.is(stdout, foobarString);74+});75+76+test('$.pipe.pipe("file", args, options)', async t => {77+ const {stdout} = await $`noop.js ${foobarString}`78+ .pipe`stdin.js`79+ .pipe('node', ['stdin.js'], {cwd: FIXTURES_DIR});80+ t.is(stdout, foobarString);81+});82+83+test('$.pipe(subprocess, pipeOptions)', async t => {84+ const {stdout} = await $`noop-fd.js 2 ${foobarString}`.pipe($({stdin: 'pipe'})`stdin.js`, {from: 'stderr'});85+ t.is(stdout, foobarString);86+});87+88+test('execa.$.pipe(subprocess, pipeOptions)', async t => {89+ const {stdout} = await execa('noop-fd.js', ['2', foobarString]).pipe($({stdin: 'pipe'})`stdin.js`, {from: 'stderr'});90+ t.is(stdout, foobarString);91+});92+93+test('$.pipe.pipe(subprocess, pipeOptions)', async t => {94+ const {stdout} = await $`noop-fd.js 2 ${foobarString}`95+ .pipe($({stdin: 'pipe'})`noop-stdin-fd.js 2`, {from: 'stderr'})96+ .pipe($({stdin: 'pipe'})`stdin.js`, {from: 'stderr'});97+ t.is(stdout, foobarString);98+});99+100+test('$.pipe(pipeOptions)`command`', async t => {101+ const {stdout} = await $`noop-fd.js 2 ${foobarString}`.pipe({from: 'stderr'})`stdin.js`;102+ t.is(stdout, foobarString);103+});104+105+test('execa.$.pipe(pipeOptions)`command`', async t => {106+ const {stdout} = await execa('noop-fd.js', ['2', foobarString]).pipe({from: 'stderr'})`stdin.js`;107+ t.is(stdout, foobarString);108+});109+110+test('$.pipe.pipe(pipeOptions)`command`', async t => {111+ const {stdout} = await $`noop-fd.js 2 ${foobarString}`112+ .pipe({from: 'stderr'})`noop-stdin-fd.js 2`113+ .pipe({from: 'stderr'})`stdin.js`;114+ t.is(stdout, foobarString);115+});116+117+test('$.pipe("file", pipeOptions)', async t => {118+ const {stdout} = await $`noop-fd.js 2 ${foobarString}`.pipe('stdin.js', {from: 'stderr'});119+ t.is(stdout, foobarString);120+});121+122+test('execa.$.pipe("file", pipeOptions)', async t => {123+ const {stdout} = await execa('noop-fd.js', ['2', foobarString]).pipe('stdin.js', {from: 'stderr'});124+ t.is(stdout, foobarString);125+});126+127+test('$.pipe.pipe("file", pipeOptions)', async t => {128+ const {stdout} = await $`noop-fd.js 2 ${foobarString}`129+ .pipe({from: 'stderr'})`noop-stdin-fd.js 2`130+ .pipe('stdin.js', {from: 'stderr'});131+ t.is(stdout, foobarString);132+});133+134+test('$.pipe(options)`command`', async t => {135+ const {stdout} = await $`noop.js ${foobarString}`.pipe({stripFinalNewline: false})`stdin.js`;136+ t.is(stdout, `${foobarString}\n`);137+});138+139+test('execa.$.pipe(options)`command`', async t => {140+ const {stdout} = await execa('noop.js', [foobarString]).pipe({stripFinalNewline: false})`stdin.js`;141+ t.is(stdout, `${foobarString}\n`);142+});143+144+test('$.pipe.pipe(options)`command`', async t => {145+ const {stdout} = await $`noop.js ${foobarString}`146+ .pipe({})`stdin.js`147+ .pipe({stripFinalNewline: false})`stdin.js`;148+ t.is(stdout, `${foobarString}\n`);149+});150+151+test('$.pipe("file", options)', async t => {152+ const {stdout} = await $`noop.js ${foobarString}`.pipe('stdin.js', {stripFinalNewline: false});153+ t.is(stdout, `${foobarString}\n`);154+});155+156+test('execa.$.pipe("file", options)', async t => {157+ const {stdout} = await execa('noop.js', [foobarString]).pipe('stdin.js', {stripFinalNewline: false});158+ t.is(stdout, `${foobarString}\n`);159+});160+161+test('$.pipe.pipe("file", options)', async t => {162+ const {stdout} = await $`noop.js ${foobarString}`163+ .pipe({})`stdin.js`164+ .pipe('stdin.js', {stripFinalNewline: false});165+ t.is(stdout, `${foobarString}\n`);166+});167+168+test('$.pipe(pipeAndSubprocessOptions)`command`', async t => {169+ const {stdout} = await $`noop-fd.js 2 ${foobarString}\n`.pipe({from: 'stderr', stripFinalNewline: false})`stdin.js`;170+ t.is(stdout, `${foobarString}\n`);171+});172+173+test('execa.$.pipe(pipeAndSubprocessOptions)`command`', async t => {174+ const {stdout} = await execa('noop-fd.js', ['2', `${foobarString}\n`]).pipe({from: 'stderr', stripFinalNewline: false})`stdin.js`;175+ t.is(stdout, `${foobarString}\n`);176+});177+178+test('$.pipe.pipe(pipeAndSubprocessOptions)`command`', async t => {179+ const {stdout} = await $`noop-fd.js 2 ${foobarString}\n`180+ .pipe({from: 'stderr'})`noop-stdin-fd.js 2`181+ .pipe({from: 'stderr', stripFinalNewline: false})`stdin.js`;182+ t.is(stdout, `${foobarString}\n`);183+});184+185+test('$.pipe("file", pipeAndSubprocessOptions)', async t => {186+ const {stdout} = await $`noop-fd.js 2 ${foobarString}\n`.pipe('stdin.js', {from: 'stderr', stripFinalNewline: false});187+ t.is(stdout, `${foobarString}\n`);188+});189+190+test('execa.$.pipe("file", pipeAndSubprocessOptions)', async t => {191+ const {stdout} = await execa('noop-fd.js', ['2', `${foobarString}\n`]).pipe('stdin.js', {from: 'stderr', stripFinalNewline: false});192+ t.is(stdout, `${foobarString}\n`);193+});194+195+test('$.pipe.pipe("file", pipeAndSubprocessOptions)', async t => {196+ const {stdout} = await $`noop-fd.js 2 ${foobarString}\n`197+ .pipe({from: 'stderr'})`noop-stdin-fd.js 2`198+ .pipe('stdin.js', {from: 'stderr', stripFinalNewline: false});199+ t.is(stdout, `${foobarString}\n`);200+});201+202+test('$.pipe(options)(secondOptions)`command`', async t => {203+ const {stdout} = await $`noop.js ${foobarString}`.pipe({stripFinalNewline: false})({stripFinalNewline: true})`stdin.js`;204+ t.is(stdout, foobarString);205+});206+207+test('execa.$.pipe(options)(secondOptions)`command`', async t => {208+ const {stdout} = await execa('noop.js', [foobarString]).pipe({stripFinalNewline: false})({stripFinalNewline: true})`stdin.js`;209+ t.is(stdout, foobarString);210+});211+212+test('$.pipe.pipe(options)(secondOptions)`command`', async t => {213+ const {stdout} = await $`noop.js ${foobarString}`214+ .pipe({})({})`stdin.js`215+ .pipe({stripFinalNewline: false})({stripFinalNewline: true})`stdin.js`;216+ t.is(stdout, foobarString);217+});218+219+test('$.pipe`command` forces "stdin: pipe"', async t => {220+ const {stdout} = await $`noop.js ${foobarString}`.pipe({stdin: 'ignore'})`stdin.js`;221+ t.is(stdout, foobarString);222+});223+224+test('execa.pipe("file") forces "stdin: "pipe"', async t => {225+ const {stdout} = await execa('noop.js', [foobarString]).pipe('stdin.js', {stdin: 'ignore'});226+ t.is(stdout, foobarString);227+});228+229+test('execa.pipe(subprocess) does not force "stdin: pipe"', async t => {230+ await t.throwsAsync(231+ execa('noop.js', [foobarString]).pipe(execa('stdin.js', {stdin: 'ignore'})),232+ {message: /"stdin: 'ignore'" option is incompatible/},233+ );234+});235+236+test('$.pipe(options)(subprocess) fails', async t => {237+ await t.throwsAsync(238+ $`empty.js`.pipe({stdout: 'pipe'})($`empty.js`),239+ {message: /Please use \.pipe/},240+ );241+});242+243+test('execa.$.pipe(options)(subprocess) fails', async t => {244+ await t.throwsAsync(245+ execa('empty.js').pipe({stdout: 'pipe'})($`empty.js`),246+ {message: /Please use \.pipe/},247+ );248+});249+250+test('$.pipe(options)("file") fails', async t => {251+ await t.throwsAsync(252+ $`empty.js`.pipe({stdout: 'pipe'})('empty.js'),253+ {message: /Please use \.pipe/},254+ );255+});256+257+test('execa.$.pipe(options)("file") fails', async t => {258+ await t.throwsAsync(259+ execa('empty.js').pipe({stdout: 'pipe'})('empty.js'),260+ {message: /Please use \.pipe/},261+ );262+});263+264+const testInvalidPipe = async (t, ...args) => {265+ await t.throwsAsync(266+ $`empty.js`.pipe(...args),267+ {message: /must be a template string/},268+ );269+};270+271+test('$.pipe(nonExecaSubprocess) fails', testInvalidPipe, spawn('node', ['--version']));272+test('$.pipe(false) fails', testInvalidPipe, false);deleted:test/pipe/validate.js-272 removed
1-import {spawn} from 'node:child_process';2-import {pathToFileURL} from 'node:url';3-import test from 'ava';4-import {$, execa} from '../../index.js';5-import {setFixtureDir, FIXTURES_DIR} from '../helpers/fixtures-dir.js';6-import {foobarString} from '../helpers/input.js';7-8-setFixtureDir();9-10-test('$.pipe(subprocess)', async t => {11- const {stdout} = await $`noop.js ${foobarString}`.pipe($({stdin: 'pipe'})`stdin.js`);12- t.is(stdout, foobarString);13-});14-15-test('execa.$.pipe(subprocess)', async t => {16- const {stdout} = await execa('noop.js', [foobarString]).pipe($({stdin: 'pipe'})`stdin.js`);17- t.is(stdout, foobarString);18-});19-20-test('$.pipe.pipe(subprocess)', async t => {21- const {stdout} = await $`noop.js ${foobarString}`22- .pipe($({stdin: 'pipe'})`stdin.js`)23- .pipe($({stdin: 'pipe'})`stdin.js`);24- t.is(stdout, foobarString);25-});26-27-test('$.pipe`command`', async t => {28- const {stdout} = await $`noop.js ${foobarString}`.pipe`stdin.js`;29- t.is(stdout, foobarString);30-});31-32-test('execa.$.pipe`command`', async t => {33- const {stdout} = await execa('noop.js', [foobarString]).pipe`stdin.js`;34- t.is(stdout, foobarString);35-});36-37-test('$.pipe.pipe`command`', async t => {38- const {stdout} = await $`noop.js ${foobarString}`39- .pipe`stdin.js`40- .pipe`stdin.js`;41- t.is(stdout, foobarString);42-});43-44-test('$.pipe("file")', async t => {45- const {stdout} = await $`noop.js ${foobarString}`.pipe('stdin.js');46- t.is(stdout, foobarString);47-});48-49-test('execa.$.pipe("file")`', async t => {50- const {stdout} = await execa('noop.js', [foobarString]).pipe('stdin.js');51- t.is(stdout, foobarString);52-});53-54-test('$.pipe.pipe("file")', async t => {55- const {stdout} = await $`noop.js ${foobarString}`56- .pipe`stdin.js`57- .pipe('stdin.js');58- t.is(stdout, foobarString);59-});60-61-test('execa.$.pipe(fileUrl)`', async t => {62- const {stdout} = await execa('noop.js', [foobarString]).pipe(pathToFileURL(`${FIXTURES_DIR}/stdin.js`));63- t.is(stdout, foobarString);64-});65-66-test('$.pipe("file", args, options)', async t => {67- const {stdout} = await $`noop.js ${foobarString}`.pipe('node', ['stdin.js'], {cwd: FIXTURES_DIR});68- t.is(stdout, foobarString);69-});70-71-test('execa.$.pipe("file", args, options)`', async t => {72- const {stdout} = await execa('noop.js', [foobarString]).pipe('node', ['stdin.js'], {cwd: FIXTURES_DIR});73- t.is(stdout, foobarString);74-});75-76-test('$.pipe.pipe("file", args, options)', async t => {77- const {stdout} = await $`noop.js ${foobarString}`78- .pipe`stdin.js`79- .pipe('node', ['stdin.js'], {cwd: FIXTURES_DIR});80- t.is(stdout, foobarString);81-});82-83-test('$.pipe(subprocess, pipeOptions)', async t => {84- const {stdout} = await $`noop-fd.js 2 ${foobarString}`.pipe($({stdin: 'pipe'})`stdin.js`, {from: 'stderr'});85- t.is(stdout, foobarString);86-});87-88-test('execa.$.pipe(subprocess, pipeOptions)', async t => {89- const {stdout} = await execa('noop-fd.js', ['2', foobarString]).pipe($({stdin: 'pipe'})`stdin.js`, {from: 'stderr'});90- t.is(stdout, foobarString);91-});92-93-test('$.pipe.pipe(subprocess, pipeOptions)', async t => {94- const {stdout} = await $`noop-fd.js 2 ${foobarString}`95- .pipe($({stdin: 'pipe'})`noop-stdin-fd.js 2`, {from: 'stderr'})96- .pipe($({stdin: 'pipe'})`stdin.js`, {from: 'stderr'});97- t.is(stdout, foobarString);98-});99-100-test('$.pipe(pipeOptions)`command`', async t => {101- const {stdout} = await $`noop-fd.js 2 ${foobarString}`.pipe({from: 'stderr'})`stdin.js`;102- t.is(stdout, foobarString);103-});104-105-test('execa.$.pipe(pipeOptions)`command`', async t => {106- const {stdout} = await execa('noop-fd.js', ['2', foobarString]).pipe({from: 'stderr'})`stdin.js`;107- t.is(stdout, foobarString);108-});109-110-test('$.pipe.pipe(pipeOptions)`command`', async t => {111- const {stdout} = await $`noop-fd.js 2 ${foobarString}`112- .pipe({from: 'stderr'})`noop-stdin-fd.js 2`113- .pipe({from: 'stderr'})`stdin.js`;114- t.is(stdout, foobarString);115-});116-117-test('$.pipe("file", pipeOptions)', async t => {118- const {stdout} = await $`noop-fd.js 2 ${foobarString}`.pipe('stdin.js', {from: 'stderr'});119- t.is(stdout, foobarString);120-});121-122-test('execa.$.pipe("file", pipeOptions)', async t => {123- const {stdout} = await execa('noop-fd.js', ['2', foobarString]).pipe('stdin.js', {from: 'stderr'});124- t.is(stdout, foobarString);125-});126-127-test('$.pipe.pipe("file", pipeOptions)', async t => {128- const {stdout} = await $`noop-fd.js 2 ${foobarString}`129- .pipe({from: 'stderr'})`noop-stdin-fd.js 2`130- .pipe('stdin.js', {from: 'stderr'});131- t.is(stdout, foobarString);132-});133-134-test('$.pipe(options)`command`', async t => {135- const {stdout} = await $`noop.js ${foobarString}`.pipe({stripFinalNewline: false})`stdin.js`;136- t.is(stdout, `${foobarString}\n`);137-});138-139-test('execa.$.pipe(options)`command`', async t => {140- const {stdout} = await execa('noop.js', [foobarString]).pipe({stripFinalNewline: false})`stdin.js`;141- t.is(stdout, `${foobarString}\n`);142-});143-144-test('$.pipe.pipe(options)`command`', async t => {145- const {stdout} = await $`noop.js ${foobarString}`146- .pipe({})`stdin.js`147- .pipe({stripFinalNewline: false})`stdin.js`;148- t.is(stdout, `${foobarString}\n`);149-});150-151-test('$.pipe("file", options)', async t => {152- const {stdout} = await $`noop.js ${foobarString}`.pipe('stdin.js', {stripFinalNewline: false});153- t.is(stdout, `${foobarString}\n`);154-});155-156-test('execa.$.pipe("file", options)', async t => {157- const {stdout} = await execa('noop.js', [foobarString]).pipe('stdin.js', {stripFinalNewline: false});158- t.is(stdout, `${foobarString}\n`);159-});160-161-test('$.pipe.pipe("file", options)', async t => {162- const {stdout} = await $`noop.js ${foobarString}`163- .pipe({})`stdin.js`164- .pipe('stdin.js', {stripFinalNewline: false});165- t.is(stdout, `${foobarString}\n`);166-});167-168-test('$.pipe(pipeAndSubprocessOptions)`command`', async t => {169- const {stdout} = await $`noop-fd.js 2 ${foobarString}\n`.pipe({from: 'stderr', stripFinalNewline: false})`stdin.js`;170- t.is(stdout, `${foobarString}\n`);171-});172-173-test('execa.$.pipe(pipeAndSubprocessOptions)`command`', async t => {174- const {stdout} = await execa('noop-fd.js', ['2', `${foobarString}\n`]).pipe({from: 'stderr', stripFinalNewline: false})`stdin.js`;175- t.is(stdout, `${foobarString}\n`);176-});177-178-test('$.pipe.pipe(pipeAndSubprocessOptions)`command`', async t => {179- const {stdout} = await $`noop-fd.js 2 ${foobarString}\n`180- .pipe({from: 'stderr'})`noop-stdin-fd.js 2`181- .pipe({from: 'stderr', stripFinalNewline: false})`stdin.js`;182- t.is(stdout, `${foobarString}\n`);183-});184-185-test('$.pipe("file", pipeAndSubprocessOptions)', async t => {186- const {stdout} = await $`noop-fd.js 2 ${foobarString}\n`.pipe('stdin.js', {from: 'stderr', stripFinalNewline: false});187- t.is(stdout, `${foobarString}\n`);188-});189-190-test('execa.$.pipe("file", pipeAndSubprocessOptions)', async t => {191- const {stdout} = await execa('noop-fd.js', ['2', `${foobarString}\n`]).pipe('stdin.js', {from: 'stderr', stripFinalNewline: false});192- t.is(stdout, `${foobarString}\n`);193-});194-195-test('$.pipe.pipe("file", pipeAndSubprocessOptions)', async t => {196- const {stdout} = await $`noop-fd.js 2 ${foobarString}\n`197- .pipe({from: 'stderr'})`noop-stdin-fd.js 2`198- .pipe('stdin.js', {from: 'stderr', stripFinalNewline: false});199- t.is(stdout, `${foobarString}\n`);200-});201-202-test('$.pipe(options)(secondOptions)`command`', async t => {203- const {stdout} = await $`noop.js ${foobarString}`.pipe({stripFinalNewline: false})({stripFinalNewline: true})`stdin.js`;204- t.is(stdout, foobarString);205-});206-207-test('execa.$.pipe(options)(secondOptions)`command`', async t => {208- const {stdout} = await execa('noop.js', [foobarString]).pipe({stripFinalNewline: false})({stripFinalNewline: true})`stdin.js`;209- t.is(stdout, foobarString);210-});211-212-test('$.pipe.pipe(options)(secondOptions)`command`', async t => {213- const {stdout} = await $`noop.js ${foobarString}`214- .pipe({})({})`stdin.js`215- .pipe({stripFinalNewline: false})({stripFinalNewline: true})`stdin.js`;216- t.is(stdout, foobarString);217-});218-219-test('$.pipe`command` forces "stdin: pipe"', async t => {220- const {stdout} = await $`noop.js ${foobarString}`.pipe({stdin: 'ignore'})`stdin.js`;221- t.is(stdout, foobarString);222-});223-224-test('execa.pipe("file") forces "stdin: "pipe"', async t => {225- const {stdout} = await execa('noop.js', [foobarString]).pipe('stdin.js', {stdin: 'ignore'});226- t.is(stdout, foobarString);227-});228-229-test('execa.pipe(subprocess) does not force "stdin: pipe"', async t => {230- await t.throwsAsync(231- execa('noop.js', [foobarString]).pipe(execa('stdin.js', {stdin: 'ignore'})),232- {message: /"stdin: 'ignore'" option is incompatible/},233- );234-});235-236-test('$.pipe(options)(subprocess) fails', async t => {237- await t.throwsAsync(238- $`empty.js`.pipe({stdout: 'pipe'})($`empty.js`),239- {message: /Please use \.pipe/},240- );241-});242-243-test('execa.$.pipe(options)(subprocess) fails', async t => {244- await t.throwsAsync(245- execa('empty.js').pipe({stdout: 'pipe'})($`empty.js`),246- {message: /Please use \.pipe/},247- );248-});249-250-test('$.pipe(options)("file") fails', async t => {251- await t.throwsAsync(252- $`empty.js`.pipe({stdout: 'pipe'})('empty.js'),253- {message: /Please use \.pipe/},254- );255-});256-257-test('execa.$.pipe(options)("file") fails', async t => {258- await t.throwsAsync(259- execa('empty.js').pipe({stdout: 'pipe'})('empty.js'),260- {message: /Please use \.pipe/},261- );262-});263-264-const testInvalidPipe = async (t, ...args) => {265- await t.throwsAsync(266- $`empty.js`.pipe(...args),267- {message: /must be a template string/},268- );269-};270-271-test('$.pipe(nonExecaSubprocess) fails', testInvalidPipe, spawn('node', ['--version']));272-test('$.pipe(false) fails', testInvalidPipe, false);added:test/resolve/all.js+171 added
1+import test from 'ava';2+import {execa, execaSync} from '../../index.js';3+import {setFixtureDir} from '../helpers/fixtures-dir.js';4+import {defaultHighWaterMark} from '../helpers/stream.js';5+import {foobarString} from '../helpers/input.js';6+7+setFixtureDir();8+9+const textEncoder = new TextEncoder();10+const foobarStringFull = `${foobarString}\n`;11+const doubleFoobarStringFull = `${foobarStringFull}${foobarStringFull}`;12+const doubleFoobarString = `${foobarStringFull}${foobarString}`;13+const doubleFoobarUint8ArrayFull = textEncoder.encode(doubleFoobarStringFull);14+const doubleFoobarUint8Array = textEncoder.encode(doubleFoobarString);15+const doubleFoobarArrayFull = [foobarStringFull, foobarStringFull];16+const doubleFoobarArray = [foobarString, foobarString];17+18+// eslint-disable-next-line max-params19+const testAllBoth = async (t, expectedOutput, encoding, lines, stripFinalNewline, isFailure, execaMethod) => {20+ const fixtureName = isFailure ? 'noop-both-fail.js' : 'noop-both.js';21+ const {exitCode, all} = await execaMethod(fixtureName, [foobarString], {all: true, encoding, lines, stripFinalNewline, reject: !isFailure});22+ t.is(exitCode, isFailure ? 1 : 0);23+ t.deepEqual(all, expectedOutput);24+};25+26+const fdOne = {stderr: true};27+const fdBoth = {stdout: true, stderr: true};28+29+test('result.all is defined', testAllBoth, doubleFoobarStringFull, 'utf8', false, false, false, execa);30+test('result.all is defined, encoding "buffer"', testAllBoth, doubleFoobarUint8ArrayFull, 'buffer', false, false, false, execa);31+test('result.all is defined, lines', testAllBoth, doubleFoobarArrayFull, 'utf8', true, false, false, execa);32+test('result.all is defined, lines, fd-specific one', testAllBoth, doubleFoobarArrayFull, 'utf8', fdOne, false, false, execa);33+test('result.all is defined, lines, fd-specific both', testAllBoth, doubleFoobarArrayFull, 'utf8', fdBoth, false, false, execa);34+test('result.all is defined, stripFinalNewline', testAllBoth, doubleFoobarString, 'utf8', false, true, false, execa);35+test('result.all is defined, stripFinalNewline, fd-specific one', testAllBoth, doubleFoobarString, 'utf8', false, fdOne, false, execa);36+test('result.all is defined, stripFinalNewline, fd-specific both', testAllBoth, doubleFoobarString, 'utf8', false, fdBoth, false, execa);37+test('result.all is defined, encoding "buffer", stripFinalNewline', testAllBoth, doubleFoobarUint8Array, 'buffer', false, true, false, execa);38+test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific one', testAllBoth, doubleFoobarUint8Array, 'buffer', false, fdOne, false, execa);39+test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific both', testAllBoth, doubleFoobarUint8Array, 'buffer', false, fdBoth, false, execa);40+test('result.all is defined, lines, stripFinalNewline', testAllBoth, doubleFoobarArray, 'utf8', true, true, false, execa);41+test('result.all is defined, lines, fd-specific one, stripFinalNewline', testAllBoth, doubleFoobarArray, 'utf8', fdOne, true, false, execa);42+test('result.all is defined, lines, fd-specific both, stripFinalNewline', testAllBoth, doubleFoobarArray, 'utf8', fdBoth, true, false, execa);43+test('result.all is defined, lines, stripFinalNewline, fd-specific one', testAllBoth, doubleFoobarArray, 'utf8', true, fdOne, false, execa);44+test('result.all is defined, lines, stripFinalNewline, fd-specific both', testAllBoth, doubleFoobarArray, 'utf8', true, fdBoth, false, execa);45+test('result.all is defined, failure', testAllBoth, doubleFoobarStringFull, 'utf8', false, false, true, execa);46+test('result.all is defined, encoding "buffer", failure', testAllBoth, doubleFoobarUint8ArrayFull, 'buffer', false, false, true, execa);47+test('result.all is defined, lines, failure', testAllBoth, doubleFoobarArrayFull, 'utf8', true, false, true, execa);48+test('result.all is defined, lines, fd-specific one, failure', testAllBoth, doubleFoobarArrayFull, 'utf8', fdOne, false, true, execa);49+test('result.all is defined, lines, fd-specific both, failure', testAllBoth, doubleFoobarArrayFull, 'utf8', fdBoth, false, true, execa);50+test('result.all is defined, stripFinalNewline, failure', testAllBoth, doubleFoobarString, 'utf8', false, true, true, execa);51+test('result.all is defined, stripFinalNewline, fd-specific one, failure', testAllBoth, doubleFoobarString, 'utf8', false, fdOne, true, execa);52+test('result.all is defined, stripFinalNewline, fd-specific both, failure', testAllBoth, doubleFoobarString, 'utf8', false, fdBoth, true, execa);53+test('result.all is defined, encoding "buffer", stripFinalNewline, failure', testAllBoth, doubleFoobarUint8Array, 'buffer', false, true, true, execa);54+test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific one, failure', testAllBoth, doubleFoobarUint8Array, 'buffer', false, fdOne, true, execa);55+test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific both, failure', testAllBoth, doubleFoobarUint8Array, 'buffer', false, fdBoth, true, execa);56+test('result.all is defined, lines, stripFinalNewline, failure', testAllBoth, doubleFoobarArray, 'utf8', true, true, true, execa);57+test('result.all is defined, lines, fd-specific one, stripFinalNewline, failure', testAllBoth, doubleFoobarArray, 'utf8', fdOne, true, true, execa);58+test('result.all is defined, lines, fd-specific both, stripFinalNewline, failure', testAllBoth, doubleFoobarArray, 'utf8', fdBoth, true, true, execa);59+test('result.all is defined, lines, stripFinalNewline, fd-specific one, failure', testAllBoth, doubleFoobarArray, 'utf8', true, fdOne, true, execa);60+test('result.all is defined, lines, stripFinalNewline, fd-specific both, failure', testAllBoth, doubleFoobarArray, 'utf8', true, fdBoth, true, execa);61+test('result.all is defined, sync', testAllBoth, doubleFoobarStringFull, 'utf8', false, false, false, execaSync);62+test('result.all is defined, encoding "buffer", sync', testAllBoth, doubleFoobarUint8ArrayFull, 'buffer', false, false, false, execaSync);63+test('result.all is defined, lines, sync', testAllBoth, doubleFoobarArrayFull, 'utf8', true, false, false, execaSync);64+test('result.all is defined, lines, fd-specific one, sync', testAllBoth, doubleFoobarArrayFull, 'utf8', fdOne, false, false, execaSync);65+test('result.all is defined, lines, fd-specific both, sync', testAllBoth, doubleFoobarArrayFull, 'utf8', fdBoth, false, false, execaSync);66+test('result.all is defined, stripFinalNewline, sync', testAllBoth, doubleFoobarString, 'utf8', false, true, false, execaSync);67+test('result.all is defined, stripFinalNewline, fd-specific one, sync', testAllBoth, doubleFoobarString, 'utf8', false, fdOne, false, execaSync);68+test('result.all is defined, stripFinalNewline, fd-specific both, sync', testAllBoth, doubleFoobarString, 'utf8', false, fdBoth, false, execaSync);69+test('result.all is defined, encoding "buffer", stripFinalNewline, sync', testAllBoth, doubleFoobarUint8Array, 'buffer', false, true, false, execaSync);70+test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific one, sync', testAllBoth, doubleFoobarUint8Array, 'buffer', false, fdOne, false, execaSync);71+test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific both, sync', testAllBoth, doubleFoobarUint8Array, 'buffer', false, fdBoth, false, execaSync);72+test('result.all is defined, lines, stripFinalNewline, sync', testAllBoth, doubleFoobarArray, 'utf8', true, true, false, execaSync);73+test('result.all is defined, lines, fd-specific one, stripFinalNewline, sync', testAllBoth, doubleFoobarArray, 'utf8', fdOne, true, false, execaSync);74+test('result.all is defined, lines, fd-specific both, stripFinalNewline, sync', testAllBoth, doubleFoobarArray, 'utf8', fdBoth, true, false, execaSync);75+test('result.all is defined, lines, stripFinalNewline, fd-specific one, sync', testAllBoth, doubleFoobarArray, 'utf8', true, fdOne, false, execaSync);76+test('result.all is defined, lines, stripFinalNewline, fd-specific both, sync', testAllBoth, doubleFoobarArray, 'utf8', true, fdBoth, false, execaSync);77+test('result.all is defined, failure, sync', testAllBoth, doubleFoobarStringFull, 'utf8', false, false, true, execaSync);78+test('result.all is defined, encoding "buffer", failure, sync', testAllBoth, doubleFoobarUint8ArrayFull, 'buffer', false, false, true, execaSync);79+test('result.all is defined, lines, failure, sync', testAllBoth, doubleFoobarArrayFull, 'utf8', true, false, true, execaSync);80+test('result.all is defined, lines, fd-specific one, failure, sync', testAllBoth, doubleFoobarArrayFull, 'utf8', fdOne, false, true, execaSync);81+test('result.all is defined, lines, fd-specific both, failure, sync', testAllBoth, doubleFoobarArrayFull, 'utf8', fdBoth, false, true, execaSync);82+test('result.all is defined, stripFinalNewline, failure, sync', testAllBoth, doubleFoobarString, 'utf8', false, true, true, execaSync);83+test('result.all is defined, stripFinalNewline, fd-specific one, failure, sync', testAllBoth, doubleFoobarString, 'utf8', false, fdOne, true, execaSync);84+test('result.all is defined, stripFinalNewline, fd-specific both, failure, sync', testAllBoth, doubleFoobarString, 'utf8', false, fdBoth, true, execaSync);85+test('result.all is defined, encoding "buffer", stripFinalNewline, failure, sync', testAllBoth, doubleFoobarUint8Array, 'buffer', false, true, true, execaSync);86+test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific one, failure, sync', testAllBoth, doubleFoobarUint8Array, 'buffer', false, fdOne, true, execaSync);87+test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific both, failure, sync', testAllBoth, doubleFoobarUint8Array, 'buffer', false, fdBoth, true, execaSync);88+test('result.all is defined, lines, stripFinalNewline, failure, sync', testAllBoth, doubleFoobarArray, 'utf8', true, true, true, execaSync);89+test('result.all is defined, lines, fd-specific one, stripFinalNewline, failure, sync', testAllBoth, doubleFoobarArray, 'utf8', fdOne, true, true, execaSync);90+test('result.all is defined, lines, fd-specific both, stripFinalNewline, failure, sync', testAllBoth, doubleFoobarArray, 'utf8', fdBoth, true, true, execaSync);91+test('result.all is defined, lines, stripFinalNewline, fd-specific one, failure, sync', testAllBoth, doubleFoobarArray, 'utf8', true, fdOne, true, execaSync);92+test('result.all is defined, lines, stripFinalNewline, fd-specific both, failure, sync', testAllBoth, doubleFoobarArray, 'utf8', true, fdBoth, true, execaSync);93+94+test.serial('result.all shows both `stdout` and `stderr` intermixed', async t => {95+ const {all} = await execa('noop-132.js', {all: true});96+ t.is(all, '1\n2\n3');97+});98+99+test.serial('result.all shows both `stdout` and `stderr` not intermixed, sync', t => {100+ const {all} = execaSync('noop-132.js', {all: true});101+ t.is(all, '1\n3\n2');102+});103+104+const testAllIgnored = async (t, options, execaMethod) => {105+ const {all} = await execaMethod('noop.js');106+ t.is(all, undefined);107+};108+109+test('result.all is undefined unless opts.all is true', testAllIgnored, {}, execa);110+test('result.all is undefined if opts.all is false', testAllIgnored, {all: false}, execa);111+test('result.all is undefined if ignored', testAllIgnored, {stdio: 'ignore', all: true}, execa);112+test('result.all is undefined unless opts.all is true, sync', testAllIgnored, {}, execaSync);113+test('result.all is undefined if opts.all is false, sync', testAllIgnored, {all: false}, execaSync);114+test('result.all is undefined if ignored, sync', testAllIgnored, {stdio: 'ignore', all: true}, execaSync);115+116+const testAllProperties = async (t, options) => {117+ const subprocess = execa('empty.js', {...options, all: true});118+ t.is(subprocess.all.readableObjectMode, false);119+ t.is(subprocess.all.readableHighWaterMark, defaultHighWaterMark);120+ await subprocess;121+};122+123+test('subprocess.all has the right objectMode and highWaterMark - stdout + stderr', testAllProperties, {});124+test('subprocess.all has the right objectMode and highWaterMark - stdout only', testAllProperties, {stderr: 'ignore'});125+test('subprocess.all has the right objectMode and highWaterMark - stderr only', testAllProperties, {stdout: 'ignore'});126+127+const testAllIgnore = async (t, streamName, otherStreamName) => {128+ const subprocess = execa('noop-both.js', {[otherStreamName]: 'ignore', all: true});129+ t.is(subprocess[otherStreamName], null);130+ t.not(subprocess[streamName], null);131+ t.not(subprocess.all, null);132+ t.is(subprocess.all.readableObjectMode, subprocess[streamName].readableObjectMode);133+ t.is(subprocess.all.readableHighWaterMark, subprocess[streamName].readableHighWaterMark);134+135+ const result = await subprocess;136+ t.is(result[otherStreamName], undefined);137+ t.is(result[streamName], foobarString);138+ t.is(result.all, foobarString);139+};140+141+test('can use all: true with stdout: ignore', testAllIgnore, 'stderr', 'stdout');142+test('can use all: true with stderr: ignore', testAllIgnore, 'stdout', 'stderr');143+144+const testAllIgnoreSync = (t, streamName, otherStreamName) => {145+ const result = execaSync('noop-both.js', {[otherStreamName]: 'ignore', all: true});146+ t.is(result[otherStreamName], undefined);147+ t.is(result[streamName], foobarString);148+ t.is(result.all, foobarString);149+};150+151+test('can use all: true with stdout: ignore, sync', testAllIgnoreSync, 'stderr', 'stdout');152+test('can use all: true with stderr: ignore, sync', testAllIgnoreSync, 'stdout', 'stderr');153+154+test('can use all: true with stdout: ignore + stderr: ignore', async t => {155+ const subprocess = execa('noop-both.js', {stdout: 'ignore', stderr: 'ignore', all: true});156+ t.is(subprocess.stdout, null);157+ t.is(subprocess.stderr, null);158+ t.is(subprocess.all, undefined);159+160+ const {stdout, stderr, all} = await subprocess;161+ t.is(stdout, undefined);162+ t.is(stderr, undefined);163+ t.is(all, undefined);164+});165+166+test('can use all: true with stdout: ignore + stderr: ignore, sync', t => {167+ const {stdout, stderr, all} = execaSync('noop-both.js', {stdout: 'ignore', stderr: 'ignore', all: true});168+ t.is(stdout, undefined);169+ t.is(stderr, undefined);170+ t.is(all, undefined);171+});added:test/resolve/buffer-end.js+78 added
1+import {once} from 'node:events';2+import {setTimeout} from 'node:timers/promises';3+import test from 'ava';4+import {execa} from '../../index.js';5+import {setFixtureDir} from '../helpers/fixtures-dir.js';6+import {fullStdio, getStdio} from '../helpers/stdio.js';7+8+setFixtureDir();9+10+const testBufferIgnore = async (t, fdNumber, all) => {11+ await t.notThrowsAsync(execa('max-buffer.js', [`${fdNumber}`], {...getStdio(fdNumber, 'ignore'), buffer: false, all}));12+};13+14+test('Subprocess buffers stdout, which does not prevent exit if ignored', testBufferIgnore, 1, false);15+test('Subprocess buffers stderr, which does not prevent exit if ignored', testBufferIgnore, 2, false);16+test('Subprocess buffers all, which does not prevent exit if ignored', testBufferIgnore, 1, true);17+18+const testBufferNotRead = async (t, fdNumber, all) => {19+ const subprocess = execa('max-buffer.js', [`${fdNumber}`], {...fullStdio, buffer: false, all});20+ await t.notThrowsAsync(subprocess);21+};22+23+test('Subprocess buffers stdout, which does not prevent exit if not read and buffer is false', testBufferNotRead, 1, false);24+test('Subprocess buffers stderr, which does not prevent exit if not read and buffer is false', testBufferNotRead, 2, false);25+test('Subprocess buffers stdio[*], which does not prevent exit if not read and buffer is false', testBufferNotRead, 3, false);26+test('Subprocess buffers all, which does not prevent exit if not read and buffer is false', testBufferNotRead, 1, true);27+28+const testBufferRead = async (t, fdNumber, all) => {29+ const subprocess = execa('max-buffer.js', [`${fdNumber}`], {...fullStdio, buffer: false, all});30+ const stream = all ? subprocess.all : subprocess.stdio[fdNumber];31+ stream.resume();32+ await t.notThrowsAsync(subprocess);33+};34+35+test('Subprocess buffers stdout, which does not prevent exit if read and buffer is false', testBufferRead, 1, false);36+test('Subprocess buffers stderr, which does not prevent exit if read and buffer is false', testBufferRead, 2, false);37+test('Subprocess buffers stdio[*], which does not prevent exit if read and buffer is false', testBufferRead, 3, false);38+test('Subprocess buffers all, which does not prevent exit if read and buffer is false', testBufferRead, 1, true);39+40+const testBufferExit = async (t, fdNumber, fixtureName, reject) => {41+ const subprocess = execa(fixtureName, [`${fdNumber}`], {...fullStdio, reject});42+ await setTimeout(100);43+ const {stdio} = await subprocess;44+ t.is(stdio[fdNumber], 'foobar');45+};46+47+test('Subprocess buffers stdout before it is read', testBufferExit, 1, 'noop-delay.js', true);48+test('Subprocess buffers stderr before it is read', testBufferExit, 2, 'noop-delay.js', true);49+test('Subprocess buffers stdio[*] before it is read', testBufferExit, 3, 'noop-delay.js', true);50+test('Subprocess buffers stdout right away, on successfully exit', testBufferExit, 1, 'noop-fd.js', true);51+test('Subprocess buffers stderr right away, on successfully exit', testBufferExit, 2, 'noop-fd.js', true);52+test('Subprocess buffers stdio[*] right away, on successfully exit', testBufferExit, 3, 'noop-fd.js', true);53+test('Subprocess buffers stdout right away, on failure', testBufferExit, 1, 'noop-fail.js', false);54+test('Subprocess buffers stderr right away, on failure', testBufferExit, 2, 'noop-fail.js', false);55+test('Subprocess buffers stdio[*] right away, on failure', testBufferExit, 3, 'noop-fail.js', false);56+57+const testBufferDirect = async (t, fdNumber) => {58+ const subprocess = execa('noop-fd.js', [`${fdNumber}`], fullStdio);59+ const data = await once(subprocess.stdio[fdNumber], 'data');60+ t.is(data.toString().trim(), 'foobar');61+ const result = await subprocess;62+ t.is(result.stdio[fdNumber], 'foobar');63+};64+65+test('Subprocess buffers stdout right away, even if directly read', testBufferDirect, 1);66+test('Subprocess buffers stderr right away, even if directly read', testBufferDirect, 2);67+test('Subprocess buffers stdio[*] right away, even if directly read', testBufferDirect, 3);68+69+const testBufferDestroyOnEnd = async (t, fdNumber) => {70+ const subprocess = execa('noop-fd.js', [`${fdNumber}`], fullStdio);71+ const result = await subprocess;72+ t.is(result.stdio[fdNumber], 'foobar');73+ t.true(subprocess.stdio[fdNumber].destroyed);74+};75+76+test('subprocess.stdout must be read right away', testBufferDestroyOnEnd, 1);77+test('subprocess.stderr must be read right away', testBufferDestroyOnEnd, 2);78+test('subprocess.stdio[*] must be read right away', testBufferDestroyOnEnd, 3);added:test/resolve/exit.js+85 added
1+import process from 'node:process';2+import test from 'ava';3+import {execa} from '../../index.js';4+import {setFixtureDir} from '../helpers/fixtures-dir.js';5+6+const isWindows = process.platform === 'win32';7+8+setFixtureDir();9+10+test('exitCode is 0 on success', async t => {11+ const {exitCode} = await execa('noop.js', ['foo']);12+ t.is(exitCode, 0);13+});14+15+const testExitCode = async (t, expectedExitCode) => {16+ const {exitCode, originalMessage, shortMessage, message} = await t.throwsAsync(17+ execa('exit.js', [`${expectedExitCode}`]),18+ );19+ t.is(exitCode, expectedExitCode);20+ t.is(originalMessage, '');21+ t.is(shortMessage, `Command failed with exit code ${expectedExitCode}: exit.js ${expectedExitCode}`);22+ t.is(message, shortMessage);23+};24+25+test('exitCode is 2', testExitCode, 2);26+test('exitCode is 3', testExitCode, 3);27+test('exitCode is 4', testExitCode, 4);28+29+if (!isWindows) {30+ test('error.signal is SIGINT', async t => {31+ const subprocess = execa('forever.js');32+33+ process.kill(subprocess.pid, 'SIGINT');34+35+ const {signal} = await t.throwsAsync(subprocess, {message: /was killed with SIGINT/});36+ t.is(signal, 'SIGINT');37+ });38+39+ test('error.signalDescription is defined', async t => {40+ const subprocess = execa('forever.js');41+42+ process.kill(subprocess.pid, 'SIGINT');43+44+ const {signalDescription} = await t.throwsAsync(subprocess, {message: /User interruption with CTRL-C/});45+ t.is(signalDescription, 'User interruption with CTRL-C');46+ });47+48+ test('error.signal is SIGTERM', async t => {49+ const subprocess = execa('forever.js');50+51+ process.kill(subprocess.pid, 'SIGTERM');52+53+ const {signal} = await t.throwsAsync(subprocess, {message: /was killed with SIGTERM/});54+ t.is(signal, 'SIGTERM');55+ });56+57+ test('error.signal uses killSignal', async t => {58+ const {signal} = await t.throwsAsync(execa('forever.js', {killSignal: 'SIGINT', timeout: 1, message: /timed out after/}));59+ t.is(signal, 'SIGINT');60+ });61+62+ test('exitCode is undefined on signal termination', async t => {63+ const subprocess = execa('forever.js');64+65+ process.kill(subprocess.pid);66+67+ const {exitCode} = await t.throwsAsync(subprocess);68+ t.is(exitCode, undefined);69+ });70+}71+72+test('result.signal is undefined for successful execution', async t => {73+ const {signal} = await execa('noop.js');74+ t.is(signal, undefined);75+});76+77+test('result.signal is undefined if subprocess failed, but was not killed', async t => {78+ const {signal} = await t.throwsAsync(execa('fail.js'));79+ t.is(signal, undefined);80+});81+82+test('result.signalDescription is undefined for successful execution', async t => {83+ const {signalDescription} = await execa('noop.js');84+ t.is(signalDescription, undefined);85+});added:test/resolve/no-buffer.js+192 added
1+import {once} from 'node:events';2+import test from 'ava';3+import getStream from 'get-stream';4+import {execa, execaSync} from '../../index.js';5+import {setFixtureDir} from '../helpers/fixtures-dir.js';6+import {fullStdio, getStdio} from '../helpers/stdio.js';7+import {foobarString, foobarUppercase, foobarUppercaseUint8Array} from '../helpers/input.js';8+import {resultGenerator, uppercaseGenerator, uppercaseBufferGenerator} from '../helpers/generator.js';9+10+setFixtureDir();11+12+const testLateStream = async (t, fdNumber, all) => {13+ const subprocess = execa('noop-fd-ipc.js', [`${fdNumber}`, foobarString], {...getStdio(4, 'ipc', 4), buffer: false, all});14+ await once(subprocess, 'message');15+ const [output, allOutput] = await Promise.all([16+ getStream(subprocess.stdio[fdNumber]),17+ all ? getStream(subprocess.all) : undefined,18+ subprocess,19+ ]);20+21+ t.is(output, '');22+23+ if (all) {24+ t.is(allOutput, '');25+ }26+};27+28+test('Lacks some data when stdout is read too late `buffer` set to `false`', testLateStream, 1, false);29+test('Lacks some data when stderr is read too late `buffer` set to `false`', testLateStream, 2, false);30+test('Lacks some data when stdio[*] is read too late `buffer` set to `false`', testLateStream, 3, false);31+test('Lacks some data when all is read too late `buffer` set to `false`', testLateStream, 1, true);32+33+const getFirstDataEvent = async stream => {34+ const [output] = await once(stream, 'data');35+ return output.toString();36+};37+38+// eslint-disable-next-line max-params39+const testIterationBuffer = async (t, fdNumber, buffer, useDataEvents, all) => {40+ const subprocess = execa('noop-fd.js', [`${fdNumber}`, foobarString], {...fullStdio, buffer, all});41+ const getOutput = useDataEvents ? getFirstDataEvent : getStream;42+ const [result, output, allOutput] = await Promise.all([43+ subprocess,44+ getOutput(subprocess.stdio[fdNumber]),45+ all ? getOutput(subprocess.all) : undefined,46+ ]);47+48+ const expectedResult = buffer ? foobarString : undefined;49+50+ t.is(result.stdio[fdNumber], expectedResult);51+ t.is(output, foobarString);52+53+ if (all) {54+ t.is(result.all, expectedResult);55+ t.is(allOutput, foobarString);56+ }57+};58+59+test('Can iterate stdout when `buffer` set to `false`', testIterationBuffer, 1, false, false, false);60+test('Can iterate stderr when `buffer` set to `false`', testIterationBuffer, 2, false, false, false);61+test('Can iterate stdio[*] when `buffer` set to `false`', testIterationBuffer, 3, false, false, false);62+test('Can iterate all when `buffer` set to `false`', testIterationBuffer, 1, false, false, true);63+test('Can iterate stdout when `buffer` set to `true`', testIterationBuffer, 1, true, false, false);64+test('Can iterate stderr when `buffer` set to `true`', testIterationBuffer, 2, true, false, false);65+test('Can iterate stdio[*] when `buffer` set to `true`', testIterationBuffer, 3, true, false, false);66+test('Can iterate all when `buffer` set to `true`', testIterationBuffer, 1, true, false, true);67+test('Can listen to `data` events on stdout when `buffer` set to `false`', testIterationBuffer, 1, false, true, false);68+test('Can listen to `data` events on stderr when `buffer` set to `false`', testIterationBuffer, 2, false, true, false);69+test('Can listen to `data` events on stdio[*] when `buffer` set to `false`', testIterationBuffer, 3, false, true, false);70+test('Can listen to `data` events on all when `buffer` set to `false`', testIterationBuffer, 1, false, true, true);71+test('Can listen to `data` events on stdout when `buffer` set to `true`', testIterationBuffer, 1, true, true, false);72+test('Can listen to `data` events on stderr when `buffer` set to `true`', testIterationBuffer, 2, true, true, false);73+test('Can listen to `data` events on stdio[*] when `buffer` set to `true`', testIterationBuffer, 3, true, true, false);74+test('Can listen to `data` events on all when `buffer` set to `true`', testIterationBuffer, 1, true, true, true);75+76+const testNoBufferStreamError = async (t, fdNumber, all) => {77+ const subprocess = execa('noop-fd.js', [`${fdNumber}`], {...fullStdio, buffer: false, all});78+ const stream = all ? subprocess.all : subprocess.stdio[fdNumber];79+ const cause = new Error('test');80+ stream.destroy(cause);81+ t.like(await t.throwsAsync(subprocess), {cause});82+};83+84+test('Listen to stdout errors even when `buffer` is `false`', testNoBufferStreamError, 1, false);85+test('Listen to stderr errors even when `buffer` is `false`', testNoBufferStreamError, 2, false);86+test('Listen to stdio[*] errors even when `buffer` is `false`', testNoBufferStreamError, 3, false);87+test('Listen to all errors even when `buffer` is `false`', testNoBufferStreamError, 1, true);88+89+const testOutput = async (t, buffer, execaMethod) => {90+ const {stdout} = await execaMethod('noop-fd.js', ['1', foobarString], {buffer});91+ t.is(stdout, foobarString);92+};93+94+test('buffer: true returns output', testOutput, true, execa);95+test('buffer: true returns output, fd-specific', testOutput, {stderr: false}, execa);96+test('buffer: default returns output', testOutput, undefined, execa);97+test('buffer: default returns output, fd-specific', testOutput, {}, execa);98+99+const testNoOutput = async (t, stdioOption, buffer, execaMethod) => {100+ const {stdout} = await execaMethod('noop.js', {stdout: stdioOption, buffer});101+ t.is(stdout, undefined);102+};103+104+test('buffer: false does not return output', testNoOutput, 'pipe', false, execa);105+test('buffer: false does not return output, fd-specific', testNoOutput, 'pipe', {stdout: false}, execa);106+test('buffer: false does not return output, stdout undefined', testNoOutput, undefined, false, execa);107+test('buffer: false does not return output, stdout null', testNoOutput, null, false, execa);108+test('buffer: false does not return output, stdout ["pipe"]', testNoOutput, ['pipe'], false, execa);109+test('buffer: false does not return output, stdout [undefined]', testNoOutput, [undefined], false, execa);110+test('buffer: false does not return output, stdout [null]', testNoOutput, [null], false, execa);111+test('buffer: false does not return output, stdout ["pipe", undefined]', testNoOutput, ['pipe', undefined], false, execa);112+test('buffer: false does not return output, sync', testNoOutput, 'pipe', false, execaSync);113+test('buffer: false does not return output, fd-specific, sync', testNoOutput, 'pipe', {stdout: false}, execaSync);114+test('buffer: false does not return output, stdout undefined, sync', testNoOutput, undefined, false, execaSync);115+test('buffer: false does not return output, stdout null, sync', testNoOutput, null, false, execaSync);116+test('buffer: false does not return output, stdout ["pipe"], sync', testNoOutput, ['pipe'], false, execaSync);117+test('buffer: false does not return output, stdout [undefined], sync', testNoOutput, [undefined], false, execaSync);118+test('buffer: false does not return output, stdout [null], sync', testNoOutput, [null], false, execaSync);119+test('buffer: false does not return output, stdout ["pipe", undefined], sync', testNoOutput, ['pipe', undefined], false, execaSync);120+121+const testNoOutputFail = async (t, execaMethod) => {122+ const {exitCode, stdout} = await execaMethod('fail.js', {buffer: false, reject: false});123+ t.is(exitCode, 2);124+ t.is(stdout, undefined);125+};126+127+test('buffer: false does not return output, failure', testNoOutputFail, execa);128+test('buffer: false does not return output, failure, sync', testNoOutputFail, execaSync);129+130+// eslint-disable-next-line max-params131+const testNoOutputAll = async (t, buffer, bufferStdout, bufferStderr, execaMethod) => {132+ const {stdout, stderr, all} = await execaMethod('noop-both.js', {all: true, buffer, stripFinalNewline: false});133+ t.is(stdout, bufferStdout ? `${foobarString}\n` : undefined);134+ t.is(stderr, bufferStderr ? `${foobarString}\n` : undefined);135+ const stdoutStderr = [stdout, stderr].filter(Boolean);136+ t.is(all, stdoutStderr.length === 0 ? undefined : stdoutStderr.join(''));137+};138+139+test('buffer: {}, all: true', testNoOutputAll, {}, true, true, execa);140+test('buffer: {stdout: false}, all: true', testNoOutputAll, {stdout: false}, false, true, execa);141+test('buffer: {stderr: false}, all: true', testNoOutputAll, {stderr: false}, true, false, execa);142+test('buffer: {all: false}, all: true', testNoOutputAll, {all: false}, false, false, execa);143+test('buffer: {}, all: true, sync', testNoOutputAll, {}, true, true, execaSync);144+test('buffer: {stdout: false}, all: true, sync', testNoOutputAll, {stdout: false}, false, true, execaSync);145+test('buffer: {stderr: false}, all: true, sync', testNoOutputAll, {stderr: false}, true, false, execaSync);146+test('buffer: {all: false}, all: true, sync', testNoOutputAll, {all: false}, false, false, execaSync);147+148+const testTransform = async (t, objectMode, execaMethod) => {149+ const lines = [];150+ const {stdout} = await execaMethod('noop.js', {151+ buffer: false,152+ stdout: [uppercaseGenerator(objectMode), resultGenerator(lines)(objectMode)],153+ });154+ t.is(stdout, undefined);155+ t.deepEqual(lines, [foobarUppercase]);156+};157+158+test('buffer: false still runs transforms', testTransform, false, execa);159+test('buffer: false still runs transforms, objectMode', testTransform, true, execa);160+test('buffer: false still runs transforms, sync', testTransform, false, execaSync);161+test('buffer: false still runs transforms, objectMode, sync', testTransform, true, execaSync);162+163+const testTransformBinary = async (t, objectMode, execaMethod) => {164+ const lines = [];165+ const {stdout} = await execaMethod('noop-fd.js', ['1', foobarString], {166+ buffer: false,167+ stdout: [uppercaseBufferGenerator(objectMode, true), resultGenerator(lines)(objectMode)],168+ encoding: 'buffer',169+ });170+ t.is(stdout, undefined);171+ t.deepEqual(lines, [foobarUppercaseUint8Array]);172+};173+174+test('buffer: false still runs transforms, encoding "buffer"', testTransformBinary, false, execa);175+test('buffer: false still runs transforms, encoding "buffer", objectMode', testTransformBinary, true, execa);176+test('buffer: false still runs transforms, encoding "buffer", sync', testTransformBinary, false, execaSync);177+test('buffer: false still runs transforms, encoding "buffer", objectMode, sync', testTransformBinary, true, execaSync);178+179+const testStreamEnd = async (t, fdNumber, buffer) => {180+ const subprocess = execa('wrong command', {...fullStdio, buffer});181+ await Promise.all([182+ t.throwsAsync(subprocess, {message: /wrong command/}),183+ once(subprocess.stdio[fdNumber], 'end'),184+ ]);185+};186+187+test('buffer: false > emits end event on stdout when promise is rejected', testStreamEnd, 1, false);188+test('buffer: false > emits end event on stderr when promise is rejected', testStreamEnd, 2, false);189+test('buffer: false > emits end event on stdio[*] when promise is rejected', testStreamEnd, 3, false);190+test('buffer: true > emits end event on stdout when promise is rejected', testStreamEnd, 1, true);191+test('buffer: true > emits end event on stderr when promise is rejected', testStreamEnd, 2, true);192+test('buffer: true > emits end event on stdio[*] when promise is rejected', testStreamEnd, 3, true);added:test/resolve/stdio.js+117 added
1+import {setTimeout} from 'node:timers/promises';2+import test from 'ava';3+import {execa} from '../../index.js';4+import {setFixtureDir} from '../helpers/fixtures-dir.js';5+import {fullStdio, getStdio, prematureClose, assertEpipe} from '../helpers/stdio.js';6+import {infiniteGenerator} from '../helpers/generator.js';7+8+setFixtureDir();9+10+const getStreamInputSubprocess = fdNumber => execa('stdin-fd.js', [`${fdNumber}`], fdNumber === 311+ ? getStdio(3, [new Uint8Array(), infiniteGenerator()])12+ : {});13+const getStreamOutputSubprocess = fdNumber => execa('noop-repeat.js', [`${fdNumber}`], fdNumber === 3 ? fullStdio : {});14+15+const assertStreamInputError = (t, {exitCode, signal, isTerminated, failed}) => {16+ t.is(exitCode, 0);17+ t.is(signal, undefined);18+ t.false(isTerminated);19+ t.true(failed);20+};21+22+const assertStreamOutputError = (t, fdNumber, {exitCode, signal, isTerminated, failed, stderr}) => {23+ if (fdNumber !== 3) {24+ t.is(exitCode, 1);25+ }26+27+ t.is(signal, undefined);28+ t.false(isTerminated);29+ t.true(failed);30+31+ assertEpipe(t, stderr, fdNumber);32+};33+34+const testStreamInputAbort = async (t, fdNumber) => {35+ const subprocess = getStreamInputSubprocess(fdNumber);36+ subprocess.stdio[fdNumber].destroy();37+ const error = await t.throwsAsync(subprocess, prematureClose);38+ assertStreamInputError(t, error);39+};40+41+test('Aborting stdin should not make the subprocess exit', testStreamInputAbort, 0);42+test('Aborting input stdio[*] should not make the subprocess exit', testStreamInputAbort, 3);43+44+const testStreamOutputAbort = async (t, fdNumber) => {45+ const subprocess = getStreamOutputSubprocess(fdNumber);46+ subprocess.stdio[fdNumber].destroy();47+ const error = await t.throwsAsync(subprocess);48+ assertStreamOutputError(t, fdNumber, error);49+};50+51+test('Aborting stdout should not make the subprocess exit', testStreamOutputAbort, 1);52+test('Aborting stderr should not make the subprocess exit', testStreamOutputAbort, 2);53+test('Aborting output stdio[*] should not make the subprocess exit', testStreamOutputAbort, 3);54+55+const testStreamInputDestroy = async (t, fdNumber) => {56+ const subprocess = getStreamInputSubprocess(fdNumber);57+ const cause = new Error('test');58+ subprocess.stdio[fdNumber].destroy(cause);59+ const error = await t.throwsAsync(subprocess);60+ t.is(error.cause, cause);61+ assertStreamInputError(t, error);62+};63+64+test('Destroying stdin should not make the subprocess exit', testStreamInputDestroy, 0);65+test('Destroying input stdio[*] should not make the subprocess exit', testStreamInputDestroy, 3);66+67+const testStreamOutputDestroy = async (t, fdNumber) => {68+ const subprocess = getStreamOutputSubprocess(fdNumber);69+ const cause = new Error('test');70+ subprocess.stdio[fdNumber].destroy(cause);71+ const error = await t.throwsAsync(subprocess);72+ t.is(error.cause, cause);73+ assertStreamOutputError(t, fdNumber, error);74+};75+76+test('Destroying stdout should not make the subprocess exit', testStreamOutputDestroy, 1);77+test('Destroying stderr should not make the subprocess exit', testStreamOutputDestroy, 2);78+test('Destroying output stdio[*] should not make the subprocess exit', testStreamOutputDestroy, 3);79+80+const testStreamInputError = async (t, fdNumber) => {81+ const subprocess = getStreamInputSubprocess(fdNumber);82+ const cause = new Error('test');83+ const stream = subprocess.stdio[fdNumber];84+ stream.emit('error', cause);85+ stream.end();86+ const error = await t.throwsAsync(subprocess);87+ t.is(error.cause, cause);88+ assertStreamInputError(t, error);89+};90+91+test('Errors on stdin should not make the subprocess exit', testStreamInputError, 0);92+test('Errors on input stdio[*] should not make the subprocess exit', testStreamInputError, 3);93+94+const testStreamOutputError = async (t, fdNumber) => {95+ const subprocess = getStreamOutputSubprocess(fdNumber);96+ const cause = new Error('test');97+ const stream = subprocess.stdio[fdNumber];98+ stream.emit('error', cause);99+ const error = await t.throwsAsync(subprocess);100+ t.is(error.cause, cause);101+ assertStreamOutputError(t, fdNumber, error);102+};103+104+test('Errors on stdout should make the subprocess exit', testStreamOutputError, 1);105+test('Errors on stderr should make the subprocess exit', testStreamOutputError, 2);106+test('Errors on output stdio[*] should make the subprocess exit', testStreamOutputError, 3);107+108+const testWaitOnStreamEnd = async (t, fdNumber) => {109+ const subprocess = execa('stdin-fd.js', [`${fdNumber}`], fullStdio);110+ await setTimeout(100);111+ subprocess.stdio[fdNumber].end('foobar');112+ const {stdout} = await subprocess;113+ t.is(stdout, 'foobar');114+};115+116+test('Subprocess waits on stdin before exiting', testWaitOnStreamEnd, 0);117+test('Subprocess waits on stdio[*] before exiting', testWaitOnStreamEnd, 3);added:test/resolve/wait-abort.js+99 added
1+import {setImmediate} from 'node:timers/promises';2+import test from 'ava';3+import {execa} from '../../index.js';4+import {setFixtureDir} from '../helpers/fixtures-dir.js';5+import {prematureClose} from '../helpers/stdio.js';6+import {noopReadable, noopWritable, noopDuplex} from '../helpers/stream.js';7+import {endOptionStream, destroyOptionStream, destroySubprocessStream, getStreamStdio} from '../helpers/wait.js';8+9+setFixtureDir();10+11+const noop = () => {};12+13+// eslint-disable-next-line max-params14+const testStreamAbortWait = async (t, streamMethod, stream, fdNumber, useTransform) => {15+ const subprocess = execa('noop-stdin-fd.js', [`${fdNumber}`], getStreamStdio(fdNumber, stream, useTransform));16+ streamMethod({stream, subprocess, fdNumber});17+ subprocess.stdin.end();18+ await setImmediate();19+ stream.destroy();20+21+ const {stdout} = await subprocess;22+ t.is(stdout, '');23+ t.true(stream.destroyed);24+};25+26+test('Keeps running when stdin option is used and subprocess.stdin ends', testStreamAbortWait, noop, noopReadable(), 0, false);27+test('Keeps running when stdin option is used and subprocess.stdin Duplex ends', testStreamAbortWait, noop, noopDuplex(), 0, false);28+test('Keeps running when input stdio[*] option is used and input subprocess.stdio[*] ends', testStreamAbortWait, noop, noopReadable(), 3, false);29+test('Keeps running when stdin option is used and subprocess.stdin ends, with a transform', testStreamAbortWait, noop, noopReadable(), 0, true);30+test('Keeps running when stdin option is used and subprocess.stdin Duplex ends, with a transform', testStreamAbortWait, noop, noopDuplex(), 0, true);31+test('Keeps running when input stdio[*] option is used and input subprocess.stdio[*] ends, with a transform', testStreamAbortWait, noop, noopReadable(), 3, true);32+33+// eslint-disable-next-line max-params34+const testStreamAbortSuccess = async (t, streamMethod, stream, fdNumber, useTransform) => {35+ const subprocess = execa('noop-stdin-fd.js', [`${fdNumber}`], getStreamStdio(fdNumber, stream, useTransform));36+ streamMethod({stream, subprocess, fdNumber});37+ subprocess.stdin.end();38+39+ const {stdout} = await subprocess;40+ t.is(stdout, '');41+ t.true(stream.destroyed);42+};43+44+test('Passes when stdin option aborts', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 0, false);45+test('Passes when stdin option Duplex aborts', testStreamAbortSuccess, destroyOptionStream, noopDuplex(), 0, false);46+test('Passes when input stdio[*] option aborts', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 3, false);47+test('Passes when stdout option ends with no more writes', testStreamAbortSuccess, endOptionStream, noopWritable(), 1, false);48+test('Passes when stderr option ends with no more writes', testStreamAbortSuccess, endOptionStream, noopWritable(), 2, false);49+test('Passes when output stdio[*] option ends with no more writes', testStreamAbortSuccess, endOptionStream, noopWritable(), 3, false);50+test('Passes when subprocess.stdout aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 1, false);51+test('Passes when subprocess.stdout Duplex aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 1, false);52+test('Passes when subprocess.stderr aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 2, false);53+test('Passes when subprocess.stderr Duplex aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 2, false);54+test('Passes when output subprocess.stdio[*] aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 3, false);55+test('Passes when output subprocess.stdio[*] Duplex aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 3, false);56+test('Passes when stdin option aborts, with a transform', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 0, true);57+test('Passes when stdin option Duplex aborts, with a transform', testStreamAbortSuccess, destroyOptionStream, noopDuplex(), 0, true);58+test('Passes when input stdio[*] option aborts, with a transform', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 3, true);59+test('Passes when stdout option ends with no more writes, with a transform', testStreamAbortSuccess, endOptionStream, noopWritable(), 1, true);60+test('Passes when stderr option ends with no more writes, with a transform', testStreamAbortSuccess, endOptionStream, noopWritable(), 2, true);61+test('Passes when output stdio[*] option ends with no more writes, with a transform', testStreamAbortSuccess, endOptionStream, noopWritable(), 3, true);62+test('Passes when subprocess.stdout aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 1, true);63+test('Passes when subprocess.stdout Duplex aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 1, true);64+test('Passes when subprocess.stderr aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 2, true);65+test('Passes when subprocess.stderr Duplex aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 2, true);66+test('Passes when output subprocess.stdio[*] aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 3, true);67+test('Passes when output subprocess.stdio[*] Duplex aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 3, true);68+69+// eslint-disable-next-line max-params70+const testStreamAbortFail = async (t, streamMethod, stream, fdNumber, useTransform) => {71+ const subprocess = execa('noop-stdin-fd.js', [`${fdNumber}`], getStreamStdio(fdNumber, stream, useTransform));72+ streamMethod({stream, subprocess, fdNumber});73+ if (fdNumber !== 0) {74+ subprocess.stdin.end();75+ }76+77+ const error = await t.throwsAsync(subprocess);78+ t.like(error, {...prematureClose, exitCode: 0});79+ t.true(stream.destroyed);80+};81+82+test('Throws abort error when subprocess.stdin aborts', testStreamAbortFail, destroySubprocessStream, noopReadable(), 0, false);83+test('Throws abort error when subprocess.stdin Duplex aborts', testStreamAbortFail, destroySubprocessStream, noopDuplex(), 0, false);84+test('Throws abort error when input subprocess.stdio[*] aborts', testStreamAbortFail, destroySubprocessStream, noopReadable(), 3, false);85+test('Throws abort error when stdout option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopWritable(), 1, false);86+test('Throws abort error when stdout option Duplex aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopDuplex(), 1, false);87+test('Throws abort error when stderr option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopWritable(), 2, false);88+test('Throws abort error when stderr option Duplex aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopDuplex(), 2, false);89+test('Throws abort error when output stdio[*] option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopWritable(), 3, false);90+test('Throws abort error when output stdio[*] Duplex option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopDuplex(), 3, false);91+test('Throws abort error when subprocess.stdin aborts, with a transform', testStreamAbortFail, destroySubprocessStream, noopReadable(), 0, true);92+test('Throws abort error when subprocess.stdin Duplex aborts, with a transform', testStreamAbortFail, destroySubprocessStream, noopDuplex(), 0, true);93+test('Throws abort error when input subprocess.stdio[*] aborts, with a transform', testStreamAbortFail, destroySubprocessStream, noopReadable(), 3, true);94+test('Throws abort error when stdout option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopWritable(), 1, true);95+test('Throws abort error when stdout option Duplex aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopDuplex(), 1, true);96+test('Throws abort error when stderr option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopWritable(), 2, true);97+test('Throws abort error when stderr option Duplex aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopDuplex(), 2, true);98+test('Throws abort error when output stdio[*] option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopWritable(), 3, true);99+test('Throws abort error when output stdio[*] Duplex option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopDuplex(), 3, true);added:test/resolve/wait-epipe.js+55 added
1+import {setImmediate} from 'node:timers/promises';2+import test from 'ava';3+import {execa} from '../../index.js';4+import {setFixtureDir} from '../helpers/fixtures-dir.js';5+import {assertEpipe} from '../helpers/stdio.js';6+import {foobarString} from '../helpers/input.js';7+import {noopWritable, noopDuplex} from '../helpers/stream.js';8+import {endOptionStream, destroyOptionStream, destroySubprocessStream, getStreamStdio} from '../helpers/wait.js';9+10+setFixtureDir();11+12+// eslint-disable-next-line max-params13+const testStreamEpipeFail = async (t, streamMethod, stream, fdNumber, useTransform) => {14+ const subprocess = execa('noop-stdin-fd.js', [`${fdNumber}`], getStreamStdio(fdNumber, stream, useTransform));15+ streamMethod({stream, subprocess, fdNumber});16+ await setImmediate();17+ subprocess.stdin.end(foobarString);18+19+ const {exitCode, stdio, stderr} = await t.throwsAsync(subprocess);20+ t.is(exitCode, 1);21+ t.is(stdio[fdNumber], '');22+ t.true(stream.destroyed);23+ assertEpipe(t, stderr, fdNumber);24+};25+26+test('Throws EPIPE when stdout option ends with more writes', testStreamEpipeFail, endOptionStream, noopWritable(), 1, false);27+test('Throws EPIPE when stdout option aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopWritable(), 1, false);28+test('Throws EPIPE when stdout option Duplex aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 1, false);29+test('Throws EPIPE when stderr option ends with more writes', testStreamEpipeFail, endOptionStream, noopWritable(), 2, false);30+test('Throws EPIPE when stderr option aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopWritable(), 2, false);31+test('Throws EPIPE when stderr option Duplex aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 2, false);32+test('Throws EPIPE when output stdio[*] option ends with more writes', testStreamEpipeFail, endOptionStream, noopWritable(), 3, false);33+test('Throws EPIPE when output stdio[*] option aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopWritable(), 3, false);34+test('Throws EPIPE when output stdio[*] option Duplex aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 3, false);35+test('Throws EPIPE when subprocess.stdout aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 1, false);36+test('Throws EPIPE when subprocess.stdout Duplex aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 1, false);37+test('Throws EPIPE when subprocess.stderr aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 2, false);38+test('Throws EPIPE when subprocess.stderr Duplex aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 2, false);39+test('Throws EPIPE when output subprocess.stdio[*] aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 3, false);40+test('Throws EPIPE when output subprocess.stdio[*] Duplex aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 3, false);41+test('Throws EPIPE when stdout option ends with more writes, with a transform', testStreamEpipeFail, endOptionStream, noopWritable(), 1, true);42+test('Throws EPIPE when stdout option aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopWritable(), 1, true);43+test('Throws EPIPE when stdout option Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 1, true);44+test('Throws EPIPE when stderr option ends with more writes, with a transform', testStreamEpipeFail, endOptionStream, noopWritable(), 2, true);45+test('Throws EPIPE when stderr option aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopWritable(), 2, true);46+test('Throws EPIPE when stderr option Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 2, true);47+test('Throws EPIPE when output stdio[*] option ends with more writes, with a transform', testStreamEpipeFail, endOptionStream, noopWritable(), 3, true);48+test('Throws EPIPE when output stdio[*] option aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopWritable(), 3, true);49+test('Throws EPIPE when output stdio[*] option Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 3, true);50+test('Throws EPIPE when subprocess.stdout aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 1, true);51+test('Throws EPIPE when subprocess.stdout Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 1, true);52+test('Throws EPIPE when subprocess.stderr aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 2, true);53+test('Throws EPIPE when subprocess.stderr Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 2, true);54+test('Throws EPIPE when output subprocess.stdio[*] aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 3, true);55+test('Throws EPIPE when output subprocess.stdio[*] Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 3, true);added:test/resolve/wait-error.js+59 added
1+import test from 'ava';2+import {execa} from '../../index.js';3+import {setFixtureDir} from '../helpers/fixtures-dir.js';4+import {noopReadable, noopWritable, noopDuplex} from '../helpers/stream.js';5+import {destroyOptionStream, destroySubprocessStream, getStreamStdio} from '../helpers/wait.js';6+7+setFixtureDir();8+9+// eslint-disable-next-line max-params10+const testStreamError = async (t, streamMethod, stream, fdNumber, useTransform) => {11+ const subprocess = execa('empty.js', getStreamStdio(fdNumber, stream, useTransform));12+ const cause = new Error('test');13+ streamMethod({stream, subprocess, fdNumber, error: cause});14+15+ const error = await t.throwsAsync(subprocess);16+ t.is(error.cause, cause);17+ t.is(error.exitCode, 0);18+ t.is(error.signal, undefined);19+ t.false(error.isTerminated);20+ t.true(error.failed);21+ t.true(stream.destroyed);22+};23+24+test('Throws stream error when stdin option errors', testStreamError, destroyOptionStream, noopReadable(), 0, false);25+test('Throws stream error when stdin option Duplex errors', testStreamError, destroyOptionStream, noopDuplex(), 0, false);26+test('Throws stream error when stdout option errors', testStreamError, destroyOptionStream, noopWritable(), 1, false);27+test('Throws stream error when stdout option Duplex errors', testStreamError, destroyOptionStream, noopDuplex(), 1, false);28+test('Throws stream error when stderr option errors', testStreamError, destroyOptionStream, noopWritable(), 2, false);29+test('Throws stream error when stderr option Duplex errors', testStreamError, destroyOptionStream, noopDuplex(), 2, false);30+test('Throws stream error when output stdio[*] option errors', testStreamError, destroyOptionStream, noopWritable(), 3, false);31+test('Throws stream error when output stdio[*] Duplex option errors', testStreamError, destroyOptionStream, noopDuplex(), 3, false);32+test('Throws stream error when input stdio[*] option errors', testStreamError, destroyOptionStream, noopReadable(), 3, false);33+test('Throws stream error when subprocess.stdin errors', testStreamError, destroySubprocessStream, noopReadable(), 0, false);34+test('Throws stream error when subprocess.stdin Duplex errors', testStreamError, destroySubprocessStream, noopDuplex(), 0, false);35+test('Throws stream error when subprocess.stdout errors', testStreamError, destroySubprocessStream, noopWritable(), 1, false);36+test('Throws stream error when subprocess.stdout Duplex errors', testStreamError, destroySubprocessStream, noopDuplex(), 1, false);37+test('Throws stream error when subprocess.stderr errors', testStreamError, destroySubprocessStream, noopWritable(), 2, false);38+test('Throws stream error when subprocess.stderr Duplex errors', testStreamError, destroySubprocessStream, noopDuplex(), 2, false);39+test('Throws stream error when output subprocess.stdio[*] errors', testStreamError, destroySubprocessStream, noopWritable(), 3, false);40+test('Throws stream error when output subprocess.stdio[*] Duplex errors', testStreamError, destroySubprocessStream, noopDuplex(), 3, false);41+test('Throws stream error when input subprocess.stdio[*] errors', testStreamError, destroySubprocessStream, noopReadable(), 3, false);42+test('Throws stream error when stdin option errors, with a transform', testStreamError, destroyOptionStream, noopReadable(), 0, true);43+test('Throws stream error when stdin option Duplex errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 0, true);44+test('Throws stream error when stdout option errors, with a transform', testStreamError, destroyOptionStream, noopWritable(), 1, true);45+test('Throws stream error when stdout option Duplex errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 1, true);46+test('Throws stream error when stderr option errors, with a transform', testStreamError, destroyOptionStream, noopWritable(), 2, true);47+test('Throws stream error when stderr option Duplex errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 2, true);48+test('Throws stream error when output stdio[*] option errors, with a transform', testStreamError, destroyOptionStream, noopWritable(), 3, true);49+test('Throws stream error when output stdio[*] Duplex option errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 3, true);50+test('Throws stream error when input stdio[*] option errors, with a transform', testStreamError, destroyOptionStream, noopReadable(), 3, true);51+test('Throws stream error when subprocess.stdin errors, with a transform', testStreamError, destroySubprocessStream, noopReadable(), 0, true);52+test('Throws stream error when subprocess.stdin Duplex errors, with a transform', testStreamError, destroySubprocessStream, noopDuplex(), 0, true);53+test('Throws stream error when subprocess.stdout errors, with a transform', testStreamError, destroySubprocessStream, noopWritable(), 1, true);54+test('Throws stream error when subprocess.stdout Duplex errors, with a transform', testStreamError, destroySubprocessStream, noopDuplex(), 1, true);55+test('Throws stream error when subprocess.stderr errors, with a transform', testStreamError, destroySubprocessStream, noopWritable(), 2, true);56+test('Throws stream error when subprocess.stderr Duplex errors, with a transform', testStreamError, destroySubprocessStream, noopDuplex(), 2, true);57+test('Throws stream error when output subprocess.stdio[*] errors, with a transform', testStreamError, destroySubprocessStream, noopWritable(), 3, true);58+test('Throws stream error when output subprocess.stdio[*] Duplex errors, with a transform', testStreamError, destroySubprocessStream, noopDuplex(), 3, true);59+test('Throws stream error when input subprocess.stdio[*] errors, with a transform', testStreamError, destroySubprocessStream, noopReadable(), 3, true);added:test/resolve/wait-subprocess.js+49 added
1+import test from 'ava';2+import {execa, execaSync} from '../../index.js';3+import {setFixtureDir} from '../helpers/fixtures-dir.js';4+import {getStdio} from '../helpers/stdio.js';5+6+setFixtureDir();7+8+const testIgnore = async (t, fdNumber, execaMethod) => {9+ const result = await execaMethod('noop.js', getStdio(fdNumber, 'ignore'));10+ t.is(result.stdio[fdNumber], undefined);11+};12+13+test('stdout is undefined if ignored', testIgnore, 1, execa);14+test('stderr is undefined if ignored', testIgnore, 2, execa);15+test('stdio[*] is undefined if ignored', testIgnore, 3, execa);16+test('stdout is undefined if ignored - sync', testIgnore, 1, execaSync);17+test('stderr is undefined if ignored - sync', testIgnore, 2, execaSync);18+test('stdio[*] is undefined if ignored - sync', testIgnore, 3, execaSync);19+20+const testSubprocessEventsCleanup = async (t, fixtureName) => {21+ const subprocess = execa(fixtureName, {reject: false});22+ t.deepEqual(subprocess.eventNames().map(String).sort(), ['Symbol(error)', 'error', 'exit', 'spawn']);23+ await subprocess;24+ t.deepEqual(subprocess.eventNames(), []);25+};26+27+test('subprocess listeners are cleaned up on success', testSubprocessEventsCleanup, 'empty.js');28+test('subprocess listeners are cleaned up on failure', testSubprocessEventsCleanup, 'fail.js');29+30+test('Aborting stdout should not abort stderr nor all', async t => {31+ const subprocess = execa('empty.js', {all: true});32+33+ subprocess.stdout.destroy();34+ t.false(subprocess.stdout.readable);35+ t.true(subprocess.stderr.readable);36+ t.true(subprocess.all.readable);37+38+ await subprocess;39+40+ t.false(subprocess.stdout.readableEnded);41+ t.is(subprocess.stdout.errored, null);42+ t.true(subprocess.stdout.destroyed);43+ t.true(subprocess.stderr.readableEnded);44+ t.is(subprocess.stderr.errored, null);45+ t.true(subprocess.stderr.destroyed);46+ t.true(subprocess.all.readableEnded);47+ t.is(subprocess.all.errored, null);48+ t.true(subprocess.all.destroyed);49+});deleted:test/return/cause.js-158 removed
1-import test from 'ava';2-import {execa, execaSync, ExecaError, ExecaSyncError} from '../../index.js';3-import {setFixtureDir} from '../helpers/fixtures-dir.js';4-import {foobarString} from '../helpers/input.js';5-import {getEarlyErrorSubprocess, getEarlyErrorSubprocessSync} from '../helpers/early-error.js';6-7-setFixtureDir();8-9-const testUnusualError = async (t, error, expectedOriginalMessage = String(error)) => {10- const subprocess = execa('empty.js');11- subprocess.emit('error', error);12- const {originalMessage, shortMessage, message} = await t.throwsAsync(subprocess);13- t.is(originalMessage, expectedOriginalMessage);14- t.true(shortMessage.includes(expectedOriginalMessage));15- t.is(message, shortMessage);16-};17-18-test('error instance can be null', testUnusualError, null);19-test('error instance can be false', testUnusualError, false);20-test('error instance can be a string', testUnusualError, 'test');21-test('error instance can be a number', testUnusualError, 0);22-test('error instance can be a BigInt', testUnusualError, 0n);23-test('error instance can be a symbol', testUnusualError, Symbol('test'));24-test('error instance can be a function', testUnusualError, () => {});25-test('error instance can be an array', testUnusualError, ['test', 'test']);26-// eslint-disable-next-line unicorn/error-message27-test('error instance can be an error with an empty message', testUnusualError, new Error(''), '');28-test('error instance can be undefined', testUnusualError, undefined, 'undefined');29-30-test('error instance can be a plain object', async t => {31- const subprocess = execa('empty.js');32- subprocess.emit('error', {message: foobarString});33- await t.throwsAsync(subprocess, {message: new RegExp(foobarString)});34-});35-36-const runAndFail = (t, fixtureName, argument, error) => {37- const subprocess = execa(fixtureName, [argument]);38- subprocess.emit('error', error);39- return t.throwsAsync(subprocess);40-};41-42-const testErrorCopy = async (t, getPreviousArgument, argument = 'two') => {43- const fixtureName = 'empty.js';44- const firstArgument = 'foo';45-46- const previousArgument = await getPreviousArgument(t, fixtureName);47- const previousError = await runAndFail(t, fixtureName, firstArgument, previousArgument);48- const error = await runAndFail(t, fixtureName, argument, previousError);49- const message = `Command failed: ${fixtureName} ${argument}\n${foobarString}`;50-51- t.not(error, previousError);52- t.is(error.cause, previousError);53- t.is(error.command, `${fixtureName} ${argument}`);54- t.is(error.message, message);55- t.true(error.stack.includes(message));56- t.is(error.shortMessage, message);57- t.is(error.originalMessage, foobarString);58-};59-60-test('error instance can be shared', testErrorCopy, () => new Error(foobarString));61-test('error TypeError can be shared', testErrorCopy, () => new TypeError(foobarString));62-test('error string can be shared', testErrorCopy, () => foobarString);63-test('error copy can be shared', testErrorCopy, (t, fixtureName) => runAndFail(t, fixtureName, 'bar', new Error(foobarString)));64-test('error with same message can be shared', testErrorCopy, () => new Error(foobarString), 'foo');65-66-test('error.cause is not set if error.exitCode is not 0', async t => {67- const {exitCode, cause} = await t.throwsAsync(execa('fail.js'));68- t.is(exitCode, 2);69- t.is(cause, undefined);70-});71-72-test('error.cause is not set if error.isTerminated', async t => {73- const subprocess = execa('forever.js');74- subprocess.kill();75- const {isTerminated, cause} = await t.throwsAsync(subprocess);76- t.true(isTerminated);77- t.is(cause, undefined);78-});79-80-test('error.cause is not set if error.timedOut', async t => {81- const {timedOut, cause} = await t.throwsAsync(execa('forever.js', {timeout: 1}));82- t.true(timedOut);83- t.is(cause, undefined);84-});85-86-test('error.cause is set on error event', async t => {87- const subprocess = execa('empty.js');88- const error = new Error(foobarString);89- subprocess.emit('error', error);90- const {cause} = await t.throwsAsync(subprocess);91- t.is(cause, error);92-});93-94-test('error.cause is set if error.isCanceled', async t => {95- const controller = new AbortController();96- const subprocess = execa('forever.js', {cancelSignal: controller.signal});97- const error = new Error('test');98- controller.abort(error);99- const {isCanceled, isTerminated, cause} = await t.throwsAsync(subprocess);100- t.true(isCanceled);101- t.false(isTerminated);102- t.is(cause.cause, error);103-});104-105-test('error.cause is not set if error.isTerminated with .kill(error)', async t => {106- const subprocess = execa('forever.js');107- const error = new Error('test');108- subprocess.kill(error);109- const {isTerminated, cause} = await t.throwsAsync(subprocess);110- t.true(isTerminated);111- t.is(cause, error);112-});113-114-test('Error is instanceof ExecaError', async t => {115- await t.throwsAsync(execa('fail.js'), {instanceOf: ExecaError});116-});117-118-test('Early error is instanceof ExecaError', async t => {119- await t.throwsAsync(getEarlyErrorSubprocess(), {instanceOf: ExecaError});120-});121-122-test('Error is instanceof ExecaSyncError', t => {123- t.throws(() => {124- execaSync('fail.js');125- }, {instanceOf: ExecaSyncError});126-});127-128-test('Early error is instanceof ExecaSyncError', t => {129- t.throws(() => {130- getEarlyErrorSubprocessSync();131- }, {instanceOf: ExecaSyncError});132-});133-134-test('Pipe error is instanceof ExecaError', async t => {135- await t.throwsAsync(execa('empty.js').pipe(false), {instanceOf: ExecaError});136-});137-138-const assertNameShape = (t, error) => {139- t.false(Object.hasOwn(error, 'name'));140- t.true(Object.hasOwn(Object.getPrototypeOf(error), 'name'));141- t.false(propertyIsEnumerable.call(Object.getPrototypeOf(error), 'name'));142-};143-144-const {propertyIsEnumerable} = Object.prototype;145-146-test('error.name is properly set', async t => {147- const error = await t.throwsAsync(execa('fail.js'));148- t.is(error.name, 'ExecaError');149- assertNameShape(t, error);150-});151-152-test('error.name is properly set - sync', async t => {153- const error = await t.throws(() => {154- execaSync('fail.js');155- });156- t.is(error.name, 'ExecaSyncError');157- assertNameShape(t, error);158-});deleted:test/return/error.js-145 removed
1-import process from 'node:process';2-import test from 'ava';3-import {execa, execaSync} from '../../index.js';4-import {setFixtureDir} from '../helpers/fixtures-dir.js';5-import {fullStdio} from '../helpers/stdio.js';6-7-const isWindows = process.platform === 'win32';8-9-setFixtureDir();10-11-const testSuccessShape = async (t, execaMethod) => {12- const result = await execaMethod('empty.js', {...fullStdio, all: true});13- t.deepEqual(Reflect.ownKeys(result), [14- 'command',15- 'escapedCommand',16- 'cwd',17- 'durationMs',18- 'failed',19- 'timedOut',20- 'isCanceled',21- 'isTerminated',22- 'isMaxBuffer',23- 'exitCode',24- 'stdout',25- 'stderr',26- 'all',27- 'stdio',28- 'pipedFrom',29- ]);30-};31-32-test('Return value properties are not missing and are ordered', testSuccessShape, execa);33-test('Return value properties are not missing and are ordered, sync', testSuccessShape, execaSync);34-35-const testErrorShape = async (t, execaMethod) => {36- const error = await execaMethod('fail.js', {...fullStdio, all: true, reject: false});37- t.is(error.exitCode, 2);38- t.deepEqual(Reflect.ownKeys(error), [39- 'stack',40- 'message',41- 'shortMessage',42- 'originalMessage',43- 'command',44- 'escapedCommand',45- 'cwd',46- 'durationMs',47- 'failed',48- 'timedOut',49- 'isCanceled',50- 'isTerminated',51- 'isMaxBuffer',52- 'exitCode',53- 'signal',54- 'signalDescription',55- 'code',56- 'stdout',57- 'stderr',58- 'all',59- 'stdio',60- 'pipedFrom',61- ]);62-};63-64-test('Error properties are not missing and are ordered', testErrorShape, execa);65-test('Error properties are not missing and are ordered, sync', testErrorShape, execaSync);66-67-test('failed is false on success', async t => {68- const {failed} = await execa('noop.js', ['foo']);69- t.false(failed);70-});71-72-test('failed is true on failure', async t => {73- const {failed} = await t.throwsAsync(execa('fail.js'));74- t.true(failed);75-});76-77-test('error.isTerminated is true if subprocess was killed directly', async t => {78- const subprocess = execa('forever.js', {killSignal: 'SIGINT'});79-80- subprocess.kill();81-82- const {isTerminated, signal, originalMessage, message, shortMessage} = await t.throwsAsync(subprocess, {message: /was killed with SIGINT/});83- t.true(isTerminated);84- t.is(signal, 'SIGINT');85- t.is(originalMessage, '');86- t.is(shortMessage, 'Command was killed with SIGINT (User interruption with CTRL-C): forever.js');87- t.is(message, shortMessage);88-});89-90-test('error.isTerminated is true if subprocess was killed indirectly', async t => {91- const subprocess = execa('forever.js', {killSignal: 'SIGHUP'});92-93- process.kill(subprocess.pid, 'SIGINT');94-95- // `subprocess.kill()` is emulated by Node.js on Windows96- if (isWindows) {97- const {isTerminated, signal} = await t.throwsAsync(subprocess, {message: /failed with exit code 1/});98- t.is(isTerminated, false);99- t.is(signal, undefined);100- } else {101- const {isTerminated, signal} = await t.throwsAsync(subprocess, {message: /was killed with SIGINT/});102- t.is(isTerminated, true);103- t.is(signal, 'SIGINT');104- }105-});106-107-test('result.isTerminated is false if not killed', async t => {108- const {isTerminated} = await execa('noop.js');109- t.false(isTerminated);110-});111-112-test('result.isTerminated is false if not killed and subprocess.kill() was called', async t => {113- const subprocess = execa('noop.js');114- subprocess.kill(0);115- t.true(subprocess.killed);116- const {isTerminated} = await subprocess;117- t.false(isTerminated);118-});119-120-test('result.isTerminated is false if not killed, in sync mode', t => {121- const {isTerminated} = execaSync('noop.js');122- t.false(isTerminated);123-});124-125-test('result.isTerminated is false on subprocess error', async t => {126- const {isTerminated} = await t.throwsAsync(execa('wrong command'));127- t.false(isTerminated);128-});129-130-test('result.isTerminated is false on subprocess error, in sync mode', t => {131- const {isTerminated} = t.throws(() => {132- execaSync('wrong command');133- });134- t.false(isTerminated);135-});136-137-test('error.code is undefined on success', async t => {138- const {code} = await execa('noop.js');139- t.is(code, undefined);140-});141-142-test('error.code is defined on failure if applicable', async t => {143- const {code} = await t.throwsAsync(execa('noop.js', {uid: true}));144- t.is(code, 'ERR_INVALID_ARG_TYPE');145-});added:test/return/final-error.js+158 added
1+import test from 'ava';2+import {execa, execaSync, ExecaError, ExecaSyncError} from '../../index.js';3+import {setFixtureDir} from '../helpers/fixtures-dir.js';4+import {foobarString} from '../helpers/input.js';5+import {getEarlyErrorSubprocess, getEarlyErrorSubprocessSync} from '../helpers/early-error.js';6+7+setFixtureDir();8+9+const testUnusualError = async (t, error, expectedOriginalMessage = String(error)) => {10+ const subprocess = execa('empty.js');11+ subprocess.emit('error', error);12+ const {originalMessage, shortMessage, message} = await t.throwsAsync(subprocess);13+ t.is(originalMessage, expectedOriginalMessage);14+ t.true(shortMessage.includes(expectedOriginalMessage));15+ t.is(message, shortMessage);16+};17+18+test('error instance can be null', testUnusualError, null);19+test('error instance can be false', testUnusualError, false);20+test('error instance can be a string', testUnusualError, 'test');21+test('error instance can be a number', testUnusualError, 0);22+test('error instance can be a BigInt', testUnusualError, 0n);23+test('error instance can be a symbol', testUnusualError, Symbol('test'));24+test('error instance can be a function', testUnusualError, () => {});25+test('error instance can be an array', testUnusualError, ['test', 'test']);26+// eslint-disable-next-line unicorn/error-message27+test('error instance can be an error with an empty message', testUnusualError, new Error(''), '');28+test('error instance can be undefined', testUnusualError, undefined, 'undefined');29+30+test('error instance can be a plain object', async t => {31+ const subprocess = execa('empty.js');32+ subprocess.emit('error', {message: foobarString});33+ await t.throwsAsync(subprocess, {message: new RegExp(foobarString)});34+});35+36+const runAndFail = (t, fixtureName, argument, error) => {37+ const subprocess = execa(fixtureName, [argument]);38+ subprocess.emit('error', error);39+ return t.throwsAsync(subprocess);40+};41+42+const testErrorCopy = async (t, getPreviousArgument, argument = 'two') => {43+ const fixtureName = 'empty.js';44+ const firstArgument = 'foo';45+46+ const previousArgument = await getPreviousArgument(t, fixtureName);47+ const previousError = await runAndFail(t, fixtureName, firstArgument, previousArgument);48+ const error = await runAndFail(t, fixtureName, argument, previousError);49+ const message = `Command failed: ${fixtureName} ${argument}\n${foobarString}`;50+51+ t.not(error, previousError);52+ t.is(error.cause, previousError);53+ t.is(error.command, `${fixtureName} ${argument}`);54+ t.is(error.message, message);55+ t.true(error.stack.includes(message));56+ t.is(error.shortMessage, message);57+ t.is(error.originalMessage, foobarString);58+};59+60+test('error instance can be shared', testErrorCopy, () => new Error(foobarString));61+test('error TypeError can be shared', testErrorCopy, () => new TypeError(foobarString));62+test('error string can be shared', testErrorCopy, () => foobarString);63+test('error copy can be shared', testErrorCopy, (t, fixtureName) => runAndFail(t, fixtureName, 'bar', new Error(foobarString)));64+test('error with same message can be shared', testErrorCopy, () => new Error(foobarString), 'foo');65+66+test('error.cause is not set if error.exitCode is not 0', async t => {67+ const {exitCode, cause} = await t.throwsAsync(execa('fail.js'));68+ t.is(exitCode, 2);69+ t.is(cause, undefined);70+});71+72+test('error.cause is not set if error.isTerminated', async t => {73+ const subprocess = execa('forever.js');74+ subprocess.kill();75+ const {isTerminated, cause} = await t.throwsAsync(subprocess);76+ t.true(isTerminated);77+ t.is(cause, undefined);78+});79+80+test('error.cause is not set if error.timedOut', async t => {81+ const {timedOut, cause} = await t.throwsAsync(execa('forever.js', {timeout: 1}));82+ t.true(timedOut);83+ t.is(cause, undefined);84+});85+86+test('error.cause is set on error event', async t => {87+ const subprocess = execa('empty.js');88+ const error = new Error(foobarString);89+ subprocess.emit('error', error);90+ const {cause} = await t.throwsAsync(subprocess);91+ t.is(cause, error);92+});93+94+test('error.cause is set if error.isCanceled', async t => {95+ const controller = new AbortController();96+ const subprocess = execa('forever.js', {cancelSignal: controller.signal});97+ const error = new Error('test');98+ controller.abort(error);99+ const {isCanceled, isTerminated, cause} = await t.throwsAsync(subprocess);100+ t.true(isCanceled);101+ t.false(isTerminated);102+ t.is(cause.cause, error);103+});104+105+test('error.cause is not set if error.isTerminated with .kill(error)', async t => {106+ const subprocess = execa('forever.js');107+ const error = new Error('test');108+ subprocess.kill(error);109+ const {isTerminated, cause} = await t.throwsAsync(subprocess);110+ t.true(isTerminated);111+ t.is(cause, error);112+});113+114+test('Error is instanceof ExecaError', async t => {115+ await t.throwsAsync(execa('fail.js'), {instanceOf: ExecaError});116+});117+118+test('Early error is instanceof ExecaError', async t => {119+ await t.throwsAsync(getEarlyErrorSubprocess(), {instanceOf: ExecaError});120+});121+122+test('Error is instanceof ExecaSyncError', t => {123+ t.throws(() => {124+ execaSync('fail.js');125+ }, {instanceOf: ExecaSyncError});126+});127+128+test('Early error is instanceof ExecaSyncError', t => {129+ t.throws(() => {130+ getEarlyErrorSubprocessSync();131+ }, {instanceOf: ExecaSyncError});132+});133+134+test('Pipe error is instanceof ExecaError', async t => {135+ await t.throwsAsync(execa('empty.js').pipe(false), {instanceOf: ExecaError});136+});137+138+const assertNameShape = (t, error) => {139+ t.false(Object.hasOwn(error, 'name'));140+ t.true(Object.hasOwn(Object.getPrototypeOf(error), 'name'));141+ t.false(propertyIsEnumerable.call(Object.getPrototypeOf(error), 'name'));142+};143+144+const {propertyIsEnumerable} = Object.prototype;145+146+test('error.name is properly set', async t => {147+ const error = await t.throwsAsync(execa('fail.js'));148+ t.is(error.name, 'ExecaError');149+ assertNameShape(t, error);150+});151+152+test('error.name is properly set - sync', async t => {153+ const error = await t.throws(() => {154+ execaSync('fail.js');155+ });156+ t.is(error.name, 'ExecaSyncError');157+ assertNameShape(t, error);158+});added:test/return/result.js+145 added
1+import process from 'node:process';2+import test from 'ava';3+import {execa, execaSync} from '../../index.js';4+import {setFixtureDir} from '../helpers/fixtures-dir.js';5+import {fullStdio} from '../helpers/stdio.js';6+7+const isWindows = process.platform === 'win32';8+9+setFixtureDir();10+11+const testSuccessShape = async (t, execaMethod) => {12+ const result = await execaMethod('empty.js', {...fullStdio, all: true});13+ t.deepEqual(Reflect.ownKeys(result), [14+ 'command',15+ 'escapedCommand',16+ 'cwd',17+ 'durationMs',18+ 'failed',19+ 'timedOut',20+ 'isCanceled',21+ 'isTerminated',22+ 'isMaxBuffer',23+ 'exitCode',24+ 'stdout',25+ 'stderr',26+ 'all',27+ 'stdio',28+ 'pipedFrom',29+ ]);30+};31+32+test('Return value properties are not missing and are ordered', testSuccessShape, execa);33+test('Return value properties are not missing and are ordered, sync', testSuccessShape, execaSync);34+35+const testErrorShape = async (t, execaMethod) => {36+ const error = await execaMethod('fail.js', {...fullStdio, all: true, reject: false});37+ t.is(error.exitCode, 2);38+ t.deepEqual(Reflect.ownKeys(error), [39+ 'stack',40+ 'message',41+ 'shortMessage',42+ 'originalMessage',43+ 'command',44+ 'escapedCommand',45+ 'cwd',46+ 'durationMs',47+ 'failed',48+ 'timedOut',49+ 'isCanceled',50+ 'isTerminated',51+ 'isMaxBuffer',52+ 'exitCode',53+ 'signal',54+ 'signalDescription',55+ 'code',56+ 'stdout',57+ 'stderr',58+ 'all',59+ 'stdio',60+ 'pipedFrom',61+ ]);62+};63+64+test('Error properties are not missing and are ordered', testErrorShape, execa);65+test('Error properties are not missing and are ordered, sync', testErrorShape, execaSync);66+67+test('failed is false on success', async t => {68+ const {failed} = await execa('noop.js', ['foo']);69+ t.false(failed);70+});71+72+test('failed is true on failure', async t => {73+ const {failed} = await t.throwsAsync(execa('fail.js'));74+ t.true(failed);75+});76+77+test('error.isTerminated is true if subprocess was killed directly', async t => {78+ const subprocess = execa('forever.js', {killSignal: 'SIGINT'});79+80+ subprocess.kill();81+82+ const {isTerminated, signal, originalMessage, message, shortMessage} = await t.throwsAsync(subprocess, {message: /was killed with SIGINT/});83+ t.true(isTerminated);84+ t.is(signal, 'SIGINT');85+ t.is(originalMessage, '');86+ t.is(shortMessage, 'Command was killed with SIGINT (User interruption with CTRL-C): forever.js');87+ t.is(message, shortMessage);88+});89+90+test('error.isTerminated is true if subprocess was killed indirectly', async t => {91+ const subprocess = execa('forever.js', {killSignal: 'SIGHUP'});92+93+ process.kill(subprocess.pid, 'SIGINT');94+95+ // `subprocess.kill()` is emulated by Node.js on Windows96+ if (isWindows) {97+ const {isTerminated, signal} = await t.throwsAsync(subprocess, {message: /failed with exit code 1/});98+ t.is(isTerminated, false);99+ t.is(signal, undefined);100+ } else {101+ const {isTerminated, signal} = await t.throwsAsync(subprocess, {message: /was killed with SIGINT/});102+ t.is(isTerminated, true);103+ t.is(signal, 'SIGINT');104+ }105+});106+107+test('result.isTerminated is false if not killed', async t => {108+ const {isTerminated} = await execa('noop.js');109+ t.false(isTerminated);110+});111+112+test('result.isTerminated is false if not killed and subprocess.kill() was called', async t => {113+ const subprocess = execa('noop.js');114+ subprocess.kill(0);115+ t.true(subprocess.killed);116+ const {isTerminated} = await subprocess;117+ t.false(isTerminated);118+});119+120+test('result.isTerminated is false if not killed, in sync mode', t => {121+ const {isTerminated} = execaSync('noop.js');122+ t.false(isTerminated);123+});124+125+test('result.isTerminated is false on subprocess error', async t => {126+ const {isTerminated} = await t.throwsAsync(execa('wrong command'));127+ t.false(isTerminated);128+});129+130+test('result.isTerminated is false on subprocess error, in sync mode', t => {131+ const {isTerminated} = t.throws(() => {132+ execaSync('wrong command');133+ });134+ t.false(isTerminated);135+});136+137+test('error.code is undefined on success', async t => {138+ const {code} = await execa('noop.js');139+ t.is(code, undefined);140+});141+142+test('error.code is defined on failure if applicable', async t => {143+ const {code} = await t.throwsAsync(execa('noop.js', {uid: true}));144+ t.is(code, 'ERR_INVALID_ARG_TYPE');145+});deleted:test/return/strip-newline.js-56 removed
1-import test from 'ava';2-import {execa, execaSync} from '../../index.js';3-import {setFixtureDir} from '../helpers/fixtures-dir.js';4-import {fullStdio} from '../helpers/stdio.js';5-import {noopGenerator} from '../helpers/generator.js';6-import {foobarString} from '../helpers/input.js';7-8-setFixtureDir();9-10-// eslint-disable-next-line max-params11-const testStripFinalNewline = async (t, fdNumber, stripFinalNewline, shouldStrip, execaMethod) => {12- const {stdio} = await execaMethod('noop-fd.js', [`${fdNumber}`, `${foobarString}\n`], {...fullStdio, stripFinalNewline});13- t.is(stdio[fdNumber], `${foobarString}${shouldStrip ? '' : '\n'}`);14-};15-16-test('stripFinalNewline: default with stdout', testStripFinalNewline, 1, undefined, true, execa);17-test('stripFinalNewline: true with stdout', testStripFinalNewline, 1, true, true, execa);18-test('stripFinalNewline: false with stdout', testStripFinalNewline, 1, false, false, execa);19-test('stripFinalNewline: default with stderr', testStripFinalNewline, 2, undefined, true, execa);20-test('stripFinalNewline: true with stderr', testStripFinalNewline, 2, true, true, execa);21-test('stripFinalNewline: false with stderr', testStripFinalNewline, 2, false, false, execa);22-test('stripFinalNewline: default with stdio[*]', testStripFinalNewline, 3, undefined, true, execa);23-test('stripFinalNewline: true with stdio[*]', testStripFinalNewline, 3, true, true, execa);24-test('stripFinalNewline: false with stdio[*]', testStripFinalNewline, 3, false, false, execa);25-test('stripFinalNewline: default with stdout, fd-specific', testStripFinalNewline, 1, {}, true, execa);26-test('stripFinalNewline: true with stdout, fd-specific', testStripFinalNewline, 1, {stdout: true}, true, execa);27-test('stripFinalNewline: false with stdout, fd-specific', testStripFinalNewline, 1, {stdout: false}, false, execa);28-test('stripFinalNewline: default with stderr, fd-specific', testStripFinalNewline, 2, {}, true, execa);29-test('stripFinalNewline: true with stderr, fd-specific', testStripFinalNewline, 2, {stderr: true}, true, execa);30-test('stripFinalNewline: false with stderr, fd-specific', testStripFinalNewline, 2, {stderr: false}, false, execa);31-test('stripFinalNewline: default with stdio[*], fd-specific', testStripFinalNewline, 3, {}, true, execa);32-test('stripFinalNewline: true with stdio[*], fd-specific', testStripFinalNewline, 3, {fd3: true}, true, execa);33-test('stripFinalNewline: false with stdio[*], fd-specific', testStripFinalNewline, 3, {fd3: false}, false, execa);34-test('stripFinalNewline: default with stdout, sync', testStripFinalNewline, 1, undefined, true, execaSync);35-test('stripFinalNewline: true with stdout, sync', testStripFinalNewline, 1, true, true, execaSync);36-test('stripFinalNewline: false with stdout, sync', testStripFinalNewline, 1, false, false, execaSync);37-test('stripFinalNewline: default with stderr, sync', testStripFinalNewline, 2, undefined, true, execaSync);38-test('stripFinalNewline: true with stderr, sync', testStripFinalNewline, 2, true, true, execaSync);39-test('stripFinalNewline: false with stderr, sync', testStripFinalNewline, 2, false, false, execaSync);40-test('stripFinalNewline: default with stdio[*], sync', testStripFinalNewline, 3, undefined, true, execaSync);41-test('stripFinalNewline: true with stdio[*], sync', testStripFinalNewline, 3, true, true, execaSync);42-test('stripFinalNewline: false with stdio[*], sync', testStripFinalNewline, 3, false, false, execaSync);43-test('stripFinalNewline: default with stdout, fd-specific, sync', testStripFinalNewline, 1, {}, true, execaSync);44-test('stripFinalNewline: true with stdout, fd-specific, sync', testStripFinalNewline, 1, {stdout: true}, true, execaSync);45-test('stripFinalNewline: false with stdout, fd-specific, sync', testStripFinalNewline, 1, {stdout: false}, false, execaSync);46-test('stripFinalNewline: default with stderr, fd-specific, sync', testStripFinalNewline, 2, {}, true, execaSync);47-test('stripFinalNewline: true with stderr, fd-specific, sync', testStripFinalNewline, 2, {stderr: true}, true, execaSync);48-test('stripFinalNewline: false with stderr, fd-specific, sync', testStripFinalNewline, 2, {stderr: false}, false, execaSync);49-test('stripFinalNewline: default with stdio[*], fd-specific, sync', testStripFinalNewline, 3, {}, true, execaSync);50-test('stripFinalNewline: true with stdio[*], fd-specific, sync', testStripFinalNewline, 3, {fd3: true}, true, execaSync);51-test('stripFinalNewline: false with stdio[*], fd-specific, sync', testStripFinalNewline, 3, {fd3: false}, false, execaSync);52-53-test('stripFinalNewline is not used in objectMode', async t => {54- const {stdout} = await execa('noop-fd.js', ['1', `${foobarString}\n`], {stripFinalNewline: true, stdout: noopGenerator(true, false, true)});55- t.deepEqual(stdout, [`${foobarString}\n`]);56-});deleted:test/stdio/encoding-final.js-129 removed
1-import {Buffer} from 'node:buffer';2-import {exec} from 'node:child_process';3-import {promisify} from 'node:util';4-import test from 'ava';5-import getStream from 'get-stream';6-import {execa, execaSync} from '../../index.js';7-import {setFixtureDir, FIXTURES_DIR} from '../helpers/fixtures-dir.js';8-import {fullStdio} from '../helpers/stdio.js';9-import {foobarString, foobarUint8Array, foobarHex} from '../helpers/input.js';10-11-const pExec = promisify(exec);12-13-setFixtureDir();14-15-const checkEncoding = async (t, encoding, fdNumber, execaMethod) => {16- const {stdio} = await execaMethod('noop-fd.js', [`${fdNumber}`, STRING_TO_ENCODE], {...fullStdio, encoding});17- compareValues(t, stdio[fdNumber], encoding);18-19- if (execaMethod !== execaSync) {20- const subprocess = execaMethod('noop-fd.js', [`${fdNumber}`, STRING_TO_ENCODE], {...fullStdio, encoding});21- const result = await getStream(subprocess.stdio[fdNumber]);22- compareValues(t, result, 'utf8');23- await subprocess;24- }25-26- if (fdNumber === 3) {27- return;28- }29-30- const {stdout, stderr} = await pExec(`node noop-fd.js ${fdNumber} ${STRING_TO_ENCODE}`, {encoding, cwd: FIXTURES_DIR});31- compareValues(t, fdNumber === 1 ? stdout : stderr, encoding);32-};33-34-const compareValues = (t, value, encoding) => {35- if (encoding === 'buffer') {36- t.true(ArrayBuffer.isView(value));37- t.true(BUFFER_TO_ENCODE.equals(value));38- } else {39- t.is(value, BUFFER_TO_ENCODE.toString(encoding));40- }41-};42-43-// This string gives different outputs with each encoding type44-const STRING_TO_ENCODE = '\u1000.';45-const BUFFER_TO_ENCODE = Buffer.from(STRING_TO_ENCODE);46-47-test('can pass encoding "buffer" to stdout', checkEncoding, 'buffer', 1, execa);48-test('can pass encoding "utf8" to stdout', checkEncoding, 'utf8', 1, execa);49-test('can pass encoding "utf16le" to stdout', checkEncoding, 'utf16le', 1, execa);50-test('can pass encoding "latin1" to stdout', checkEncoding, 'latin1', 1, execa);51-test('can pass encoding "ascii" to stdout', checkEncoding, 'ascii', 1, execa);52-test('can pass encoding "hex" to stdout', checkEncoding, 'hex', 1, execa);53-test('can pass encoding "base64" to stdout', checkEncoding, 'base64', 1, execa);54-test('can pass encoding "base64url" to stdout', checkEncoding, 'base64url', 1, execa);55-test('can pass encoding "buffer" to stderr', checkEncoding, 'buffer', 2, execa);56-test('can pass encoding "utf8" to stderr', checkEncoding, 'utf8', 2, execa);57-test('can pass encoding "utf16le" to stderr', checkEncoding, 'utf16le', 2, execa);58-test('can pass encoding "latin1" to stderr', checkEncoding, 'latin1', 2, execa);59-test('can pass encoding "ascii" to stderr', checkEncoding, 'ascii', 2, execa);60-test('can pass encoding "hex" to stderr', checkEncoding, 'hex', 2, execa);61-test('can pass encoding "base64" to stderr', checkEncoding, 'base64', 2, execa);62-test('can pass encoding "base64url" to stderr', checkEncoding, 'base64url', 2, execa);63-test('can pass encoding "buffer" to stdio[*]', checkEncoding, 'buffer', 3, execa);64-test('can pass encoding "utf8" to stdio[*]', checkEncoding, 'utf8', 3, execa);65-test('can pass encoding "utf16le" to stdio[*]', checkEncoding, 'utf16le', 3, execa);66-test('can pass encoding "latin1" to stdio[*]', checkEncoding, 'latin1', 3, execa);67-test('can pass encoding "ascii" to stdio[*]', checkEncoding, 'ascii', 3, execa);68-test('can pass encoding "hex" to stdio[*]', checkEncoding, 'hex', 3, execa);69-test('can pass encoding "base64" to stdio[*]', checkEncoding, 'base64', 3, execa);70-test('can pass encoding "base64url" to stdio[*]', checkEncoding, 'base64url', 3, execa);71-test('can pass encoding "buffer" to stdout - sync', checkEncoding, 'buffer', 1, execaSync);72-test('can pass encoding "utf8" to stdout - sync', checkEncoding, 'utf8', 1, execaSync);73-test('can pass encoding "utf16le" to stdout - sync', checkEncoding, 'utf16le', 1, execaSync);74-test('can pass encoding "latin1" to stdout - sync', checkEncoding, 'latin1', 1, execaSync);75-test('can pass encoding "ascii" to stdout - sync', checkEncoding, 'ascii', 1, execaSync);76-test('can pass encoding "hex" to stdout - sync', checkEncoding, 'hex', 1, execaSync);77-test('can pass encoding "base64" to stdout - sync', checkEncoding, 'base64', 1, execaSync);78-test('can pass encoding "base64url" to stdout - sync', checkEncoding, 'base64url', 1, execaSync);79-test('can pass encoding "buffer" to stderr - sync', checkEncoding, 'buffer', 2, execaSync);80-test('can pass encoding "utf8" to stderr - sync', checkEncoding, 'utf8', 2, execaSync);81-test('can pass encoding "utf16le" to stderr - sync', checkEncoding, 'utf16le', 2, execaSync);82-test('can pass encoding "latin1" to stderr - sync', checkEncoding, 'latin1', 2, execaSync);83-test('can pass encoding "ascii" to stderr - sync', checkEncoding, 'ascii', 2, execaSync);84-test('can pass encoding "hex" to stderr - sync', checkEncoding, 'hex', 2, execaSync);85-test('can pass encoding "base64" to stderr - sync', checkEncoding, 'base64', 2, execaSync);86-test('can pass encoding "base64url" to stderr - sync', checkEncoding, 'base64url', 2, execaSync);87-test('can pass encoding "buffer" to stdio[*] - sync', checkEncoding, 'buffer', 3, execaSync);88-test('can pass encoding "utf8" to stdio[*] - sync', checkEncoding, 'utf8', 3, execaSync);89-test('can pass encoding "utf16le" to stdio[*] - sync', checkEncoding, 'utf16le', 3, execaSync);90-test('can pass encoding "latin1" to stdio[*] - sync', checkEncoding, 'latin1', 3, execaSync);91-test('can pass encoding "ascii" to stdio[*] - sync', checkEncoding, 'ascii', 3, execaSync);92-test('can pass encoding "hex" to stdio[*] - sync', checkEncoding, 'hex', 3, execaSync);93-test('can pass encoding "base64" to stdio[*] - sync', checkEncoding, 'base64', 3, execaSync);94-test('can pass encoding "base64url" to stdio[*] - sync', checkEncoding, 'base64url', 3, execaSync);95-96-// eslint-disable-next-line max-params97-const testEncodingInput = async (t, input, expectedStdout, encoding, execaMethod) => {98- const {stdout} = await execaMethod('stdin.js', {input, encoding});99- t.deepEqual(stdout, expectedStdout);100-};101-102-test('Can use string input', testEncodingInput, foobarString, foobarString, 'utf8', execa);103-test('Can use Uint8Array input', testEncodingInput, foobarUint8Array, foobarString, 'utf8', execa);104-test('Can use string input, encoding "buffer"', testEncodingInput, foobarString, foobarUint8Array, 'buffer', execa);105-test('Can use Uint8Array input, encoding "buffer"', testEncodingInput, foobarUint8Array, foobarUint8Array, 'buffer', execa);106-test('Can use string input, encoding "hex"', testEncodingInput, foobarString, foobarHex, 'hex', execa);107-test('Can use Uint8Array input, encoding "hex"', testEncodingInput, foobarUint8Array, foobarHex, 'hex', execa);108-test('Can use string input, sync', testEncodingInput, foobarString, foobarString, 'utf8', execaSync);109-test('Can use Uint8Array input, sync', testEncodingInput, foobarUint8Array, foobarString, 'utf8', execaSync);110-test('Can use string input, encoding "buffer", sync', testEncodingInput, foobarString, foobarUint8Array, 'buffer', execaSync);111-test('Can use Uint8Array input, encoding "buffer", sync', testEncodingInput, foobarUint8Array, foobarUint8Array, 'buffer', execaSync);112-test('Can use string input, encoding "hex", sync', testEncodingInput, foobarString, foobarHex, 'hex', execaSync);113-test('Can use Uint8Array input, encoding "hex", sync', testEncodingInput, foobarUint8Array, foobarHex, 'hex', execaSync);114-115-const testSubprocessEncoding = (t, encoding) => {116- const subprocess = execa('empty.js', {...fullStdio, encoding});117- t.is(subprocess.stdout.readableEncoding, null);118- t.is(subprocess.stderr.readableEncoding, null);119- t.is(subprocess.stdio[3].readableEncoding, null);120-};121-122-test('Does not modify subprocess.std* encoding, "utf8"', testSubprocessEncoding, 'utf8');123-test('Does not modify subprocess.std* encoding, "utf16le"', testSubprocessEncoding, 'utf16le');124-test('Does not modify subprocess.std* encoding, "buffer"', testSubprocessEncoding, 'buffer');125-test('Does not modify subprocess.std* encoding, "hex"', testSubprocessEncoding, 'hex');126-test('Does not modify subprocess.std* encoding, "base64"', testSubprocessEncoding, 'base64');127-test('Does not modify subprocess.std* encoding, "base64url"', testSubprocessEncoding, 'base64url');128-test('Does not modify subprocess.std* encoding, "latin1"', testSubprocessEncoding, 'latin1');129-test('Does not modify subprocess.std* encoding, "ascii"', testSubprocessEncoding, 'ascii');deleted:test/stdio/encoding-ignored.js-92 removed
1-import process from 'node:process';2-import test from 'ava';3-import {execa, execaSync} from '../../index.js';4-import {setFixtureDir} from '../helpers/fixtures-dir.js';5-import {outputObjectGenerator, addNoopGenerator} from '../helpers/generator.js';6-import {foobarObject} from '../helpers/input.js';7-8-setFixtureDir();9-10-const testObjectMode = async (t, addNoopTransform, execaMethod) => {11- const {stdout} = await execaMethod('noop.js', {12- stdout: addNoopGenerator(outputObjectGenerator(), addNoopTransform, true),13- encoding: 'base64',14- });15- t.deepEqual(stdout, [foobarObject]);16-};17-18-test('Other encodings work with transforms that return objects', testObjectMode, false, execa);19-test('Other encodings work with transforms that return objects, noop transform', testObjectMode, true, execa);20-test('Other encodings work with transforms that return objects, sync', testObjectMode, false, execaSync);21-test('Other encodings work with transforms that return objects, noop transform, sync', testObjectMode, true, execaSync);22-23-// eslint-disable-next-line max-params24-const testIgnoredEncoding = async (t, stdoutOption, isUndefined, options, execaMethod) => {25- const {stdout} = await execaMethod('empty.js', {stdout: stdoutOption, ...options});26- t.is(stdout === undefined, isUndefined);27-};28-29-const base64Options = {encoding: 'base64'};30-const linesOptions = {lines: true};31-test('Is ignored with other encodings and "ignore"', testIgnoredEncoding, 'ignore', true, base64Options, execa);32-test('Is ignored with other encodings and ["ignore"]', testIgnoredEncoding, ['ignore'], true, base64Options, execa);33-test('Is ignored with other encodings and "ipc"', testIgnoredEncoding, 'ipc', true, base64Options, execa);34-test('Is ignored with other encodings and ["ipc"]', testIgnoredEncoding, ['ipc'], true, base64Options, execa);35-test('Is ignored with other encodings and "inherit"', testIgnoredEncoding, 'inherit', true, base64Options, execa);36-test('Is ignored with other encodings and ["inherit"]', testIgnoredEncoding, ['inherit'], true, base64Options, execa);37-test('Is ignored with other encodings and 1', testIgnoredEncoding, 1, true, base64Options, execa);38-test('Is ignored with other encodings and [1]', testIgnoredEncoding, [1], true, base64Options, execa);39-test('Is ignored with other encodings and process.stdout', testIgnoredEncoding, process.stdout, true, base64Options, execa);40-test('Is ignored with other encodings and [process.stdout]', testIgnoredEncoding, [process.stdout], true, base64Options, execa);41-test('Is not ignored with other encodings and "pipe"', testIgnoredEncoding, 'pipe', false, base64Options, execa);42-test('Is not ignored with other encodings and ["pipe"]', testIgnoredEncoding, ['pipe'], false, base64Options, execa);43-test('Is not ignored with other encodings and "overlapped"', testIgnoredEncoding, 'overlapped', false, base64Options, execa);44-test('Is not ignored with other encodings and ["overlapped"]', testIgnoredEncoding, ['overlapped'], false, base64Options, execa);45-test('Is not ignored with other encodings and ["inherit", "pipe"]', testIgnoredEncoding, ['inherit', 'pipe'], false, base64Options, execa);46-test('Is not ignored with other encodings and undefined', testIgnoredEncoding, undefined, false, base64Options, execa);47-test('Is not ignored with other encodings and null', testIgnoredEncoding, null, false, base64Options, execa);48-test('Is ignored with "lines: true" and "ignore"', testIgnoredEncoding, 'ignore', true, linesOptions, execa);49-test('Is ignored with "lines: true" and ["ignore"]', testIgnoredEncoding, ['ignore'], true, linesOptions, execa);50-test('Is ignored with "lines: true" and "ipc"', testIgnoredEncoding, 'ipc', true, linesOptions, execa);51-test('Is ignored with "lines: true" and ["ipc"]', testIgnoredEncoding, ['ipc'], true, linesOptions, execa);52-test('Is ignored with "lines: true" and "inherit"', testIgnoredEncoding, 'inherit', true, linesOptions, execa);53-test('Is ignored with "lines: true" and ["inherit"]', testIgnoredEncoding, ['inherit'], true, linesOptions, execa);54-test('Is ignored with "lines: true" and 1', testIgnoredEncoding, 1, true, linesOptions, execa);55-test('Is ignored with "lines: true" and [1]', testIgnoredEncoding, [1], true, linesOptions, execa);56-test('Is ignored with "lines: true" and process.stdout', testIgnoredEncoding, process.stdout, true, linesOptions, execa);57-test('Is ignored with "lines: true" and [process.stdout]', testIgnoredEncoding, [process.stdout], true, linesOptions, execa);58-test('Is not ignored with "lines: true" and "pipe"', testIgnoredEncoding, 'pipe', false, linesOptions, execa);59-test('Is not ignored with "lines: true" and ["pipe"]', testIgnoredEncoding, ['pipe'], false, linesOptions, execa);60-test('Is not ignored with "lines: true" and "overlapped"', testIgnoredEncoding, 'overlapped', false, linesOptions, execa);61-test('Is not ignored with "lines: true" and ["overlapped"]', testIgnoredEncoding, ['overlapped'], false, linesOptions, execa);62-test('Is not ignored with "lines: true" and ["inherit", "pipe"]', testIgnoredEncoding, ['inherit', 'pipe'], false, linesOptions, execa);63-test('Is not ignored with "lines: true" and undefined', testIgnoredEncoding, undefined, false, linesOptions, execa);64-test('Is not ignored with "lines: true" and null', testIgnoredEncoding, null, false, linesOptions, execa);65-test('Is ignored with "lines: true", other encodings and "ignore"', testIgnoredEncoding, 'ignore', true, {...base64Options, ...linesOptions}, execa);66-test('Is not ignored with "lines: true", other encodings and "pipe"', testIgnoredEncoding, 'pipe', false, {...base64Options, ...linesOptions}, execa);67-test('Is ignored with other encodings and "ignore", sync', testIgnoredEncoding, 'ignore', true, base64Options, execaSync);68-test('Is ignored with other encodings and ["ignore"], sync', testIgnoredEncoding, ['ignore'], true, base64Options, execaSync);69-test('Is ignored with other encodings and "inherit", sync', testIgnoredEncoding, 'inherit', true, base64Options, execaSync);70-test('Is ignored with other encodings and ["inherit"], sync', testIgnoredEncoding, ['inherit'], true, base64Options, execaSync);71-test('Is ignored with other encodings and 1, sync', testIgnoredEncoding, 1, true, base64Options, execaSync);72-test('Is ignored with other encodings and [1], sync', testIgnoredEncoding, [1], true, base64Options, execaSync);73-test('Is ignored with other encodings and process.stdout, sync', testIgnoredEncoding, process.stdout, true, base64Options, execaSync);74-test('Is ignored with other encodings and [process.stdout], sync', testIgnoredEncoding, [process.stdout], true, base64Options, execaSync);75-test('Is not ignored with other encodings and "pipe", sync', testIgnoredEncoding, 'pipe', false, base64Options, execaSync);76-test('Is not ignored with other encodings and ["pipe"], sync', testIgnoredEncoding, ['pipe'], false, base64Options, execaSync);77-test('Is not ignored with other encodings and undefined, sync', testIgnoredEncoding, undefined, false, base64Options, execaSync);78-test('Is not ignored with other encodings and null, sync', testIgnoredEncoding, null, false, base64Options, execaSync);79-test('Is ignored with "lines: true" and "ignore", sync', testIgnoredEncoding, 'ignore', true, linesOptions, execaSync);80-test('Is ignored with "lines: true" and ["ignore"], sync', testIgnoredEncoding, ['ignore'], true, linesOptions, execaSync);81-test('Is ignored with "lines: true" and "inherit", sync', testIgnoredEncoding, 'inherit', true, linesOptions, execaSync);82-test('Is ignored with "lines: true" and ["inherit"], sync', testIgnoredEncoding, ['inherit'], true, linesOptions, execaSync);83-test('Is ignored with "lines: true" and 1, sync', testIgnoredEncoding, 1, true, linesOptions, execaSync);84-test('Is ignored with "lines: true" and [1], sync', testIgnoredEncoding, [1], true, linesOptions, execaSync);85-test('Is ignored with "lines: true" and process.stdout, sync', testIgnoredEncoding, process.stdout, true, linesOptions, execaSync);86-test('Is ignored with "lines: true" and [process.stdout], sync', testIgnoredEncoding, [process.stdout], true, linesOptions, execaSync);87-test('Is not ignored with "lines: true" and "pipe", sync', testIgnoredEncoding, 'pipe', false, linesOptions, execaSync);88-test('Is not ignored with "lines: true" and ["pipe"], sync', testIgnoredEncoding, ['pipe'], false, linesOptions, execaSync);89-test('Is not ignored with "lines: true" and undefined, sync', testIgnoredEncoding, undefined, false, linesOptions, execaSync);90-test('Is not ignored with "lines: true" and null, sync', testIgnoredEncoding, null, false, linesOptions, execaSync);91-test('Is ignored with "lines: true", other encodings and "ignore", sync', testIgnoredEncoding, 'ignore', true, {...base64Options, ...linesOptions}, execaSync);92-test('Is not ignored with "lines: true", other encodings and "pipe", sync', testIgnoredEncoding, 'pipe', false, {...base64Options, ...linesOptions}, execaSync);deleted:test/stdio/encoding-multibyte.js-73 removed
1-import test from 'ava';2-import {execa, execaSync} from '../../index.js';3-import {setFixtureDir} from '../helpers/fixtures-dir.js';4-import {noopGenerator, getOutputsGenerator, addNoopGenerator} from '../helpers/generator.js';5-import {multibyteChar, multibyteString, multibyteUint8Array, breakingLength, brokenSymbol} from '../helpers/encoding.js';6-7-setFixtureDir();8-9-const foobarArray = ['fo', 'ob', 'ar', '..'];10-11-const testMultibyteCharacters = async (t, objectMode, addNoopTransform, execaMethod) => {12- const {stdout} = await execaMethod('noop.js', {13- stdout: addNoopGenerator(getOutputsGenerator(foobarArray)(objectMode, true), addNoopTransform, objectMode),14- encoding: 'base64',15- });16- if (objectMode) {17- t.deepEqual(stdout, foobarArray);18- } else {19- t.is(stdout, btoa(foobarArray.join('')));20- }21-};22-23-test('Handle multibyte characters', testMultibyteCharacters, false, false, execa);24-test('Handle multibyte characters, noop transform', testMultibyteCharacters, false, true, execa);25-test('Handle multibyte characters, with objectMode', testMultibyteCharacters, true, false, execa);26-test('Handle multibyte characters, with objectMode, noop transform', testMultibyteCharacters, true, true, execa);27-test('Handle multibyte characters, sync', testMultibyteCharacters, false, false, execaSync);28-test('Handle multibyte characters, noop transform, sync', testMultibyteCharacters, false, true, execaSync);29-test('Handle multibyte characters, with objectMode, sync', testMultibyteCharacters, true, false, execaSync);30-test('Handle multibyte characters, with objectMode, noop transform, sync', testMultibyteCharacters, true, true, execaSync);31-32-const testMultibyte = async (t, objectMode, execaMethod) => {33- const {stdout} = await execaMethod('stdin.js', {34- stdin: [35- [multibyteUint8Array.slice(0, breakingLength), multibyteUint8Array.slice(breakingLength)],36- noopGenerator(objectMode, true),37- ],38- });39- t.is(stdout, multibyteString);40-};41-42-test('Generator handles multibyte characters with Uint8Array', testMultibyte, false, execa);43-test('Generator handles multibyte characters with Uint8Array, objectMode', testMultibyte, true, execa);44-test('Generator handles multibyte characters with Uint8Array, sync', testMultibyte, false, execaSync);45-test('Generator handles multibyte characters with Uint8Array, objectMode, sync', testMultibyte, true, execaSync);46-47-const testMultibytePartial = async (t, objectMode, execaMethod) => {48- const {stdout} = await execaMethod('stdin.js', {49- stdin: [50- [multibyteUint8Array.slice(0, breakingLength)],51- noopGenerator(objectMode, true),52- ],53- });54- t.is(stdout, `${multibyteChar}${brokenSymbol}`);55-};56-57-test('Generator handles partial multibyte characters with Uint8Array', testMultibytePartial, false, execa);58-test('Generator handles partial multibyte characters with Uint8Array, objectMode', testMultibytePartial, true, execa);59-test('Generator handles partial multibyte characters with Uint8Array, sync', testMultibytePartial, false, execaSync);60-test('Generator handles partial multibyte characters with Uint8Array, objectMode, sync', testMultibytePartial, true, execaSync);61-62-const testMultibytePartialOutput = async (t, execaMethod) => {63- const {stdout} = await execaMethod('noop.js', {64- stdout: getOutputsGenerator([65- multibyteUint8Array.slice(0, breakingLength),66- multibyteUint8Array.slice(breakingLength),67- ])(false, true),68- });69- t.is(stdout, multibyteString);70-};71-72-test('Generator handles output multibyte characters with Uint8Array', testMultibytePartialOutput, execa);73-test('Generator handles output multibyte characters with Uint8Array, sync', testMultibytePartialOutput, execaSync);deleted:test/stdio/encoding-transform.js-172 removed
1-import {Buffer} from 'node:buffer';2-import test from 'ava';3-import {execa, execaSync} from '../../index.js';4-import {setFixtureDir} from '../helpers/fixtures-dir.js';5-import {getStdio} from '../helpers/stdio.js';6-import {foobarString, foobarUint8Array, foobarBuffer, foobarObject} from '../helpers/input.js';7-import {noopGenerator, getOutputGenerator} from '../helpers/generator.js';8-9-setFixtureDir();10-11-const getTypeofGenerator = lines => (objectMode, binary) => ({12- * transform(line) {13- lines.push(Object.prototype.toString.call(line));14- yield '';15- },16- objectMode,17- binary,18-});19-20-const assertTypeofChunk = (t, lines, expectedType) => {21- t.deepEqual(lines, [`[object ${expectedType}]`]);22-};23-24-// eslint-disable-next-line max-params25-const testGeneratorFirstEncoding = async (t, input, encoding, expectedType, objectMode, binary) => {26- const lines = [];27- const subprocess = execa('stdin.js', {stdin: getTypeofGenerator(lines)(objectMode, binary), encoding});28- subprocess.stdin.end(input);29- await subprocess;30- assertTypeofChunk(t, lines, expectedType);31-};32-33-test('First generator argument is string with default encoding, with string writes', testGeneratorFirstEncoding, foobarString, 'utf8', 'String', false, undefined);34-test('First generator argument is string with default encoding, with Buffer writes', testGeneratorFirstEncoding, foobarBuffer, 'utf8', 'String', false, undefined);35-test('First generator argument is string with default encoding, with Uint8Array writes', testGeneratorFirstEncoding, foobarUint8Array, 'utf8', 'String', false, undefined);36-test('First generator argument is string with default encoding, with string writes, "binary: false"', testGeneratorFirstEncoding, foobarString, 'utf8', 'String', false, false);37-test('First generator argument is Uint8Array with default encoding, with string writes, "binary: true"', testGeneratorFirstEncoding, foobarString, 'utf8', 'Uint8Array', false, true);38-test('First generator argument is string with encoding "utf16le", with string writes', testGeneratorFirstEncoding, foobarString, 'utf16le', 'String', false, undefined);39-test('First generator argument is string with encoding "utf16le", with Buffer writes', testGeneratorFirstEncoding, foobarBuffer, 'utf16le', 'String', false, undefined);40-test('First generator argument is string with encoding "utf16le", with Uint8Array writes', testGeneratorFirstEncoding, foobarUint8Array, 'utf16le', 'String', false, undefined);41-test('First generator argument is string with encoding "utf16le", with string writes, "binary: false"', testGeneratorFirstEncoding, foobarString, 'utf16le', 'String', false, false);42-test('First generator argument is Uint8Array with encoding "utf16le", with string writes, "binary: true"', testGeneratorFirstEncoding, foobarString, 'utf16le', 'Uint8Array', false, true);43-test('First generator argument is Uint8Array with encoding "buffer", with string writes', testGeneratorFirstEncoding, foobarString, 'buffer', 'Uint8Array', false, undefined);44-test('First generator argument is Uint8Array with encoding "buffer", with Buffer writes', testGeneratorFirstEncoding, foobarBuffer, 'buffer', 'Uint8Array', false, undefined);45-test('First generator argument is Uint8Array with encoding "buffer", with Uint8Array writes', testGeneratorFirstEncoding, foobarUint8Array, 'buffer', 'Uint8Array', false, undefined);46-test('First generator argument is Uint8Array with encoding "buffer", with string writes, "binary: false"', testGeneratorFirstEncoding, foobarString, 'buffer', 'Uint8Array', false, false);47-test('First generator argument is Uint8Array with encoding "buffer", with string writes, "binary: true"', testGeneratorFirstEncoding, foobarString, 'buffer', 'Uint8Array', false, true);48-test('First generator argument is Uint8Array with encoding "hex", with string writes', testGeneratorFirstEncoding, foobarString, 'hex', 'Uint8Array', false, undefined);49-test('First generator argument is Uint8Array with encoding "hex", with Buffer writes', testGeneratorFirstEncoding, foobarBuffer, 'hex', 'Uint8Array', false, undefined);50-test('First generator argument is Uint8Array with encoding "hex", with Uint8Array writes', testGeneratorFirstEncoding, foobarUint8Array, 'hex', 'Uint8Array', false, undefined);51-test('First generator argument is Uint8Array with encoding "hex", with string writes, "binary: false"', testGeneratorFirstEncoding, foobarString, 'hex', 'Uint8Array', false, false);52-test('First generator argument is Uint8Array with encoding "hex", with string writes, "binary: true"', testGeneratorFirstEncoding, foobarString, 'hex', 'Uint8Array', false, true);53-test('First generator argument can be string with objectMode', testGeneratorFirstEncoding, foobarString, 'utf8', 'String', true, undefined);54-test('First generator argument can be string with objectMode, "binary: false"', testGeneratorFirstEncoding, foobarString, 'utf8', 'String', true, false);55-test('First generator argument can be string with objectMode, "binary: true"', testGeneratorFirstEncoding, foobarString, 'utf8', 'String', true, true);56-test('First generator argument can be objects with objectMode', testGeneratorFirstEncoding, foobarObject, 'utf8', 'Object', true, undefined);57-test('First generator argument can be objects with objectMode, "binary: false"', testGeneratorFirstEncoding, foobarObject, 'utf8', 'Object', true, false);58-test('First generator argument can be objects with objectMode, "binary: true"', testGeneratorFirstEncoding, foobarObject, 'utf8', 'Object', true, true);59-60-// eslint-disable-next-line max-params61-const testGeneratorFirstEncodingSync = (t, input, encoding, expectedType, objectMode, binary) => {62- const lines = [];63- execaSync('stdin.js', {stdin: [[input], getTypeofGenerator(lines)(objectMode, binary)], encoding});64- assertTypeofChunk(t, lines, expectedType);65-};66-67-test('First generator argument is string with default encoding, with string writes, sync', testGeneratorFirstEncodingSync, foobarString, 'utf8', 'String', false, undefined);68-test('First generator argument is string with default encoding, with Uint8Array writes, sync', testGeneratorFirstEncodingSync, foobarUint8Array, 'utf8', 'String', false, undefined);69-test('First generator argument is string with default encoding, with string writes, "binary: false", sync', testGeneratorFirstEncodingSync, foobarString, 'utf8', 'String', false, false);70-test('First generator argument is Uint8Array with default encoding, with string writes, "binary: true", sync', testGeneratorFirstEncodingSync, foobarString, 'utf8', 'Uint8Array', false, true);71-test('First generator argument is string with encoding "utf16le", with string writes, sync', testGeneratorFirstEncodingSync, foobarString, 'utf16le', 'String', false, undefined);72-test('First generator argument is string with encoding "utf16le", with Uint8Array writes, sync', testGeneratorFirstEncodingSync, foobarUint8Array, 'utf16le', 'String', false, undefined);73-test('First generator argument is string with encoding "utf16le", with string writes, "binary: false", sync', testGeneratorFirstEncodingSync, foobarString, 'utf16le', 'String', false, false);74-test('First generator argument is Uint8Array with encoding "utf16le", with string writes, "binary: true", sync', testGeneratorFirstEncodingSync, foobarString, 'utf16le', 'Uint8Array', false, true);75-test('First generator argument is Uint8Array with encoding "buffer", with string writes, sync', testGeneratorFirstEncodingSync, foobarString, 'buffer', 'Uint8Array', false, undefined);76-test('First generator argument is Uint8Array with encoding "buffer", with Uint8Array writes, sync', testGeneratorFirstEncodingSync, foobarUint8Array, 'buffer', 'Uint8Array', false, undefined);77-test('First generator argument is Uint8Array with encoding "buffer", with string writes, "binary: false", sync', testGeneratorFirstEncodingSync, foobarString, 'buffer', 'Uint8Array', false, false);78-test('First generator argument is Uint8Array with encoding "buffer", with string writes, "binary: true", sync', testGeneratorFirstEncodingSync, foobarString, 'buffer', 'Uint8Array', false, true);79-test('First generator argument is Uint8Array with encoding "hex", with string writes, sync', testGeneratorFirstEncodingSync, foobarString, 'hex', 'Uint8Array', false, undefined);80-test('First generator argument is Uint8Array with encoding "hex", with Uint8Array writes, sync', testGeneratorFirstEncodingSync, foobarUint8Array, 'hex', 'Uint8Array', false, undefined);81-test('First generator argument is Uint8Array with encoding "hex", with string writes, "binary: false", sync', testGeneratorFirstEncodingSync, foobarString, 'hex', 'Uint8Array', false, false);82-test('First generator argument is Uint8Array with encoding "hex", with string writes, "binary: true", sync', testGeneratorFirstEncodingSync, foobarString, 'hex', 'Uint8Array', false, true);83-test('First generator argument can be string with objectMode, sync', testGeneratorFirstEncodingSync, foobarString, 'utf8', 'String', true, undefined);84-test('First generator argument can be string with objectMode, "binary: false", sync', testGeneratorFirstEncodingSync, foobarString, 'utf8', 'String', true, false);85-test('First generator argument can be string with objectMode, "binary: true", sync', testGeneratorFirstEncodingSync, foobarString, 'utf8', 'String', true, true);86-test('First generator argument can be objects with objectMode, sync', testGeneratorFirstEncodingSync, foobarObject, 'utf8', 'Object', true, undefined);87-test('First generator argument can be objects with objectMode, "binary: false", sync', testGeneratorFirstEncodingSync, foobarObject, 'utf8', 'Object', true, false);88-test('First generator argument can be objects with objectMode, "binary: true", sync', testGeneratorFirstEncodingSync, foobarObject, 'utf8', 'Object', true, true);89-90-const testEncodingIgnored = async (t, encoding) => {91- const input = Buffer.from(foobarString).toString(encoding);92- const subprocess = execa('stdin.js', {stdin: noopGenerator(true)});93- subprocess.stdin.end(input, encoding);94- const {stdout} = await subprocess;95- t.is(stdout, input);96-};97-98-test('Write call encoding "utf8" is ignored with objectMode', testEncodingIgnored, 'utf8');99-test('Write call encoding "utf16le" is ignored with objectMode', testEncodingIgnored, 'utf16le');100-test('Write call encoding "hex" is ignored with objectMode', testEncodingIgnored, 'hex');101-test('Write call encoding "base64" is ignored with objectMode', testEncodingIgnored, 'base64');102-103-// eslint-disable-next-line max-params104-const testGeneratorNextEncoding = async (t, input, encoding, firstObjectMode, secondObjectMode, expectedType, execaMethod) => {105- const lines = [];106- await execaMethod('noop.js', ['other'], {107- stdout: [108- getOutputGenerator(input)(firstObjectMode),109- getTypeofGenerator(lines)(secondObjectMode),110- ],111- encoding,112- });113- assertTypeofChunk(t, lines, expectedType);114-};115-116-test('Next generator argument is string with default encoding, with string writes', testGeneratorNextEncoding, foobarString, 'utf8', false, false, 'String', execa);117-test('Next generator argument is string with default encoding, with string writes, objectMode first', testGeneratorNextEncoding, foobarString, 'utf8', true, false, 'String', execa);118-test('Next generator argument is string with default encoding, with string writes, objectMode both', testGeneratorNextEncoding, foobarString, 'utf8', true, true, 'String', execa);119-test('Next generator argument is string with default encoding, with Uint8Array writes', testGeneratorNextEncoding, foobarUint8Array, 'utf8', false, false, 'String', execa);120-test('Next generator argument is Uint8Array with default encoding, with Uint8Array writes, objectMode first', testGeneratorNextEncoding, foobarUint8Array, 'utf8', true, false, 'Uint8Array', execa);121-test('Next generator argument is string with default encoding, with Uint8Array writes, objectMode both', testGeneratorNextEncoding, foobarUint8Array, 'utf8', true, true, 'Uint8Array', execa);122-test('Next generator argument is string with encoding "utf16le", with string writes', testGeneratorNextEncoding, foobarString, 'utf16le', false, false, 'String', execa);123-test('Next generator argument is string with encoding "utf16le",, with string writes, objectMode first', testGeneratorNextEncoding, foobarString, 'utf16le', true, false, 'String', execa);124-test('Next generator argument is string with encoding "utf16le",, with string writes, objectMode both', testGeneratorNextEncoding, foobarString, 'utf16le', true, true, 'String', execa);125-test('Next generator argument is string with encoding "utf16le",, with Uint8Array writes', testGeneratorNextEncoding, foobarUint8Array, 'utf16le', false, false, 'String', execa);126-test('Next generator argument is Uint8Array with encoding "utf16le",, with Uint8Array writes, objectMode first', testGeneratorNextEncoding, foobarUint8Array, 'utf16le', true, false, 'Uint8Array', execa);127-test('Next generator argument is string with encoding "utf16le",, with Uint8Array writes, objectMode both', testGeneratorNextEncoding, foobarUint8Array, 'utf16le', true, true, 'Uint8Array', execa);128-test('Next generator argument is Uint8Array with encoding "buffer", with string writes', testGeneratorNextEncoding, foobarString, 'buffer', false, false, 'Uint8Array', execa);129-test('Next generator argument is string with encoding "buffer", with string writes, objectMode first', testGeneratorNextEncoding, foobarString, 'buffer', true, false, 'String', execa);130-test('Next generator argument is string with encoding "buffer", with string writes, objectMode both', testGeneratorNextEncoding, foobarString, 'buffer', true, true, 'String', execa);131-test('Next generator argument is Uint8Array with encoding "buffer", with Uint8Array writes', testGeneratorNextEncoding, foobarUint8Array, 'buffer', false, false, 'Uint8Array', execa);132-test('Next generator argument is Uint8Array with encoding "buffer", with Uint8Array writes, objectMode first', testGeneratorNextEncoding, foobarUint8Array, 'buffer', true, false, 'Uint8Array', execa);133-test('Next generator argument is Uint8Array with encoding "buffer", with Uint8Array writes, objectMode both', testGeneratorNextEncoding, foobarUint8Array, 'buffer', true, true, 'Uint8Array', execa);134-test('Next generator argument is Uint8Array with encoding "hex", with string writes', testGeneratorNextEncoding, foobarString, 'hex', false, false, 'Uint8Array', execa);135-test('Next generator argument is Uint8Array with encoding "hex", with Uint8Array writes', testGeneratorNextEncoding, foobarUint8Array, 'hex', false, false, 'Uint8Array', execa);136-test('Next generator argument is object with default encoding, with object writes, objectMode first', testGeneratorNextEncoding, foobarObject, 'utf8', true, false, 'Object', execa);137-test('Next generator argument is object with default encoding, with object writes, objectMode both', testGeneratorNextEncoding, foobarObject, 'utf8', true, true, 'Object', execa);138-test('Next generator argument is string with default encoding, with string writes, sync', testGeneratorNextEncoding, foobarString, 'utf8', false, false, 'String', execaSync);139-test('Next generator argument is string with default encoding, with string writes, objectMode first, sync', testGeneratorNextEncoding, foobarString, 'utf8', true, false, 'String', execaSync);140-test('Next generator argument is string with default encoding, with string writes, objectMode both, sync', testGeneratorNextEncoding, foobarString, 'utf8', true, true, 'String', execaSync);141-test('Next generator argument is string with default encoding, with Uint8Array writes, sync', testGeneratorNextEncoding, foobarUint8Array, 'utf8', false, false, 'String', execaSync);142-test('Next generator argument is Uint8Array with default encoding, with Uint8Array writes, objectMode first, sync', testGeneratorNextEncoding, foobarUint8Array, 'utf8', true, false, 'Uint8Array', execaSync);143-test('Next generator argument is string with default encoding, with Uint8Array writes, objectMode both, sync', testGeneratorNextEncoding, foobarUint8Array, 'utf8', true, true, 'Uint8Array', execaSync);144-test('Next generator argument is string with encoding "utf16le", with string writes, sync', testGeneratorNextEncoding, foobarString, 'utf16le', false, false, 'String', execaSync);145-test('Next generator argument is string with encoding "utf16le",, with string writes, objectMode first, sync', testGeneratorNextEncoding, foobarString, 'utf16le', true, false, 'String', execaSync);146-test('Next generator argument is string with encoding "utf16le",, with string writes, objectMode both, sync', testGeneratorNextEncoding, foobarString, 'utf16le', true, true, 'String', execaSync);147-test('Next generator argument is string with encoding "utf16le",, with Uint8Array writes, sync', testGeneratorNextEncoding, foobarUint8Array, 'utf16le', false, false, 'String', execaSync);148-test('Next generator argument is Uint8Array with encoding "utf16le",, with Uint8Array writes, objectMode first, sync', testGeneratorNextEncoding, foobarUint8Array, 'utf16le', true, false, 'Uint8Array', execaSync);149-test('Next generator argument is string with encoding "utf16le",, with Uint8Array writes, objectMode both, sync', testGeneratorNextEncoding, foobarUint8Array, 'utf16le', true, true, 'Uint8Array', execaSync);150-test('Next generator argument is Uint8Array with encoding "buffer", with string writes, sync', testGeneratorNextEncoding, foobarString, 'buffer', false, false, 'Uint8Array', execaSync);151-test('Next generator argument is string with encoding "buffer", with string writes, objectMode first, sync', testGeneratorNextEncoding, foobarString, 'buffer', true, false, 'String', execaSync);152-test('Next generator argument is string with encoding "buffer", with string writes, objectMode both, sync', testGeneratorNextEncoding, foobarString, 'buffer', true, true, 'String', execaSync);153-test('Next generator argument is Uint8Array with encoding "buffer", with Uint8Array writes, sync', testGeneratorNextEncoding, foobarUint8Array, 'buffer', false, false, 'Uint8Array', execaSync);154-test('Next generator argument is Uint8Array with encoding "buffer", with Uint8Array writes, objectMode first, sync', testGeneratorNextEncoding, foobarUint8Array, 'buffer', true, false, 'Uint8Array', execaSync);155-test('Next generator argument is Uint8Array with encoding "buffer", with Uint8Array writes, objectMode both, sync', testGeneratorNextEncoding, foobarUint8Array, 'buffer', true, true, 'Uint8Array', execaSync);156-test('Next generator argument is Uint8Array with encoding "hex", with string writes, sync', testGeneratorNextEncoding, foobarString, 'hex', false, false, 'Uint8Array', execaSync);157-test('Next generator argument is Uint8Array with encoding "hex", with Uint8Array writes, sync', testGeneratorNextEncoding, foobarUint8Array, 'hex', false, false, 'Uint8Array', execaSync);158-test('Next generator argument is object with default encoding, with object writes, objectMode first, sync', testGeneratorNextEncoding, foobarObject, 'utf8', true, false, 'Object', execaSync);159-test('Next generator argument is object with default encoding, with object writes, objectMode both, sync', testGeneratorNextEncoding, foobarObject, 'utf8', true, true, 'Object', execaSync);160-161-const testFirstOutputGeneratorArgument = async (t, fdNumber, execaMethod) => {162- const lines = [];163- await execaMethod('noop-fd.js', [`${fdNumber}`], getStdio(fdNumber, getTypeofGenerator(lines)(true)));164- assertTypeofChunk(t, lines, 'String');165-};166-167-test('The first generator with result.stdout does not receive an object argument even in objectMode', testFirstOutputGeneratorArgument, 1, execa);168-test('The first generator with result.stderr does not receive an object argument even in objectMode', testFirstOutputGeneratorArgument, 2, execa);169-test('The first generator with result.stdio[*] does not receive an object argument even in objectMode', testFirstOutputGeneratorArgument, 3, execa);170-test('The first generator with result.stdout does not receive an object argument even in objectMode, sync', testFirstOutputGeneratorArgument, 1, execaSync);171-test('The first generator with result.stderr does not receive an object argument even in objectMode, sync', testFirstOutputGeneratorArgument, 2, execaSync);172-test('The first generator with result.stdio[*] does not receive an object argument even in objectMode, sync', testFirstOutputGeneratorArgument, 3, execaSync);deleted:test/stdio/generator-return.js-150 removed
1-import {Buffer} from 'node:buffer';2-import test from 'ava';3-import {execa, execaSync} from '../../index.js';4-import {setFixtureDir} from '../helpers/fixtures-dir.js';5-import {foobarString, foobarUint8Array} from '../helpers/input.js';6-import {getOutputGenerator, convertTransformToFinal} from '../helpers/generator.js';7-8-setFixtureDir();9-10-// eslint-disable-next-line max-params11-const testGeneratorReturnType = async (t, input, encoding, reject, objectMode, final, execaMethod) => {12- const fixtureName = reject ? 'noop-fd.js' : 'noop-fail.js';13- const {stdout} = await execaMethod(fixtureName, ['1', foobarString], {14- stdout: convertTransformToFinal(getOutputGenerator(input)(objectMode, true), final),15- encoding,16- reject,17- });18- const typeofChunk = Array.isArray(stdout) ? stdout[0] : stdout;19- const output = Buffer.from(typeofChunk, encoding === 'buffer' || objectMode ? undefined : encoding).toString();20- t.is(output, foobarString);21-};22-23-test('Generator can return string with default encoding', testGeneratorReturnType, foobarString, 'utf8', true, false, false, execa);24-test('Generator can return Uint8Array with default encoding', testGeneratorReturnType, foobarUint8Array, 'utf8', true, false, false, execa);25-test('Generator can return string with encoding "utf16le"', testGeneratorReturnType, foobarString, 'utf16le', true, false, false, execa);26-test('Generator can return Uint8Array with encoding "utf16le"', testGeneratorReturnType, foobarUint8Array, 'utf16le', true, false, false, execa);27-test('Generator can return string with encoding "buffer"', testGeneratorReturnType, foobarString, 'buffer', true, false, false, execa);28-test('Generator can return Uint8Array with encoding "buffer"', testGeneratorReturnType, foobarUint8Array, 'buffer', true, false, false, execa);29-test('Generator can return string with encoding "hex"', testGeneratorReturnType, foobarString, 'hex', true, false, false, execa);30-test('Generator can return Uint8Array with encoding "hex"', testGeneratorReturnType, foobarUint8Array, 'hex', true, false, false, execa);31-test('Generator can return string with default encoding, failure', testGeneratorReturnType, foobarString, 'utf8', false, false, false, execa);32-test('Generator can return Uint8Array with default encoding, failure', testGeneratorReturnType, foobarUint8Array, 'utf8', false, false, false, execa);33-test('Generator can return string with encoding "utf16le", failure', testGeneratorReturnType, foobarString, 'utf16le', false, false, false, execa);34-test('Generator can return Uint8Array with encoding "utf16le", failure', testGeneratorReturnType, foobarUint8Array, 'utf16le', false, false, false, execa);35-test('Generator can return string with encoding "buffer", failure', testGeneratorReturnType, foobarString, 'buffer', false, false, false, execa);36-test('Generator can return Uint8Array with encoding "buffer", failure', testGeneratorReturnType, foobarUint8Array, 'buffer', false, false, false, execa);37-test('Generator can return string with encoding "hex", failure', testGeneratorReturnType, foobarString, 'hex', false, false, false, execa);38-test('Generator can return Uint8Array with encoding "hex", failure', testGeneratorReturnType, foobarUint8Array, 'hex', false, false, false, execa);39-test('Generator can return string with default encoding, objectMode', testGeneratorReturnType, foobarString, 'utf8', true, true, false, execa);40-test('Generator can return Uint8Array with default encoding, objectMode', testGeneratorReturnType, foobarUint8Array, 'utf8', true, true, false, execa);41-test('Generator can return string with encoding "utf16le", objectMode', testGeneratorReturnType, foobarString, 'utf16le', true, true, false, execa);42-test('Generator can return Uint8Array with encoding "utf16le", objectMode', testGeneratorReturnType, foobarUint8Array, 'utf16le', true, true, false, execa);43-test('Generator can return string with encoding "buffer", objectMode', testGeneratorReturnType, foobarString, 'buffer', true, true, false, execa);44-test('Generator can return Uint8Array with encoding "buffer", objectMode', testGeneratorReturnType, foobarUint8Array, 'buffer', true, true, false, execa);45-test('Generator can return string with encoding "hex", objectMode', testGeneratorReturnType, foobarString, 'hex', true, true, false, execa);46-test('Generator can return Uint8Array with encoding "hex", objectMode', testGeneratorReturnType, foobarUint8Array, 'hex', true, true, false, execa);47-test('Generator can return string with default encoding, objectMode, failure', testGeneratorReturnType, foobarString, 'utf8', false, true, false, execa);48-test('Generator can return Uint8Array with default encoding, objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'utf8', false, true, false, execa);49-test('Generator can return string with encoding "utf16le", objectMode, failure', testGeneratorReturnType, foobarString, 'utf16le', false, true, false, execa);50-test('Generator can return Uint8Array with encoding "utf16le", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'utf16le', false, true, false, execa);51-test('Generator can return string with encoding "buffer", objectMode, failure', testGeneratorReturnType, foobarString, 'buffer', false, true, false, execa);52-test('Generator can return Uint8Array with encoding "buffer", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'buffer', false, true, false, execa);53-test('Generator can return string with encoding "hex", objectMode, failure', testGeneratorReturnType, foobarString, 'hex', false, true, false, execa);54-test('Generator can return Uint8Array with encoding "hex", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'hex', false, true, false, execa);55-test('Generator can return final string with default encoding', testGeneratorReturnType, foobarString, 'utf8', true, false, true, execa);56-test('Generator can return final Uint8Array with default encoding', testGeneratorReturnType, foobarUint8Array, 'utf8', true, false, true, execa);57-test('Generator can return final string with encoding "utf16le"', testGeneratorReturnType, foobarString, 'utf16le', true, false, true, execa);58-test('Generator can return final Uint8Array with encoding "utf16le"', testGeneratorReturnType, foobarUint8Array, 'utf16le', true, false, true, execa);59-test('Generator can return final string with encoding "buffer"', testGeneratorReturnType, foobarString, 'buffer', true, false, true, execa);60-test('Generator can return final Uint8Array with encoding "buffer"', testGeneratorReturnType, foobarUint8Array, 'buffer', true, false, true, execa);61-test('Generator can return final string with encoding "hex"', testGeneratorReturnType, foobarString, 'hex', true, false, true, execa);62-test('Generator can return final Uint8Array with encoding "hex"', testGeneratorReturnType, foobarUint8Array, 'hex', true, false, true, execa);63-test('Generator can return final string with default encoding, failure', testGeneratorReturnType, foobarString, 'utf8', false, false, true, execa);64-test('Generator can return final Uint8Array with default encoding, failure', testGeneratorReturnType, foobarUint8Array, 'utf8', false, false, true, execa);65-test('Generator can return final string with encoding "utf16le", failure', testGeneratorReturnType, foobarString, 'utf16le', false, false, true, execa);66-test('Generator can return final Uint8Array with encoding "utf16le", failure', testGeneratorReturnType, foobarUint8Array, 'utf16le', false, false, true, execa);67-test('Generator can return final string with encoding "buffer", failure', testGeneratorReturnType, foobarString, 'buffer', false, false, true, execa);68-test('Generator can return final Uint8Array with encoding "buffer", failure', testGeneratorReturnType, foobarUint8Array, 'buffer', false, false, true, execa);69-test('Generator can return final string with encoding "hex", failure', testGeneratorReturnType, foobarString, 'hex', false, false, true, execa);70-test('Generator can return final Uint8Array with encoding "hex", failure', testGeneratorReturnType, foobarUint8Array, 'hex', false, false, true, execa);71-test('Generator can return final string with default encoding, objectMode', testGeneratorReturnType, foobarString, 'utf8', true, true, true, execa);72-test('Generator can return final Uint8Array with default encoding, objectMode', testGeneratorReturnType, foobarUint8Array, 'utf8', true, true, true, execa);73-test('Generator can return final string with encoding "utf16le", objectMode', testGeneratorReturnType, foobarString, 'utf16le', true, true, true, execa);74-test('Generator can return final Uint8Array with encoding "utf16le", objectMode', testGeneratorReturnType, foobarUint8Array, 'utf16le', true, true, true, execa);75-test('Generator can return final string with encoding "buffer", objectMode', testGeneratorReturnType, foobarString, 'buffer', true, true, true, execa);76-test('Generator can return final Uint8Array with encoding "buffer", objectMode', testGeneratorReturnType, foobarUint8Array, 'buffer', true, true, true, execa);77-test('Generator can return final string with encoding "hex", objectMode', testGeneratorReturnType, foobarString, 'hex', true, true, true, execa);78-test('Generator can return final Uint8Array with encoding "hex", objectMode', testGeneratorReturnType, foobarUint8Array, 'hex', true, true, true, execa);79-test('Generator can return final string with default encoding, objectMode, failure', testGeneratorReturnType, foobarString, 'utf8', false, true, true, execa);80-test('Generator can return final Uint8Array with default encoding, objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'utf8', false, true, true, execa);81-test('Generator can return final string with encoding "utf16le", objectMode, failure', testGeneratorReturnType, foobarString, 'utf16le', false, true, true, execa);82-test('Generator can return final Uint8Array with encoding "utf16le", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'utf16le', false, true, true, execa);83-test('Generator can return final string with encoding "buffer", objectMode, failure', testGeneratorReturnType, foobarString, 'buffer', false, true, true, execa);84-test('Generator can return final Uint8Array with encoding "buffer", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'buffer', false, true, true, execa);85-test('Generator can return final string with encoding "hex", objectMode, failure', testGeneratorReturnType, foobarString, 'hex', false, true, true, execa);86-test('Generator can return final Uint8Array with encoding "hex", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'hex', false, true, true, execa);87-test('Generator can return string with default encoding, sync', testGeneratorReturnType, foobarString, 'utf8', true, false, false, execaSync);88-test('Generator can return Uint8Array with default encoding, sync', testGeneratorReturnType, foobarUint8Array, 'utf8', true, false, false, execaSync);89-test('Generator can return string with encoding "utf16le", sync', testGeneratorReturnType, foobarString, 'utf16le', true, false, false, execaSync);90-test('Generator can return Uint8Array with encoding "utf16le", sync', testGeneratorReturnType, foobarUint8Array, 'utf16le', true, false, false, execaSync);91-test('Generator can return string with encoding "buffer", sync', testGeneratorReturnType, foobarString, 'buffer', true, false, false, execaSync);92-test('Generator can return Uint8Array with encoding "buffer", sync', testGeneratorReturnType, foobarUint8Array, 'buffer', true, false, false, execaSync);93-test('Generator can return string with encoding "hex", sync', testGeneratorReturnType, foobarString, 'hex', true, false, false, execaSync);94-test('Generator can return Uint8Array with encoding "hex", sync', testGeneratorReturnType, foobarUint8Array, 'hex', true, false, false, execaSync);95-test('Generator can return string with default encoding, failure, sync', testGeneratorReturnType, foobarString, 'utf8', false, false, false, execaSync);96-test('Generator can return Uint8Array with default encoding, failure, sync', testGeneratorReturnType, foobarUint8Array, 'utf8', false, false, false, execaSync);97-test('Generator can return string with encoding "utf16le", failure, sync', testGeneratorReturnType, foobarString, 'utf16le', false, false, false, execaSync);98-test('Generator can return Uint8Array with encoding "utf16le", failure, sync', testGeneratorReturnType, foobarUint8Array, 'utf16le', false, false, false, execaSync);99-test('Generator can return string with encoding "buffer", failure, sync', testGeneratorReturnType, foobarString, 'buffer', false, false, false, execaSync);100-test('Generator can return Uint8Array with encoding "buffer", failure, sync', testGeneratorReturnType, foobarUint8Array, 'buffer', false, false, false, execaSync);101-test('Generator can return string with encoding "hex", failure, sync', testGeneratorReturnType, foobarString, 'hex', false, false, false, execaSync);102-test('Generator can return Uint8Array with encoding "hex", failure, sync', testGeneratorReturnType, foobarUint8Array, 'hex', false, false, false, execaSync);103-test('Generator can return string with default encoding, objectMode, sync', testGeneratorReturnType, foobarString, 'utf8', true, true, false, execaSync);104-test('Generator can return Uint8Array with default encoding, objectMode, sync', testGeneratorReturnType, foobarUint8Array, 'utf8', true, true, false, execaSync);105-test('Generator can return string with encoding "utf16le", objectMode, sync', testGeneratorReturnType, foobarString, 'utf16le', true, true, false, execaSync);106-test('Generator can return Uint8Array with encoding "utf16le", objectMode, sync', testGeneratorReturnType, foobarUint8Array, 'utf16le', true, true, false, execaSync);107-test('Generator can return string with encoding "buffer", objectMode, sync', testGeneratorReturnType, foobarString, 'buffer', true, true, false, execaSync);108-test('Generator can return Uint8Array with encoding "buffer", objectMode, sync', testGeneratorReturnType, foobarUint8Array, 'buffer', true, true, false, execaSync);109-test('Generator can return string with encoding "hex", objectMode, sync', testGeneratorReturnType, foobarString, 'hex', true, true, false, execaSync);110-test('Generator can return Uint8Array with encoding "hex", objectMode, sync', testGeneratorReturnType, foobarUint8Array, 'hex', true, true, false, execaSync);111-test('Generator can return string with default encoding, objectMode, failure, sync', testGeneratorReturnType, foobarString, 'utf8', false, true, false, execaSync);112-test('Generator can return Uint8Array with default encoding, objectMode, failure, sync', testGeneratorReturnType, foobarUint8Array, 'utf8', false, true, false, execaSync);113-test('Generator can return string with encoding "utf16le", objectMode, failure, sync', testGeneratorReturnType, foobarString, 'utf16le', false, true, false, execaSync);114-test('Generator can return Uint8Array with encoding "utf16le", objectMode, failure, sync', testGeneratorReturnType, foobarUint8Array, 'utf16le', false, true, false, execaSync);115-test('Generator can return string with encoding "buffer", objectMode, failure, sync', testGeneratorReturnType, foobarString, 'buffer', false, true, false, execaSync);116-test('Generator can return Uint8Array with encoding "buffer", objectMode, failure, sync', testGeneratorReturnType, foobarUint8Array, 'buffer', false, true, false, execaSync);117-test('Generator can return string with encoding "hex", objectMode, failure, sync', testGeneratorReturnType, foobarString, 'hex', false, true, false, execaSync);118-test('Generator can return Uint8Array with encoding "hex", objectMode, failure, sync', testGeneratorReturnType, foobarUint8Array, 'hex', false, true, false, execaSync);119-test('Generator can return final string with default encoding, sync', testGeneratorReturnType, foobarString, 'utf8', true, false, true, execaSync);120-test('Generator can return final Uint8Array with default encoding, sync', testGeneratorReturnType, foobarUint8Array, 'utf8', true, false, true, execaSync);121-test('Generator can return final string with encoding "utf16le", sync', testGeneratorReturnType, foobarString, 'utf16le', true, false, true, execaSync);122-test('Generator can return final Uint8Array with encoding "utf16le", sync', testGeneratorReturnType, foobarUint8Array, 'utf16le', true, false, true, execaSync);123-test('Generator can return final string with encoding "buffer", sync', testGeneratorReturnType, foobarString, 'buffer', true, false, true, execaSync);124-test('Generator can return final Uint8Array with encoding "buffer", sync', testGeneratorReturnType, foobarUint8Array, 'buffer', true, false, true, execaSync);125-test('Generator can return final string with encoding "hex", sync', testGeneratorReturnType, foobarString, 'hex', true, false, true, execaSync);126-test('Generator can return final Uint8Array with encoding "hex", sync', testGeneratorReturnType, foobarUint8Array, 'hex', true, false, true, execaSync);127-test('Generator can return final string with default encoding, failure, sync', testGeneratorReturnType, foobarString, 'utf8', false, false, true, execaSync);128-test('Generator can return final Uint8Array with default encoding, failure, sync', testGeneratorReturnType, foobarUint8Array, 'utf8', false, false, true, execaSync);129-test('Generator can return final string with encoding "utf16le", failure, sync', testGeneratorReturnType, foobarString, 'utf16le', false, false, true, execaSync);130-test('Generator can return final Uint8Array with encoding "utf16le", failure, sync', testGeneratorReturnType, foobarUint8Array, 'utf16le', false, false, true, execaSync);131-test('Generator can return final string with encoding "buffer", failure, sync', testGeneratorReturnType, foobarString, 'buffer', false, false, true, execaSync);132-test('Generator can return final Uint8Array with encoding "buffer", failure, sync', testGeneratorReturnType, foobarUint8Array, 'buffer', false, false, true, execaSync);133-test('Generator can return final string with encoding "hex", failure, sync', testGeneratorReturnType, foobarString, 'hex', false, false, true, execaSync);134-test('Generator can return final Uint8Array with encoding "hex", failure, sync', testGeneratorReturnType, foobarUint8Array, 'hex', false, false, true, execaSync);135-test('Generator can return final string with default encoding, objectMode, sync', testGeneratorReturnType, foobarString, 'utf8', true, true, true, execaSync);136-test('Generator can return final Uint8Array with default encoding, objectMode, sync', testGeneratorReturnType, foobarUint8Array, 'utf8', true, true, true, execaSync);137-test('Generator can return final string with encoding "utf16le", objectMode, sync', testGeneratorReturnType, foobarString, 'utf16le', true, true, true, execaSync);138-test('Generator can return final Uint8Array with encoding "utf16le", objectMode, sync', testGeneratorReturnType, foobarUint8Array, 'utf16le', true, true, true, execaSync);139-test('Generator can return final string with encoding "buffer", objectMode, sync', testGeneratorReturnType, foobarString, 'buffer', true, true, true, execaSync);140-test('Generator can return final Uint8Array with encoding "buffer", objectMode, sync', testGeneratorReturnType, foobarUint8Array, 'buffer', true, true, true, execaSync);141-test('Generator can return final string with encoding "hex", objectMode, sync', testGeneratorReturnType, foobarString, 'hex', true, true, true, execaSync);142-test('Generator can return final Uint8Array with encoding "hex", objectMode, sync', testGeneratorReturnType, foobarUint8Array, 'hex', true, true, true, execaSync);143-test('Generator can return final string with default encoding, objectMode, failure, sync', testGeneratorReturnType, foobarString, 'utf8', false, true, true, execaSync);144-test('Generator can return final Uint8Array with default encoding, objectMode, failure, sync', testGeneratorReturnType, foobarUint8Array, 'utf8', false, true, true, execaSync);145-test('Generator can return final string with encoding "utf16le", objectMode, failure, sync', testGeneratorReturnType, foobarString, 'utf16le', false, true, true, execaSync);146-test('Generator can return final Uint8Array with encoding "utf16le", objectMode, failure, sync', testGeneratorReturnType, foobarUint8Array, 'utf16le', false, true, true, execaSync);147-test('Generator can return final string with encoding "buffer", objectMode, failure, sync', testGeneratorReturnType, foobarString, 'buffer', false, true, true, execaSync);148-test('Generator can return final Uint8Array with encoding "buffer", objectMode, failure, sync', testGeneratorReturnType, foobarUint8Array, 'buffer', false, true, true, execaSync);149-test('Generator can return final string with encoding "hex", objectMode, failure, sync', testGeneratorReturnType, foobarString, 'hex', false, true, true, execaSync);150-test('Generator can return final Uint8Array with encoding "hex", objectMode, failure, sync', testGeneratorReturnType, foobarUint8Array, 'hex', false, true, true, execaSync);deleted:test/stdio/input-sync.js-18 removed
1-import test from 'ava';2-import {execaSync} from '../../index.js';3-import {setFixtureDir} from '../helpers/fixtures-dir.js';4-import {getStdio} from '../helpers/stdio.js';5-6-setFixtureDir();7-8-const getFd3InputMessage = type => `not \`stdio[3]\`, can be ${type}`;9-10-const testFd3InputSync = (t, stdioOption, expectedMessage) => {11- const {message} = t.throws(() => {12- execaSync('empty.js', getStdio(3, stdioOption));13- });14- t.true(message.includes(expectedMessage));15-};16-17-test('Cannot use Uint8Array with stdio[*], sync', testFd3InputSync, new Uint8Array(), getFd3InputMessage('a Uint8Array'));18-test('Cannot use iterable with stdio[*], sync', testFd3InputSync, [[]], getFd3InputMessage('an iterable'));deleted:test/stdio/input.js-43 removed
1-import {Writable} from 'node:stream';2-import test from 'ava';3-import {execa, execaSync} from '../../index.js';4-import {setFixtureDir} from '../helpers/fixtures-dir.js';5-import {runExeca, runExecaSync, runScript, runScriptSync} from '../helpers/run.js';6-import {foobarUint8Array, foobarBuffer, foobarArrayBuffer, foobarUint16Array, foobarDataView} from '../helpers/input.js';7-8-setFixtureDir();9-10-const testInput = async (t, input, execaMethod) => {11- const {stdout} = await execaMethod('stdin.js', {input});12- t.is(stdout, 'foobar');13-};14-15-test('input option can be a String', testInput, 'foobar', runExeca);16-test('input option can be a Uint8Array', testInput, foobarUint8Array, runExeca);17-test('input option can be a String - sync', testInput, 'foobar', runExecaSync);18-test('input option can be a Uint8Array - sync', testInput, foobarUint8Array, runExecaSync);19-test('input option can be used with $', testInput, 'foobar', runScript);20-test('input option can be used with $.sync', testInput, 'foobar', runScriptSync);21-22-const testInvalidInput = async (t, input, execaMethod) => {23- t.throws(() => {24- execaMethod('empty.js', {input});25- }, {message: /a string, a Uint8Array/});26-};27-28-test('input option cannot be a Buffer', testInvalidInput, foobarBuffer, execa);29-test('input option cannot be an ArrayBuffer', testInvalidInput, foobarArrayBuffer, execa);30-test('input option cannot be a DataView', testInvalidInput, foobarDataView, execa);31-test('input option cannot be a Uint16Array', testInvalidInput, foobarUint16Array, execa);32-test('input option cannot be 0', testInvalidInput, 0, execa);33-test('input option cannot be false', testInvalidInput, false, execa);34-test('input option cannot be null', testInvalidInput, null, execa);35-test('input option cannot be a non-Readable stream', testInvalidInput, new Writable(), execa);36-test('input option cannot be a Buffer - sync', testInvalidInput, foobarBuffer, execaSync);37-test('input option cannot be an ArrayBuffer - sync', testInvalidInput, foobarArrayBuffer, execaSync);38-test('input option cannot be a DataView - sync', testInvalidInput, foobarDataView, execaSync);39-test('input option cannot be a Uint16Array - sync', testInvalidInput, foobarUint16Array, execaSync);40-test('input option cannot be 0 - sync', testInvalidInput, 0, execaSync);41-test('input option cannot be false - sync', testInvalidInput, false, execaSync);42-test('input option cannot be null - sync', testInvalidInput, null, execaSync);43-test('input option cannot be a non-Readable stream - sync', testInvalidInput, new Writable(), execaSync);deleted:test/stdio/normalize-transform.js-55 removed
1-import test from 'ava';2-import {execa, execaSync} from '../../index.js';3-import {setFixtureDir} from '../helpers/fixtures-dir.js';4-import {foobarString, foobarUppercase, foobarUint8Array} from '../helpers/input.js';5-import {casedSuffix} from '../helpers/generator.js';6-import {generatorsMap} from '../helpers/map.js';7-8-setFixtureDir();9-10-const testAppendInput = async (t, reversed, type, execaMethod) => {11- const stdin = [foobarUint8Array, generatorsMap[type].uppercase(), generatorsMap[type].append()];12- const reversedStdin = reversed ? stdin.reverse() : stdin;13- const {stdout} = await execaMethod('stdin-fd.js', ['0'], {stdin: reversedStdin});14- const reversedSuffix = reversed ? casedSuffix.toUpperCase() : casedSuffix;15- t.is(stdout, `${foobarUppercase}${reversedSuffix}`);16-};17-18-test('Can use multiple generators as input', testAppendInput, false, 'generator', execa);19-test('Can use multiple generators as input, reversed', testAppendInput, true, 'generator', execa);20-test('Can use multiple generators as input, sync', testAppendInput, false, 'generator', execaSync);21-test('Can use multiple generators as input, reversed, sync', testAppendInput, true, 'generator', execaSync);22-test('Can use multiple duplexes as input', testAppendInput, false, 'duplex', execa);23-test('Can use multiple duplexes as input, reversed', testAppendInput, true, 'duplex', execa);24-test('Can use multiple webTransforms as input', testAppendInput, false, 'webTransform', execa);25-test('Can use multiple webTransforms as input, reversed', testAppendInput, true, 'webTransform', execa);26-27-const testAppendOutput = async (t, reversed, type, execaMethod) => {28- const stdoutOption = [generatorsMap[type].uppercase(), generatorsMap[type].append()];29- const reversedStdoutOption = reversed ? stdoutOption.reverse() : stdoutOption;30- const {stdout} = await execaMethod('noop-fd.js', ['1', foobarString], {stdout: reversedStdoutOption});31- const reversedSuffix = reversed ? casedSuffix.toUpperCase() : casedSuffix;32- t.is(stdout, `${foobarUppercase}${reversedSuffix}`);33-};34-35-test('Can use multiple generators as output', testAppendOutput, false, 'generator', execa);36-test('Can use multiple generators as output, reversed', testAppendOutput, true, 'generator', execa);37-test('Can use multiple generators as output, sync', testAppendOutput, false, 'generator', execaSync);38-test('Can use multiple generators as output, reversed, sync', testAppendOutput, true, 'generator', execaSync);39-test('Can use multiple duplexes as output', testAppendOutput, false, 'duplex', execa);40-test('Can use multiple duplexes as output, reversed', testAppendOutput, true, 'duplex', execa);41-test('Can use multiple webTransforms as output', testAppendOutput, false, 'webTransform', execa);42-test('Can use multiple webTransforms as output, reversed', testAppendOutput, true, 'webTransform', execa);43-44-const testGeneratorSyntax = async (t, type, usePlainObject, execaMethod) => {45- const transform = generatorsMap[type].uppercase();46- const {stdout} = await execaMethod('noop-fd.js', ['1', foobarString], {stdout: usePlainObject ? transform : transform.transform});47- t.is(stdout, foobarUppercase);48-};49-50-test('Can pass generators with an options plain object', testGeneratorSyntax, 'generator', false, execa);51-test('Can pass generators without an options plain object', testGeneratorSyntax, 'generator', true, execa);52-test('Can pass generators with an options plain object, sync', testGeneratorSyntax, 'generator', false, execaSync);53-test('Can pass generators without an options plain object, sync', testGeneratorSyntax, 'generator', true, execaSync);54-test('Can pass webTransforms with an options plain object', testGeneratorSyntax, 'webTransform', true, execa);55-test('Can pass webTransforms without an options plain object', testGeneratorSyntax, 'webTransform', false, execa);deleted:test/stdio/option.js-57 removed
1-import {inspect} from 'node:util';2-import test from 'ava';3-import {normalizeStdio} from '../../lib/stdio/option.js';4-5-const macro = (t, input, expected, func) => {6- if (expected instanceof Error) {7- t.throws(() => {8- normalizeStdio(input);9- }, {message: expected.message});10- return;11- }12-13- t.deepEqual(func(input), expected);14-};15-16-const macroTitle = name => (title, input) => `${name} ${(inspect(input))}`;17-18-const stdioMacro = (...args) => macro(...args, normalizeStdio);19-stdioMacro.title = macroTitle('execa()');20-21-test(stdioMacro, {stdio: 'inherit'}, ['inherit', 'inherit', 'inherit']);22-test(stdioMacro, {stdio: 'pipe'}, ['pipe', 'pipe', 'pipe']);23-test(stdioMacro, {stdio: 'ignore'}, ['ignore', 'ignore', 'ignore']);24-25-test(stdioMacro, {}, ['pipe', 'pipe', 'pipe']);26-test(stdioMacro, {stdio: []}, ['pipe', 'pipe', 'pipe']);27-test(stdioMacro, {stdio: [0]}, [0, 'pipe', 'pipe']);28-test(stdioMacro, {stdio: [0, 1]}, [0, 1, 'pipe']);29-test(stdioMacro, {stdio: [0, 1, 2]}, [0, 1, 2]);30-test(stdioMacro, {stdio: [0, 1, 2, 3]}, [0, 1, 2, 3]);31-test(stdioMacro, {stdio: [undefined, 1, 2]}, ['pipe', 1, 2]);32-test(stdioMacro, {stdio: [null, 1, 2]}, ['pipe', 1, 2]);33-test(stdioMacro, {stdio: [0, undefined, 2]}, [0, 'pipe', 2]);34-test(stdioMacro, {stdio: [0, null, 2]}, [0, 'pipe', 2]);35-test(stdioMacro, {stdio: [0, 1, undefined]}, [0, 1, 'pipe']);36-test(stdioMacro, {stdio: [0, 1, null]}, [0, 1, 'pipe']);37-test(stdioMacro, {stdio: [0, 1, 2, undefined]}, [0, 1, 2, 'ignore']);38-test(stdioMacro, {stdio: [0, 1, 2, null]}, [0, 1, 2, 'ignore']);39-40-test(stdioMacro, {stdin: 'pipe'}, ['pipe', 'pipe', 'pipe']);41-test(stdioMacro, {stdout: 'ignore'}, ['pipe', 'ignore', 'pipe']);42-test(stdioMacro, {stderr: 'inherit'}, ['pipe', 'pipe', 'inherit']);43-test(stdioMacro, {stdin: 'pipe', stdout: 'ignore', stderr: 'inherit'}, ['pipe', 'ignore', 'inherit']);44-test(stdioMacro, {stdin: 'pipe', stdout: 'ignore'}, ['pipe', 'ignore', 'pipe']);45-test(stdioMacro, {stdin: 'pipe', stderr: 'inherit'}, ['pipe', 'pipe', 'inherit']);46-test(stdioMacro, {stdout: 'ignore', stderr: 'inherit'}, ['pipe', 'ignore', 'inherit']);47-test(stdioMacro, {stdin: 0, stdout: 1, stderr: 2}, [0, 1, 2]);48-test(stdioMacro, {stdin: 0, stdout: 1}, [0, 1, 'pipe']);49-test(stdioMacro, {stdin: 0, stderr: 2}, [0, 'pipe', 2]);50-test(stdioMacro, {stdout: 1, stderr: 2}, ['pipe', 1, 2]);51-52-test(stdioMacro, {stdio: {foo: 'bar'}}, new TypeError('Expected `stdio` to be of type `string` or `Array`, got `object`'));53-54-test(stdioMacro, {stdin: 'inherit', stdio: 'pipe'}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));55-test(stdioMacro, {stdin: 'inherit', stdio: ['pipe']}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));56-test(stdioMacro, {stdin: 'inherit', stdio: [undefined, 'pipe']}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));57-test(stdioMacro, {stdin: 0, stdio: 'pipe'}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));deleted:test/stdio/output-async.js-84 removed
1-import {once, defaultMaxListeners} from 'node:events';2-import process from 'node:process';3-import {setImmediate} from 'node:timers/promises';4-import test from 'ava';5-import {execa} from '../../index.js';6-import {STANDARD_STREAMS} from '../helpers/stdio.js';7-import {foobarString} from '../helpers/input.js';8-import {setFixtureDir} from '../helpers/fixtures-dir.js';9-import {assertMaxListeners} from '../helpers/listeners.js';10-11-setFixtureDir();12-13-const getStandardStreamListeners = stream => Object.fromEntries(stream.eventNames().map(eventName => [eventName, stream.listeners(eventName)]));14-const getStandardStreamsListeners = () => STANDARD_STREAMS.map(stream => getStandardStreamListeners(stream));15-16-const getComplexStdio = isMultiple => ({17- stdin: ['pipe', 'inherit', ...(isMultiple ? [0, process.stdin] : [])],18- stdout: ['pipe', 'inherit', ...(isMultiple ? [1, process.stdout] : [])],19- stderr: ['pipe', 'inherit', ...(isMultiple ? [2, process.stderr] : [])],20-});21-22-const onStdinRemoveListener = () => once(process.stdin, 'removeListener');23-24-const testListenersCleanup = async (t, isMultiple) => {25- const streamsPreviousListeners = getStandardStreamsListeners();26- const subprocess = execa('empty.js', getComplexStdio(isMultiple));27- t.notDeepEqual(getStandardStreamsListeners(), streamsPreviousListeners);28- await Promise.all([subprocess, onStdinRemoveListener()]);29- if (isMultiple) {30- await onStdinRemoveListener();31- }32-33- for (const [fdNumber, streamNewListeners] of Object.entries(getStandardStreamsListeners())) {34- const defaultListeners = Object.fromEntries(Reflect.ownKeys(streamNewListeners).map(eventName => [eventName, []]));35- t.deepEqual(streamNewListeners, {...defaultListeners, ...streamsPreviousListeners[fdNumber]});36- }37-};38-39-test.serial('process.std* listeners are cleaned up on success with a single input', testListenersCleanup, false);40-test.serial('process.std* listeners are cleaned up on success with multiple inputs', testListenersCleanup, true);41-42-const subprocessesCount = 100;43-44-test.serial('Can spawn many subprocesses in parallel', async t => {45- const results = await Promise.all(46- Array.from({length: subprocessesCount}, () => execa('noop.js', [foobarString])),47- );48- t.true(results.every(({stdout}) => stdout === foobarString));49-});50-51-const testMaxListeners = async (t, isMultiple, maxListenersCount) => {52- const checkMaxListeners = assertMaxListeners(t);53-54- for (const standardStream of STANDARD_STREAMS) {55- standardStream.setMaxListeners(maxListenersCount);56- }57-58- try {59- const results = await Promise.all(60- Array.from({length: subprocessesCount}, () => execa('empty.js', getComplexStdio(isMultiple))),61- );62- t.true(results.every(({exitCode}) => exitCode === 0));63- } finally {64- await setImmediate();65- await setImmediate();66- checkMaxListeners();67-68- for (const standardStream of STANDARD_STREAMS) {69- t.is(standardStream.getMaxListeners(), maxListenersCount);70- standardStream.setMaxListeners(defaultMaxListeners);71- }72- }73-};74-75-test.serial('No warning with maxListeners 1 and ["pipe", "inherit"]', testMaxListeners, false, 1);76-test.serial('No warning with maxListeners default and ["pipe", "inherit"]', testMaxListeners, false, defaultMaxListeners);77-test.serial('No warning with maxListeners 100 and ["pipe", "inherit"]', testMaxListeners, false, 100);78-test.serial('No warning with maxListeners Infinity and ["pipe", "inherit"]', testMaxListeners, false, Number.POSITIVE_INFINITY);79-test.serial('No warning with maxListeners 0 and ["pipe", "inherit"]', testMaxListeners, false, 0);80-test.serial('No warning with maxListeners 1 and ["pipe", "inherit"], multiple inputs', testMaxListeners, true, 1);81-test.serial('No warning with maxListeners default and ["pipe", "inherit"], multiple inputs', testMaxListeners, true, defaultMaxListeners);82-test.serial('No warning with maxListeners 100 and ["pipe", "inherit"], multiple inputs', testMaxListeners, true, 100);83-test.serial('No warning with maxListeners Infinity and ["pipe", "inherit"], multiple inputs', testMaxListeners, true, Number.POSITIVE_INFINITY);84-test.serial('No warning with maxListeners 0 and ["pipe", "inherit"], multiple inputs', testMaxListeners, true, 0);deleted:test/stdio/output-sync.js-33 removed
1-import test from 'ava';2-import {execaSync} from '../../index.js';3-import {setFixtureDir} from '../helpers/fixtures-dir.js';4-import {throwingGenerator} from '../helpers/generator.js';5-import {foobarString} from '../helpers/input.js';6-7-setFixtureDir();8-9-test('Handles errors with stdout generator, sync', t => {10- const cause = new Error(foobarString);11- const error = t.throws(() => {12- execaSync('noop.js', {stdout: throwingGenerator(cause)()});13- });14- t.is(error.cause, cause);15-});16-17-test('Handles errors with stdout generator, spawn failure, sync', t => {18- const cause = new Error(foobarString);19- const error = t.throws(() => {20- execaSync('noop.js', {cwd: 'does_not_exist', stdout: throwingGenerator(cause)()});21- });22- t.true(error.failed);23- t.is(error.cause.code, 'ENOENT');24-});25-26-test('Handles errors with stdout generator, subprocess failure, sync', t => {27- const cause = new Error(foobarString);28- const error = t.throws(() => {29- execaSync('noop-fail.js', ['1'], {stdout: throwingGenerator(cause)()});30- });31- t.true(error.failed);32- t.is(error.cause, cause);33-});deleted:test/stdio/pipeline.js-38 removed
1-import test from 'ava';2-import {execa} from '../../index.js';3-import {getStdio, STANDARD_STREAMS} from '../helpers/stdio.js';4-import {setFixtureDir} from '../helpers/fixtures-dir.js';5-6-setFixtureDir();7-8-const testDestroyStandard = async (t, fdNumber) => {9- const subprocess = execa('forever.js', {...getStdio(fdNumber, [STANDARD_STREAMS[fdNumber], 'pipe']), timeout: 1});10- await t.throwsAsync(subprocess, {message: /timed out/});11- t.false(STANDARD_STREAMS[fdNumber].destroyed);12-};13-14-test('Does not destroy process.stdin on subprocess errors', testDestroyStandard, 0);15-test('Does not destroy process.stdout on subprocess errors', testDestroyStandard, 1);16-test('Does not destroy process.stderr on subprocess errors', testDestroyStandard, 2);17-18-const testDestroyStandardSpawn = async (t, fdNumber) => {19- await t.throwsAsync(execa('forever.js', {...getStdio(fdNumber, [STANDARD_STREAMS[fdNumber], 'pipe']), uid: -1}));20- t.false(STANDARD_STREAMS[fdNumber].destroyed);21-};22-23-test('Does not destroy process.stdin on subprocess early errors', testDestroyStandardSpawn, 0);24-test('Does not destroy process.stdout on subprocess early errors', testDestroyStandardSpawn, 1);25-test('Does not destroy process.stderr on subprocess early errors', testDestroyStandardSpawn, 2);26-27-const testDestroyStandardStream = async (t, fdNumber) => {28- const subprocess = execa('forever.js', getStdio(fdNumber, [STANDARD_STREAMS[fdNumber], 'pipe']));29- const cause = new Error('test');30- subprocess.stdio[fdNumber].destroy(cause);31- subprocess.kill();32- t.like(await t.throwsAsync(subprocess), {cause});33- t.false(STANDARD_STREAMS[fdNumber].destroyed);34-};35-36-test('Does not destroy process.stdin on stream subprocess errors', testDestroyStandardStream, 0);37-test('Does not destroy process.stdout on stream subprocess errors', testDestroyStandardStream, 1);38-test('Does not destroy process.stderr on stream subprocess errors', testDestroyStandardStream, 2);deleted:test/stdio/split-binary.js-95 removed
1-import test from 'ava';2-import {execa, execaSync} from '../../index.js';3-import {setFixtureDir} from '../helpers/fixtures-dir.js';4-import {getOutputsGenerator, resultGenerator} from '../helpers/generator.js';5-import {6- simpleFull,7- simpleChunks,8- simpleFullUint8Array,9- simpleFullUtf16Inverted,10- simpleFullUtf16Uint8Array,11- simpleChunksUint8Array,12- simpleFullEnd,13- simpleFullEndUtf16Inverted,14- simpleFullHex,15- simpleLines,16- noNewlinesChunks,17-} from '../helpers/lines.js';18-19-setFixtureDir();20-21-// eslint-disable-next-line max-params22-const testBinaryOption = async (t, binary, input, expectedLines, expectedOutput, objectMode, preserveNewlines, encoding, execaMethod) => {23- const lines = [];24- const {stdout} = await execaMethod('noop.js', {25- stdout: [26- getOutputsGenerator(input)(false, true),27- resultGenerator(lines)(objectMode, binary, preserveNewlines),28- ],29- stripFinalNewline: false,30- encoding,31- });32- t.deepEqual(lines, expectedLines);33- t.deepEqual(stdout, expectedOutput);34-};35-36-test('Does not split lines when "binary" is true', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFull, false, true, 'utf8', execa);37-test('Splits lines when "binary" is false', testBinaryOption, false, simpleChunks, simpleLines, simpleFull, false, true, 'utf8', execa);38-test('Splits lines when "binary" is undefined', testBinaryOption, undefined, simpleChunks, simpleLines, simpleFull, false, true, 'utf8', execa);39-test('Does not split lines when "binary" is true, encoding "utf16le"', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUtf16Inverted, false, true, 'utf16le', execa);40-test('Splits lines when "binary" is false, encoding "utf16le"', testBinaryOption, false, [simpleFullUtf16Uint8Array], simpleLines, simpleFullUtf16Inverted, false, true, 'utf16le', execa);41-test('Splits lines when "binary" is undefined, encoding "utf16le"', testBinaryOption, undefined, [simpleFullUtf16Uint8Array], simpleLines, simpleFullUtf16Inverted, false, true, 'utf16le', execa);42-test('Does not split lines when "binary" is true, encoding "buffer"', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, true, 'buffer', execa);43-test('Does not split lines when "binary" is undefined, encoding "buffer"', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, true, 'buffer', execa);44-test('Does not split lines when "binary" is false, encoding "buffer"', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, true, 'buffer', execa);45-test('Does not split lines when "binary" is true, encoding "hex"', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, true, 'hex', execa);46-test('Does not split lines when "binary" is undefined, encoding "hex"', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, true, 'hex', execa);47-test('Does not split lines when "binary" is false, encoding "hex"', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, true, 'hex', execa);48-test('Does not split lines when "binary" is true, objectMode', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleChunksUint8Array, true, true, 'utf8', execa);49-test('Splits lines when "binary" is false, objectMode', testBinaryOption, false, simpleChunks, simpleLines, simpleLines, true, true, 'utf8', execa);50-test('Splits lines when "binary" is undefined, objectMode', testBinaryOption, undefined, simpleChunks, simpleLines, simpleLines, true, true, 'utf8', execa);51-test('Does not split lines when "binary" is true, preserveNewlines', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFull, false, false, 'utf8', execa);52-test('Splits lines when "binary" is false, preserveNewlines', testBinaryOption, false, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, 'utf8', execa);53-test('Splits lines when "binary" is undefined, preserveNewlines', testBinaryOption, undefined, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, 'utf8', execa);54-test('Does not split lines when "binary" is true, preserveNewlines, encoding "utf16le"', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUtf16Inverted, false, false, 'utf16le', execa);55-test('Splits lines when "binary" is false, preserveNewlines, encoding "utf16le"', testBinaryOption, false, [simpleFullUtf16Uint8Array], noNewlinesChunks, simpleFullEndUtf16Inverted, false, false, 'utf16le', execa);56-test('Splits lines when "binary" is undefined, preserveNewlines, encoding "utf16le"', testBinaryOption, undefined, [simpleFullUtf16Uint8Array], noNewlinesChunks, simpleFullEndUtf16Inverted, false, false, 'utf16le', execa);57-test('Does not split lines when "binary" is true, encoding "buffer", preserveNewlines', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, false, 'buffer', execa);58-test('Does not split lines when "binary" is undefined, encoding "buffer", preserveNewlines', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, false, 'buffer', execa);59-test('Does not split lines when "binary" is false, encoding "buffer", preserveNewlines', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, false, 'buffer', execa);60-test('Does not split lines when "binary" is true, objectMode, preserveNewlines', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleChunksUint8Array, true, false, 'utf8', execa);61-test('Does not split lines when "binary" is true, encoding "hex", preserveNewlines', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, false, 'hex', execa);62-test('Does not split lines when "binary" is undefined, encoding "hex", preserveNewlines', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, false, 'hex', execa);63-test('Does not split lines when "binary" is false, encoding "hex", preserveNewlines', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, false, 'hex', execa);64-test('Splits lines when "binary" is false, objectMode, preserveNewlines', testBinaryOption, false, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, 'utf8', execa);65-test('Splits lines when "binary" is undefined, objectMode, preserveNewlines', testBinaryOption, undefined, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, 'utf8', execa);66-test('Does not split lines when "binary" is true, sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFull, false, true, 'utf8', execaSync);67-test('Splits lines when "binary" is false, sync', testBinaryOption, false, simpleChunks, simpleLines, simpleFull, false, true, 'utf8', execaSync);68-test('Splits lines when "binary" is undefined, sync', testBinaryOption, undefined, simpleChunks, simpleLines, simpleFull, false, true, 'utf8', execaSync);69-test('Does not split lines when "binary" is true, encoding "utf16le", sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUtf16Inverted, false, true, 'utf16le', execaSync);70-test('Splits lines when "binary" is false, encoding "utf16le", sync', testBinaryOption, false, [simpleFullUtf16Uint8Array], simpleLines, simpleFullUtf16Inverted, false, true, 'utf16le', execaSync);71-test('Splits lines when "binary" is undefined, encoding "utf16le", sync', testBinaryOption, undefined, [simpleFullUtf16Uint8Array], simpleLines, simpleFullUtf16Inverted, false, true, 'utf16le', execaSync);72-test('Does not split lines when "binary" is true, encoding "buffer", sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, true, 'buffer', execaSync);73-test('Does not split lines when "binary" is undefined, encoding "buffer", sync', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, true, 'buffer', execaSync);74-test('Does not split lines when "binary" is false, encoding "buffer", sync', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, true, 'buffer', execaSync);75-test('Does not split lines when "binary" is true, encoding "hex", sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, true, 'hex', execaSync);76-test('Does not split lines when "binary" is undefined, encoding "hex", sync', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, true, 'hex', execaSync);77-test('Does not split lines when "binary" is false, encoding "hex", sync', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, true, 'hex', execaSync);78-test('Does not split lines when "binary" is true, objectMode, sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleChunksUint8Array, true, true, 'utf8', execaSync);79-test('Splits lines when "binary" is false, objectMode, sync', testBinaryOption, false, simpleChunks, simpleLines, simpleLines, true, true, 'utf8', execaSync);80-test('Splits lines when "binary" is undefined, objectMode, sync', testBinaryOption, undefined, simpleChunks, simpleLines, simpleLines, true, true, 'utf8', execaSync);81-test('Does not split lines when "binary" is true, preserveNewlines, sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFull, false, false, 'utf8', execaSync);82-test('Splits lines when "binary" is false, preserveNewlines, sync', testBinaryOption, false, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, 'utf8', execaSync);83-test('Splits lines when "binary" is undefined, preserveNewlines, sync', testBinaryOption, undefined, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, 'utf8', execaSync);84-test('Does not split lines when "binary" is true, preserveNewlines, encoding "utf16le", sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUtf16Inverted, false, false, 'utf16le', execaSync);85-test('Splits lines when "binary" is false, preserveNewlines, encoding "utf16le", sync', testBinaryOption, false, [simpleFullUtf16Uint8Array], noNewlinesChunks, simpleFullEndUtf16Inverted, false, false, 'utf16le', execaSync);86-test('Splits lines when "binary" is undefined, preserveNewlines, encoding "utf16le", sync', testBinaryOption, undefined, [simpleFullUtf16Uint8Array], noNewlinesChunks, simpleFullEndUtf16Inverted, false, false, 'utf16le', execaSync);87-test('Does not split lines when "binary" is true, encoding "buffer", preserveNewlines, sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, false, 'buffer', execaSync);88-test('Does not split lines when "binary" is undefined, encoding "buffer", preserveNewlines, sync', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, false, 'buffer', execaSync);89-test('Does not split lines when "binary" is false, encoding "buffer", preserveNewlines, sync', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, false, 'buffer', execaSync);90-test('Does not split lines when "binary" is true, objectMode, preserveNewlines, sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleChunksUint8Array, true, false, 'utf8', execaSync);91-test('Does not split lines when "binary" is true, encoding "hex", preserveNewlines, sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, false, 'hex', execaSync);92-test('Does not split lines when "binary" is undefined, encoding "hex", preserveNewlines, sync', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, false, 'hex', execaSync);93-test('Does not split lines when "binary" is false, encoding "hex", preserveNewlines, sync', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, false, 'hex', execaSync);94-test('Splits lines when "binary" is false, objectMode, preserveNewlines, sync', testBinaryOption, false, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, 'utf8', execaSync);95-test('Splits lines when "binary" is undefined, objectMode, preserveNewlines, sync', testBinaryOption, undefined, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, 'utf8', execaSync);deleted:test/stdio/split-lines.js-174 removed
1-import test from 'ava';2-import {execa, execaSync} from '../../index.js';3-import {setFixtureDir} from '../helpers/fixtures-dir.js';4-import {getStdio} from '../helpers/stdio.js';5-import {getOutputsGenerator, resultGenerator} from '../helpers/generator.js';6-import {7- singleFull,8- singleFullEnd,9- simpleFull,10- simpleChunks,11- simpleFullEnd,12- simpleFullEndChunks,13- simpleLines,14- simpleFullEndLines,15- noNewlinesFull,16- noNewlinesChunks,17-} from '../helpers/lines.js';18-19-setFixtureDir();20-21-const windowsFull = 'aaa\r\nbbb\r\nccc';22-const windowsFullEnd = `${windowsFull}\r\n`;23-const windowsChunks = [windowsFull];24-const windowsLines = ['aaa\r\n', 'bbb\r\n', 'ccc'];25-const noNewlinesFullEnd = `${noNewlinesFull}\n`;26-const noNewlinesLines = ['aaabbbccc'];27-const singleChunks = [singleFull];28-const noLines = [];29-const emptyFull = '';30-const emptyChunks = [emptyFull];31-const manyEmptyChunks = [emptyFull, emptyFull, emptyFull];32-const newlineFull = '\n';33-const newlineChunks = [newlineFull];34-const newlinesFull = '\n\n\n';35-const newlinesChunks = [newlinesFull];36-const newlinesLines = ['\n', '\n', '\n'];37-const windowsNewlinesFull = '\r\n\r\n\r\n';38-const windowsNewlinesChunks = [windowsNewlinesFull];39-const windowsNewlinesLines = ['\r\n', '\r\n', '\r\n'];40-const runOverChunks = ['aaa\nb', 'b', 'b\nccc'];41-const bigFull = '.'.repeat(1e5);42-const bigFullEnd = `${bigFull}\n`;43-const bigChunks = [bigFull];44-const manyChunks = Array.from({length: 1e3}).fill('.');45-const manyFull = manyChunks.join('');46-const manyFullEnd = `${manyFull}\n`;47-const manyLines = [manyFull];48-49-// eslint-disable-next-line max-params50-const testLines = async (t, fdNumber, input, expectedLines, expectedOutput, objectMode, preserveNewlines, execaMethod) => {51- const lines = [];52- const {stdio} = await execaMethod('noop-fd.js', [`${fdNumber}`], {53- ...getStdio(fdNumber, [54- getOutputsGenerator(input)(false, true),55- resultGenerator(lines)(objectMode, false, preserveNewlines),56- ]),57- stripFinalNewline: false,58- });59- t.deepEqual(lines, expectedLines);60- t.deepEqual(stdio[fdNumber], expectedOutput);61-};62-63-test('Split stdout - n newlines, 1 chunk', testLines, 1, simpleChunks, simpleLines, simpleFull, false, true, execa);64-test('Split stderr - n newlines, 1 chunk', testLines, 2, simpleChunks, simpleLines, simpleFull, false, true, execa);65-test('Split stdio[*] - n newlines, 1 chunk', testLines, 3, simpleChunks, simpleLines, simpleFull, false, true, execa);66-test('Split stdout - preserveNewlines, n chunks', testLines, 1, noNewlinesChunks, noNewlinesLines, noNewlinesFull, false, true, execa);67-test('Split stdout - 0 newlines, 1 chunk', testLines, 1, singleChunks, singleChunks, singleFull, false, true, execa);68-test('Split stdout - empty, 1 chunk', testLines, 1, emptyChunks, noLines, emptyFull, false, true, execa);69-test('Split stdout - Windows newlines', testLines, 1, windowsChunks, windowsLines, windowsFull, false, true, execa);70-test('Split stdout - chunk ends with newline', testLines, 1, simpleFullEndChunks, simpleFullEndLines, simpleFullEnd, false, true, execa);71-test('Split stdout - single newline', testLines, 1, newlineChunks, newlineChunks, newlineFull, false, true, execa);72-test('Split stdout - only newlines', testLines, 1, newlinesChunks, newlinesLines, newlinesFull, false, true, execa);73-test('Split stdout - only Windows newlines', testLines, 1, windowsNewlinesChunks, windowsNewlinesLines, windowsNewlinesFull, false, true, execa);74-test('Split stdout - line split over multiple chunks', testLines, 1, runOverChunks, simpleLines, simpleFull, false, true, execa);75-test('Split stdout - 0 newlines, big line', testLines, 1, bigChunks, bigChunks, bigFull, false, true, execa);76-test('Split stdout - 0 newlines, many chunks', testLines, 1, manyChunks, manyLines, manyFull, false, true, execa);77-test('Split stdout - n newlines, 1 chunk, objectMode', testLines, 1, simpleChunks, simpleLines, simpleLines, true, true, execa);78-test('Split stderr - n newlines, 1 chunk, objectMode', testLines, 2, simpleChunks, simpleLines, simpleLines, true, true, execa);79-test('Split stdio[*] - n newlines, 1 chunk, objectMode', testLines, 3, simpleChunks, simpleLines, simpleLines, true, true, execa);80-test('Split stdout - preserveNewlines, n chunks, objectMode', testLines, 1, noNewlinesChunks, noNewlinesLines, noNewlinesLines, true, true, execa);81-test('Split stdout - empty, 1 chunk, objectMode', testLines, 1, emptyChunks, noLines, noLines, true, true, execa);82-test('Split stdout - 0 newlines, 1 chunk, objectMode', testLines, 1, singleChunks, singleChunks, singleChunks, true, true, execa);83-test('Split stdout - Windows newlines, objectMode', testLines, 1, windowsChunks, windowsLines, windowsLines, true, true, execa);84-test('Split stdout - chunk ends with newline, objectMode', testLines, 1, simpleFullEndChunks, simpleFullEndLines, simpleFullEndLines, true, true, execa);85-test('Split stdout - single newline, objectMode', testLines, 1, newlineChunks, newlineChunks, newlineChunks, true, true, execa);86-test('Split stdout - only newlines, objectMode', testLines, 1, newlinesChunks, newlinesLines, newlinesLines, true, true, execa);87-test('Split stdout - only Windows newlines, objectMode', testLines, 1, windowsNewlinesChunks, windowsNewlinesLines, windowsNewlinesLines, true, true, execa);88-test('Split stdout - line split over multiple chunks, objectMode', testLines, 1, runOverChunks, simpleLines, simpleLines, true, true, execa);89-test('Split stdout - 0 newlines, big line, objectMode', testLines, 1, bigChunks, bigChunks, bigChunks, true, true, execa);90-test('Split stdout - 0 newlines, many chunks, objectMode', testLines, 1, manyChunks, manyLines, manyLines, true, true, execa);91-test('Split stdout - n newlines, 1 chunk, preserveNewlines', testLines, 1, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, execa);92-test('Split stderr - n newlines, 1 chunk, preserveNewlines', testLines, 2, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, execa);93-test('Split stdio[*] - n newlines, 1 chunk, preserveNewlines', testLines, 3, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, execa);94-test('Split stdout - preserveNewlines, n chunks, preserveNewlines', testLines, 1, noNewlinesChunks, noNewlinesLines, noNewlinesFullEnd, false, false, execa);95-test('Split stdout - empty, 1 chunk, preserveNewlines', testLines, 1, emptyChunks, noLines, emptyFull, false, false, execa);96-test('Split stdout - 0 newlines, 1 chunk, preserveNewlines', testLines, 1, singleChunks, singleChunks, singleFullEnd, false, false, execa);97-test('Split stdout - Windows newlines, preserveNewlines', testLines, 1, windowsChunks, noNewlinesChunks, windowsFullEnd, false, false, execa);98-test('Split stdout - chunk ends with newline, preserveNewlines', testLines, 1, simpleFullEndChunks, noNewlinesChunks, simpleFullEnd, false, false, execa);99-test('Split stdout - single newline, preserveNewlines', testLines, 1, newlineChunks, emptyChunks, newlineFull, false, false, execa);100-test('Split stdout - only newlines, preserveNewlines', testLines, 1, newlinesChunks, manyEmptyChunks, newlinesFull, false, false, execa);101-test('Split stdout - only Windows newlines, preserveNewlines', testLines, 1, windowsNewlinesChunks, manyEmptyChunks, windowsNewlinesFull, false, false, execa);102-test('Split stdout - line split over multiple chunks, preserveNewlines', testLines, 1, runOverChunks, noNewlinesChunks, simpleFullEnd, false, false, execa);103-test('Split stdout - 0 newlines, big line, preserveNewlines', testLines, 1, bigChunks, bigChunks, bigFullEnd, false, false, execa);104-test('Split stdout - 0 newlines, many chunks, preserveNewlines', testLines, 1, manyChunks, manyLines, manyFullEnd, false, false, execa);105-test('Split stdout - n newlines, 1 chunk, objectMode, preserveNewlines', testLines, 1, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, execa);106-test('Split stderr - n newlines, 1 chunk, objectMode, preserveNewlines', testLines, 2, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, execa);107-test('Split stdio[*] - n newlines, 1 chunk, objectMode, preserveNewlines', testLines, 3, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, execa);108-test('Split stdout - preserveNewlines, n chunks, objectMode, preserveNewlines', testLines, 1, noNewlinesChunks, noNewlinesLines, noNewlinesLines, true, false, execa);109-test('Split stdout - empty, 1 chunk, objectMode, preserveNewlines', testLines, 1, emptyChunks, noLines, noLines, true, false, execa);110-test('Split stdout - 0 newlines, 1 chunk, objectMode, preserveNewlines', testLines, 1, singleChunks, singleChunks, singleChunks, true, false, execa);111-test('Split stdout - Windows newlines, objectMode, preserveNewlines', testLines, 1, windowsChunks, noNewlinesChunks, noNewlinesChunks, true, false, execa);112-test('Split stdout - chunk ends with newline, objectMode, preserveNewlines', testLines, 1, simpleFullEndChunks, noNewlinesChunks, noNewlinesChunks, true, false, execa);113-test('Split stdout - single newline, objectMode, preserveNewlines', testLines, 1, newlineChunks, emptyChunks, emptyChunks, true, false, execa);114-test('Split stdout - only newlines, objectMode, preserveNewlines', testLines, 1, newlinesChunks, manyEmptyChunks, manyEmptyChunks, true, false, execa);115-test('Split stdout - only Windows newlines, objectMode, preserveNewlines', testLines, 1, windowsNewlinesChunks, manyEmptyChunks, manyEmptyChunks, true, false, execa);116-test('Split stdout - line split over multiple chunks, objectMode, preserveNewlines', testLines, 1, runOverChunks, noNewlinesChunks, noNewlinesChunks, true, false, execa);117-test('Split stdout - 0 newlines, big line, objectMode, preserveNewlines', testLines, 1, bigChunks, bigChunks, bigChunks, true, false, execa);118-test('Split stdout - 0 newlines, many chunks, objectMode, preserveNewlines', testLines, 1, manyChunks, manyLines, manyLines, true, false, execa);119-test('Split stdout - n newlines, 1 chunk, sync', testLines, 1, simpleChunks, simpleLines, simpleFull, false, true, execaSync);120-test('Split stderr - n newlines, 1 chunk, sync', testLines, 2, simpleChunks, simpleLines, simpleFull, false, true, execaSync);121-test('Split stdio[*] - n newlines, 1 chunk, sync', testLines, 3, simpleChunks, simpleLines, simpleFull, false, true, execaSync);122-test('Split stdout - preserveNewlines, n chunks, sync', testLines, 1, noNewlinesChunks, noNewlinesLines, noNewlinesFull, false, true, execaSync);123-test('Split stdout - 0 newlines, 1 chunk, sync', testLines, 1, singleChunks, singleChunks, singleFull, false, true, execaSync);124-test('Split stdout - empty, 1 chunk, sync', testLines, 1, emptyChunks, noLines, emptyFull, false, true, execaSync);125-test('Split stdout - Windows newlines, sync', testLines, 1, windowsChunks, windowsLines, windowsFull, false, true, execaSync);126-test('Split stdout - chunk ends with newline, sync', testLines, 1, simpleFullEndChunks, simpleFullEndLines, simpleFullEnd, false, true, execaSync);127-test('Split stdout - single newline, sync', testLines, 1, newlineChunks, newlineChunks, newlineFull, false, true, execaSync);128-test('Split stdout - only newlines, sync', testLines, 1, newlinesChunks, newlinesLines, newlinesFull, false, true, execaSync);129-test('Split stdout - only Windows newlines, sync', testLines, 1, windowsNewlinesChunks, windowsNewlinesLines, windowsNewlinesFull, false, true, execaSync);130-test('Split stdout - line split over multiple chunks, sync', testLines, 1, runOverChunks, simpleLines, simpleFull, false, true, execaSync);131-test('Split stdout - 0 newlines, big line, sync', testLines, 1, bigChunks, bigChunks, bigFull, false, true, execaSync);132-test('Split stdout - 0 newlines, many chunks, sync', testLines, 1, manyChunks, manyLines, manyFull, false, true, execaSync);133-test('Split stdout - n newlines, 1 chunk, objectMode, sync', testLines, 1, simpleChunks, simpleLines, simpleLines, true, true, execaSync);134-test('Split stderr - n newlines, 1 chunk, objectMode, sync', testLines, 2, simpleChunks, simpleLines, simpleLines, true, true, execaSync);135-test('Split stdio[*] - n newlines, 1 chunk, objectMode, sync', testLines, 3, simpleChunks, simpleLines, simpleLines, true, true, execaSync);136-test('Split stdout - preserveNewlines, n chunks, objectMode, sync', testLines, 1, noNewlinesChunks, noNewlinesLines, noNewlinesLines, true, true, execaSync);137-test('Split stdout - empty, 1 chunk, objectMode, sync', testLines, 1, emptyChunks, noLines, noLines, true, true, execaSync);138-test('Split stdout - 0 newlines, 1 chunk, objectMode, sync', testLines, 1, singleChunks, singleChunks, singleChunks, true, true, execaSync);139-test('Split stdout - Windows newlines, objectMode, sync', testLines, 1, windowsChunks, windowsLines, windowsLines, true, true, execaSync);140-test('Split stdout - chunk ends with newline, objectMode, sync', testLines, 1, simpleFullEndChunks, simpleFullEndLines, simpleFullEndLines, true, true, execaSync);141-test('Split stdout - single newline, objectMode, sync', testLines, 1, newlineChunks, newlineChunks, newlineChunks, true, true, execaSync);142-test('Split stdout - only newlines, objectMode, sync', testLines, 1, newlinesChunks, newlinesLines, newlinesLines, true, true, execaSync);143-test('Split stdout - only Windows newlines, objectMode, sync', testLines, 1, windowsNewlinesChunks, windowsNewlinesLines, windowsNewlinesLines, true, true, execaSync);144-test('Split stdout - line split over multiple chunks, objectMode, sync', testLines, 1, runOverChunks, simpleLines, simpleLines, true, true, execaSync);145-test('Split stdout - 0 newlines, big line, objectMode, sync', testLines, 1, bigChunks, bigChunks, bigChunks, true, true, execaSync);146-test('Split stdout - 0 newlines, many chunks, objectMode, sync', testLines, 1, manyChunks, manyLines, manyLines, true, true, execaSync);147-test('Split stdout - n newlines, 1 chunk, preserveNewlines, sync', testLines, 1, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, execaSync);148-test('Split stderr - n newlines, 1 chunk, preserveNewlines, sync', testLines, 2, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, execaSync);149-test('Split stdio[*] - n newlines, 1 chunk, preserveNewlines, sync', testLines, 3, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, execaSync);150-test('Split stdout - preserveNewlines, n chunks, preserveNewlines, sync', testLines, 1, noNewlinesChunks, noNewlinesLines, noNewlinesFullEnd, false, false, execaSync);151-test('Split stdout - empty, 1 chunk, preserveNewlines, sync', testLines, 1, emptyChunks, noLines, emptyFull, false, false, execaSync);152-test('Split stdout - 0 newlines, 1 chunk, preserveNewlines, sync', testLines, 1, singleChunks, singleChunks, singleFullEnd, false, false, execaSync);153-test('Split stdout - Windows newlines, preserveNewlines, sync', testLines, 1, windowsChunks, noNewlinesChunks, windowsFullEnd, false, false, execaSync);154-test('Split stdout - chunk ends with newline, preserveNewlines, sync', testLines, 1, simpleFullEndChunks, noNewlinesChunks, simpleFullEnd, false, false, execaSync);155-test('Split stdout - single newline, preserveNewlines, sync', testLines, 1, newlineChunks, emptyChunks, newlineFull, false, false, execaSync);156-test('Split stdout - only newlines, preserveNewlines, sync', testLines, 1, newlinesChunks, manyEmptyChunks, newlinesFull, false, false, execaSync);157-test('Split stdout - only Windows newlines, preserveNewlines, sync', testLines, 1, windowsNewlinesChunks, manyEmptyChunks, windowsNewlinesFull, false, false, execaSync);158-test('Split stdout - line split over multiple chunks, preserveNewlines, sync', testLines, 1, runOverChunks, noNewlinesChunks, simpleFullEnd, false, false, execaSync);159-test('Split stdout - 0 newlines, big line, preserveNewlines, sync', testLines, 1, bigChunks, bigChunks, bigFullEnd, false, false, execaSync);160-test('Split stdout - 0 newlines, many chunks, preserveNewlines, sync', testLines, 1, manyChunks, manyLines, manyFullEnd, false, false, execaSync);161-test('Split stdout - n newlines, 1 chunk, objectMode, preserveNewlines, sync', testLines, 1, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, execaSync);162-test('Split stderr - n newlines, 1 chunk, objectMode, preserveNewlines, sync', testLines, 2, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, execaSync);163-test('Split stdio[*] - n newlines, 1 chunk, objectMode, preserveNewlines, sync', testLines, 3, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, execaSync);164-test('Split stdout - preserveNewlines, n chunks, objectMode, preserveNewlines, sync', testLines, 1, noNewlinesChunks, noNewlinesLines, noNewlinesLines, true, false, execaSync);165-test('Split stdout - empty, 1 chunk, objectMode, preserveNewlines, sync', testLines, 1, emptyChunks, noLines, noLines, true, false, execaSync);166-test('Split stdout - 0 newlines, 1 chunk, objectMode, preserveNewlines, sync', testLines, 1, singleChunks, singleChunks, singleChunks, true, false, execaSync);167-test('Split stdout - Windows newlines, objectMode, preserveNewlines, sync', testLines, 1, windowsChunks, noNewlinesChunks, noNewlinesChunks, true, false, execaSync);168-test('Split stdout - chunk ends with newline, objectMode, preserveNewlines, sync', testLines, 1, simpleFullEndChunks, noNewlinesChunks, noNewlinesChunks, true, false, execaSync);169-test('Split stdout - single newline, objectMode, preserveNewlines, sync', testLines, 1, newlineChunks, emptyChunks, emptyChunks, true, false, execaSync);170-test('Split stdout - only newlines, objectMode, preserveNewlines, sync', testLines, 1, newlinesChunks, manyEmptyChunks, manyEmptyChunks, true, false, execaSync);171-test('Split stdout - only Windows newlines, objectMode, preserveNewlines, sync', testLines, 1, windowsNewlinesChunks, manyEmptyChunks, manyEmptyChunks, true, false, execaSync);172-test('Split stdout - line split over multiple chunks, objectMode, preserveNewlines, sync', testLines, 1, runOverChunks, noNewlinesChunks, noNewlinesChunks, true, false, execaSync);173-test('Split stdout - 0 newlines, big line, objectMode, preserveNewlines, sync', testLines, 1, bigChunks, bigChunks, bigChunks, true, false, execaSync);174-test('Split stdout - 0 newlines, many chunks, objectMode, preserveNewlines, sync', testLines, 1, manyChunks, manyLines, manyLines, true, false, execaSync);deleted:test/stdio/split-newline.js-37 removed
1-import test from 'ava';2-import {execa, execaSync} from '../../index.js';3-import {setFixtureDir} from '../helpers/fixtures-dir.js';4-import {getOutputsGenerator, noopGenerator, noopAsyncGenerator} from '../helpers/generator.js';5-import {singleFull, singleFullEnd} from '../helpers/lines.js';6-7-setFixtureDir();8-9-const singleFullEndWindows = `${singleFull}\r\n`;10-const mixedNewlines = '.\n.\r\n.\n.\r\n.\n';11-12-const testStripNewline = async (t, input, expectedOutput, execaMethod) => {13- const {stdout} = await execaMethod('noop.js', {14- stdout: getOutputsGenerator([input])(),15- stripFinalNewline: false,16- });17- t.is(stdout, expectedOutput);18-};19-20-test('Strips newline when user do not mistakenly yield one at the end', testStripNewline, singleFull, singleFullEnd, execa);21-test('Strips newline when user mistakenly yielded one at the end', testStripNewline, singleFullEnd, singleFullEnd, execa);22-test('Strips newline when user mistakenly yielded one at the end, Windows newline', testStripNewline, singleFullEndWindows, singleFullEndWindows, execa);23-test('Strips newline when user do not mistakenly yield one at the end, sync', testStripNewline, singleFull, singleFullEnd, execaSync);24-test('Strips newline when user mistakenly yielded one at the end, sync', testStripNewline, singleFullEnd, singleFullEnd, execaSync);25-test('Strips newline when user mistakenly yielded one at the end, Windows newline, sync', testStripNewline, singleFullEndWindows, singleFullEndWindows, execaSync);26-27-const testMixNewlines = async (t, generator, execaMethod) => {28- const {stdout} = await execaMethod('noop-fd.js', ['1', mixedNewlines], {29- stdout: generator(),30- stripFinalNewline: false,31- });32- t.is(stdout, mixedNewlines);33-};34-35-test('Can mix Unix and Windows newlines', testMixNewlines, noopGenerator, execa);36-test('Can mix Unix and Windows newlines, sync', testMixNewlines, noopGenerator, execaSync);37-test('Can mix Unix and Windows newlines, async', testMixNewlines, noopAsyncGenerator, execa);deleted:test/stdio/split-transform.js-78 removed
1-import test from 'ava';2-import {execa, execaSync} from '../../index.js';3-import {setFixtureDir} from '../helpers/fixtures-dir.js';4-import {getOutputsGenerator, resultGenerator} from '../helpers/generator.js';5-import {foobarString, foobarUint8Array, foobarObject, foobarObjectString} from '../helpers/input.js';6-7-setFixtureDir();8-9-const resultUint8ArrayGenerator = function * (lines, chunk) {10- lines.push(chunk);11- yield new TextEncoder().encode(chunk);12-};13-14-// eslint-disable-next-line max-params15-const testStringToUint8Array = async (t, expectedOutput, objectMode, preserveNewlines, execaMethod) => {16- const lines = [];17- const {stdout} = await execaMethod('noop-fd.js', ['1', foobarString], {18- stdout: {19- transform: resultUint8ArrayGenerator.bind(undefined, lines),20- objectMode,21- preserveNewlines,22- },23- lines: true,24- });25- t.deepEqual(lines, [foobarString]);26- t.deepEqual(stdout, expectedOutput);27-};28-29-test('Line splitting when converting from string to Uint8Array', testStringToUint8Array, [foobarString], false, true, execa);30-test('Line splitting when converting from string to Uint8Array, objectMode', testStringToUint8Array, [foobarUint8Array], true, true, execa);31-test('Line splitting when converting from string to Uint8Array, preserveNewlines', testStringToUint8Array, [foobarString], false, false, execa);32-test('Line splitting when converting from string to Uint8Array, objectMode, preserveNewlines', testStringToUint8Array, [foobarUint8Array], true, false, execa);33-test('Line splitting when converting from string to Uint8Array, sync', testStringToUint8Array, [foobarString], false, true, execaSync);34-test('Line splitting when converting from string to Uint8Array, objectMode, sync', testStringToUint8Array, [foobarUint8Array], true, true, execaSync);35-test('Line splitting when converting from string to Uint8Array, preserveNewlines, sync', testStringToUint8Array, [foobarString], false, false, execaSync);36-test('Line splitting when converting from string to Uint8Array, objectMode, preserveNewlines, sync', testStringToUint8Array, [foobarUint8Array], true, false, execaSync);37-38-const serializeResultGenerator = function * (lines, chunk) {39- lines.push(chunk);40- yield JSON.stringify(chunk);41-};42-43-const testUnsetObjectMode = async (t, expectedOutput, preserveNewlines, execaMethod) => {44- const lines = [];45- const {stdout} = await execaMethod('noop.js', {46- stdout: [47- getOutputsGenerator([foobarObject])(true),48- {transform: serializeResultGenerator.bind(undefined, lines), preserveNewlines, objectMode: false},49- ],50- stripFinalNewline: false,51- });52- t.deepEqual(lines, [foobarObject]);53- t.is(stdout, expectedOutput);54-};55-56-test('Can switch from objectMode to non-objectMode', testUnsetObjectMode, `${foobarObjectString}\n`, false, execa);57-test('Can switch from objectMode to non-objectMode, preserveNewlines', testUnsetObjectMode, foobarObjectString, true, execa);58-test('Can switch from objectMode to non-objectMode, sync', testUnsetObjectMode, `${foobarObjectString}\n`, false, execaSync);59-test('Can switch from objectMode to non-objectMode, preserveNewlines, sync', testUnsetObjectMode, foobarObjectString, true, execaSync);60-61-// eslint-disable-next-line max-params62-const testYieldArray = async (t, input, expectedLines, expectedOutput, execaMethod) => {63- const lines = [];64- const {stdout} = await execaMethod('noop.js', {65- stdout: [66- getOutputsGenerator(input)(),67- resultGenerator(lines)(),68- ],69- stripFinalNewline: false,70- });71- t.deepEqual(lines, expectedLines);72- t.deepEqual(stdout, expectedOutput);73-};74-75-test('Can use "yield* array" to produce multiple lines', testYieldArray, [foobarString, foobarString], [foobarString, foobarString], `${foobarString}\n${foobarString}\n`, execa);76-test('Can use "yield* array" to produce empty lines', testYieldArray, [foobarString, ''], [foobarString, ''], `${foobarString}\n\n`, execa);77-test('Can use "yield* array" to produce multiple lines, sync', testYieldArray, [foobarString, foobarString], [foobarString, foobarString], `${foobarString}\n${foobarString}\n`, execaSync);78-test('Can use "yield* array" to produce empty lines, sync', testYieldArray, [foobarString, ''], [foobarString, ''], `${foobarString}\n\n`, execaSync);added:test/stdio/stdio-option.js+57 added
1+import {inspect} from 'node:util';2+import test from 'ava';3+import {normalizeStdioOption} from '../../lib/stdio/stdio-option.js';4+5+const macro = (t, input, expected, func) => {6+ if (expected instanceof Error) {7+ t.throws(() => {8+ normalizeStdioOption(input);9+ }, {message: expected.message});10+ return;11+ }12+13+ t.deepEqual(func(input), expected);14+};15+16+const macroTitle = name => (title, input) => `${name} ${(inspect(input))}`;17+18+const stdioMacro = (...args) => macro(...args, normalizeStdioOption);19+stdioMacro.title = macroTitle('execa()');20+21+test(stdioMacro, {stdio: 'inherit'}, ['inherit', 'inherit', 'inherit']);22+test(stdioMacro, {stdio: 'pipe'}, ['pipe', 'pipe', 'pipe']);23+test(stdioMacro, {stdio: 'ignore'}, ['ignore', 'ignore', 'ignore']);24+25+test(stdioMacro, {}, ['pipe', 'pipe', 'pipe']);26+test(stdioMacro, {stdio: []}, ['pipe', 'pipe', 'pipe']);27+test(stdioMacro, {stdio: [0]}, [0, 'pipe', 'pipe']);28+test(stdioMacro, {stdio: [0, 1]}, [0, 1, 'pipe']);29+test(stdioMacro, {stdio: [0, 1, 2]}, [0, 1, 2]);30+test(stdioMacro, {stdio: [0, 1, 2, 3]}, [0, 1, 2, 3]);31+test(stdioMacro, {stdio: [undefined, 1, 2]}, ['pipe', 1, 2]);32+test(stdioMacro, {stdio: [null, 1, 2]}, ['pipe', 1, 2]);33+test(stdioMacro, {stdio: [0, undefined, 2]}, [0, 'pipe', 2]);34+test(stdioMacro, {stdio: [0, null, 2]}, [0, 'pipe', 2]);35+test(stdioMacro, {stdio: [0, 1, undefined]}, [0, 1, 'pipe']);36+test(stdioMacro, {stdio: [0, 1, null]}, [0, 1, 'pipe']);37+test(stdioMacro, {stdio: [0, 1, 2, undefined]}, [0, 1, 2, 'ignore']);38+test(stdioMacro, {stdio: [0, 1, 2, null]}, [0, 1, 2, 'ignore']);39+40+test(stdioMacro, {stdin: 'pipe'}, ['pipe', 'pipe', 'pipe']);41+test(stdioMacro, {stdout: 'ignore'}, ['pipe', 'ignore', 'pipe']);42+test(stdioMacro, {stderr: 'inherit'}, ['pipe', 'pipe', 'inherit']);43+test(stdioMacro, {stdin: 'pipe', stdout: 'ignore', stderr: 'inherit'}, ['pipe', 'ignore', 'inherit']);44+test(stdioMacro, {stdin: 'pipe', stdout: 'ignore'}, ['pipe', 'ignore', 'pipe']);45+test(stdioMacro, {stdin: 'pipe', stderr: 'inherit'}, ['pipe', 'pipe', 'inherit']);46+test(stdioMacro, {stdout: 'ignore', stderr: 'inherit'}, ['pipe', 'ignore', 'inherit']);47+test(stdioMacro, {stdin: 0, stdout: 1, stderr: 2}, [0, 1, 2]);48+test(stdioMacro, {stdin: 0, stdout: 1}, [0, 1, 'pipe']);49+test(stdioMacro, {stdin: 0, stderr: 2}, [0, 'pipe', 2]);50+test(stdioMacro, {stdout: 1, stderr: 2}, ['pipe', 1, 2]);51+52+test(stdioMacro, {stdio: {foo: 'bar'}}, new TypeError('Expected `stdio` to be of type `string` or `Array`, got `object`'));53+54+test(stdioMacro, {stdin: 'inherit', stdio: 'pipe'}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));55+test(stdioMacro, {stdin: 'inherit', stdio: ['pipe']}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));56+test(stdioMacro, {stdin: 'inherit', stdio: [undefined, 'pipe']}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));57+test(stdioMacro, {stdin: 0, stdio: 'pipe'}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));deleted:test/stdio/transform-all.js-224 removed
1-import {Buffer} from 'node:buffer';2-import test from 'ava';3-import {execa, execaSync} from '../../index.js';4-import {setFixtureDir} from '../helpers/fixtures-dir.js';5-import {foobarObject} from '../helpers/input.js';6-import {7- outputObjectGenerator,8- uppercaseGenerator,9- uppercaseBufferGenerator,10-} from '../helpers/generator.js';11-12-setFixtureDir();13-14-const textEncoder = new TextEncoder();15-16-const getAllStdioOption = (stdioOption, encoding, objectMode) => {17- if (stdioOption) {18- return 'pipe';19- }20-21- if (objectMode) {22- return outputObjectGenerator();23- }24-25- return encoding === 'utf8' ? uppercaseGenerator() : uppercaseBufferGenerator();26-};27-28-const getStdoutStderrOutput = ({output, stdioOption, encoding, objectMode, lines}) => {29- if (objectMode && !stdioOption) {30- return encoding === 'utf8' ? [foobarObject, foobarObject] : [foobarObject];31- }32-33- const stdioOutput = stdioOption ? output : output.toUpperCase();34-35- if (encoding === 'hex') {36- return Buffer.from(stdioOutput).toString('hex');37- }38-39- if (encoding === 'buffer') {40- return textEncoder.encode(stdioOutput);41- }42-43- return lines ? stdioOutput.trim().split('\n').map(string => `${string}\n`) : stdioOutput;44-};45-46-const getAllOutput = ({stdoutOutput, stderrOutput, encoding, objectMode, lines}) => {47- if (objectMode || (lines && encoding === 'utf8')) {48- return [stdoutOutput, stderrOutput].flat();49- }50-51- return encoding === 'buffer'52- ? new Uint8Array([...stdoutOutput, ...stderrOutput])53- : `${stdoutOutput}${stderrOutput}`;54-};55-56-// eslint-disable-next-line max-params57-const testGeneratorAll = async (t, reject, encoding, objectMode, stdoutOption, stderrOption, lines, execaMethod) => {58- const fixtureName = reject ? 'all.js' : 'all-fail.js';59- const {stdout, stderr, all} = await execaMethod(fixtureName, {60- all: true,61- reject,62- stdout: getAllStdioOption(stdoutOption, encoding, objectMode),63- stderr: getAllStdioOption(stderrOption, encoding, objectMode),64- encoding,65- lines,66- stripFinalNewline: false,67- });68-69- const stdoutOutput = getStdoutStderrOutput({output: 'std\nout\n', stdioOption: stdoutOption, encoding, objectMode, lines});70- t.deepEqual(stdout, stdoutOutput);71- const stderrOutput = getStdoutStderrOutput({output: 'std\nerr\n', stdioOption: stderrOption, encoding, objectMode, lines});72- t.deepEqual(stderr, stderrOutput);73- const allOutput = getAllOutput({stdoutOutput, stderrOutput, encoding, objectMode, lines});74- if (Array.isArray(all) && Array.isArray(allOutput)) {75- t.deepEqual([...all].sort(), [...allOutput].sort());76- } else {77- t.deepEqual(all, allOutput);78- }79-};80-81-test('Can use generators with result.all = transform + transform', testGeneratorAll, true, 'utf8', false, false, false, false, execa);82-test('Can use generators with error.all = transform + transform', testGeneratorAll, false, 'utf8', false, false, false, false, execa);83-test('Can use generators with result.all = transform + transform, encoding "buffer"', testGeneratorAll, true, 'buffer', false, false, false, false, execa);84-test('Can use generators with error.all = transform + transform, encoding "buffer"', testGeneratorAll, false, 'buffer', false, false, false, false, execa);85-test('Can use generators with result.all = transform + transform, encoding "hex"', testGeneratorAll, true, 'hex', false, false, false, false, execa);86-test('Can use generators with error.all = transform + transform, encoding "hex"', testGeneratorAll, false, 'hex', false, false, false, false, execa);87-test('Can use generators with result.all = transform + pipe', testGeneratorAll, true, 'utf8', false, false, true, false, execa);88-test('Can use generators with error.all = transform + pipe', testGeneratorAll, false, 'utf8', false, false, true, false, execa);89-test('Can use generators with result.all = transform + pipe, encoding "buffer"', testGeneratorAll, true, 'buffer', false, false, true, false, execa);90-test('Can use generators with error.all = transform + pipe, encoding "buffer"', testGeneratorAll, false, 'buffer', false, false, true, false, execa);91-test('Can use generators with result.all = transform + pipe, encoding "hex"', testGeneratorAll, true, 'hex', false, false, true, false, execa);92-test('Can use generators with error.all = transform + pipe, encoding "hex"', testGeneratorAll, false, 'hex', false, false, true, false, execa);93-test('Can use generators with result.all = pipe + transform', testGeneratorAll, true, 'utf8', false, true, false, false, execa);94-test('Can use generators with error.all = pipe + transform', testGeneratorAll, false, 'utf8', false, true, false, false, execa);95-test('Can use generators with result.all = pipe + transform, encoding "buffer"', testGeneratorAll, true, 'buffer', false, true, false, false, execa);96-test('Can use generators with error.all = pipe + transform, encoding "buffer"', testGeneratorAll, false, 'buffer', false, true, false, false, execa);97-test('Can use generators with result.all = pipe + transform, encoding "hex"', testGeneratorAll, true, 'hex', false, true, false, false, execa);98-test('Can use generators with error.all = pipe + transform, encoding "hex"', testGeneratorAll, false, 'hex', false, true, false, false, execa);99-test('Can use generators with result.all = transform + transform, objectMode', testGeneratorAll, true, 'utf8', true, false, false, false, execa);100-test('Can use generators with error.all = transform + transform, objectMode', testGeneratorAll, false, 'utf8', true, false, false, false, execa);101-test('Can use generators with result.all = transform + transform, objectMode, encoding "buffer"', testGeneratorAll, true, 'buffer', true, false, false, false, execa);102-test('Can use generators with error.all = transform + transform, objectMode, encoding "buffer"', testGeneratorAll, false, 'buffer', true, false, false, false, execa);103-test('Can use generators with result.all = transform + transform, objectMode, encoding "hex"', testGeneratorAll, true, 'hex', true, false, false, false, execa);104-test('Can use generators with error.all = transform + transform, objectMode, encoding "hex"', testGeneratorAll, false, 'hex', true, false, false, false, execa);105-test('Can use generators with result.all = transform + pipe, objectMode', testGeneratorAll, true, 'utf8', true, false, true, false, execa);106-test('Can use generators with error.all = transform + pipe, objectMode', testGeneratorAll, false, 'utf8', true, false, true, false, execa);107-test('Can use generators with result.all = transform + pipe, objectMode, encoding "buffer"', testGeneratorAll, true, 'buffer', true, false, true, false, execa);108-test('Can use generators with error.all = transform + pipe, objectMode, encoding "buffer"', testGeneratorAll, false, 'buffer', true, false, true, false, execa);109-test('Can use generators with result.all = transform + pipe, objectMode, encoding "hex"', testGeneratorAll, true, 'hex', true, false, true, false, execa);110-test('Can use generators with error.all = transform + pipe, objectMode, encoding "hex"', testGeneratorAll, false, 'hex', true, false, true, false, execa);111-test('Can use generators with result.all = pipe + transform, objectMode', testGeneratorAll, true, 'utf8', true, true, false, false, execa);112-test('Can use generators with error.all = pipe + transform, objectMode', testGeneratorAll, false, 'utf8', true, true, false, false, execa);113-test('Can use generators with result.all = pipe + transform, objectMode, encoding "buffer"', testGeneratorAll, true, 'buffer', true, true, false, false, execa);114-test('Can use generators with error.all = pipe + transform, objectMode, encoding "buffer"', testGeneratorAll, false, 'buffer', true, true, false, false, execa);115-test('Can use generators with result.all = pipe + transform, objectMode, encoding "hex"', testGeneratorAll, true, 'hex', true, true, false, false, execa);116-test('Can use generators with error.all = pipe + transform, objectMode, encoding "hex"', testGeneratorAll, false, 'hex', true, true, false, false, execa);117-test('Can use generators with result.all = transform + transform, sync', testGeneratorAll, true, 'utf8', false, false, false, false, execaSync);118-test('Can use generators with error.all = transform + transform, sync', testGeneratorAll, false, 'utf8', false, false, false, false, execaSync);119-test('Can use generators with result.all = transform + transform, encoding "buffer", sync', testGeneratorAll, true, 'buffer', false, false, false, false, execaSync);120-test('Can use generators with error.all = transform + transform, encoding "buffer", sync', testGeneratorAll, false, 'buffer', false, false, false, false, execaSync);121-test('Can use generators with result.all = transform + transform, encoding "hex", sync', testGeneratorAll, true, 'hex', false, false, false, false, execaSync);122-test('Can use generators with error.all = transform + transform, encoding "hex", sync', testGeneratorAll, false, 'hex', false, false, false, false, execaSync);123-test('Can use generators with result.all = transform + pipe, sync', testGeneratorAll, true, 'utf8', false, false, true, false, execaSync);124-test('Can use generators with error.all = transform + pipe, sync', testGeneratorAll, false, 'utf8', false, false, true, false, execaSync);125-test('Can use generators with result.all = transform + pipe, encoding "buffer", sync', testGeneratorAll, true, 'buffer', false, false, true, false, execaSync);126-test('Can use generators with error.all = transform + pipe, encoding "buffer", sync', testGeneratorAll, false, 'buffer', false, false, true, false, execaSync);127-test('Can use generators with result.all = transform + pipe, encoding "hex", sync', testGeneratorAll, true, 'hex', false, false, true, false, execaSync);128-test('Can use generators with error.all = transform + pipe, encoding "hex", sync', testGeneratorAll, false, 'hex', false, false, true, false, execaSync);129-test('Can use generators with result.all = pipe + transform, sync', testGeneratorAll, true, 'utf8', false, true, false, false, execaSync);130-test('Can use generators with error.all = pipe + transform, sync', testGeneratorAll, false, 'utf8', false, true, false, false, execaSync);131-test('Can use generators with result.all = pipe + transform, encoding "buffer", sync', testGeneratorAll, true, 'buffer', false, true, false, false, execaSync);132-test('Can use generators with error.all = pipe + transform, encoding "buffer", sync', testGeneratorAll, false, 'buffer', false, true, false, false, execaSync);133-test('Can use generators with result.all = pipe + transform, encoding "hex", sync', testGeneratorAll, true, 'hex', false, true, false, false, execaSync);134-test('Can use generators with error.all = pipe + transform, encoding "hex", sync', testGeneratorAll, false, 'hex', false, true, false, false, execaSync);135-test('Can use generators with result.all = transform + transform, objectMode, sync', testGeneratorAll, true, 'utf8', true, false, false, false, execaSync);136-test('Can use generators with error.all = transform + transform, objectMode, sync', testGeneratorAll, false, 'utf8', true, false, false, false, execaSync);137-test('Can use generators with result.all = transform + transform, objectMode, encoding "buffer", sync', testGeneratorAll, true, 'buffer', true, false, false, false, execaSync);138-test('Can use generators with error.all = transform + transform, objectMode, encoding "buffer", sync', testGeneratorAll, false, 'buffer', true, false, false, false, execaSync);139-test('Can use generators with result.all = transform + transform, objectMode, encoding "hex", sync', testGeneratorAll, true, 'hex', true, false, false, false, execaSync);140-test('Can use generators with error.all = transform + transform, objectMode, encoding "hex", sync', testGeneratorAll, false, 'hex', true, false, false, false, execaSync);141-test('Can use generators with result.all = transform + pipe, objectMode, sync', testGeneratorAll, true, 'utf8', true, false, true, false, execaSync);142-test('Can use generators with error.all = transform + pipe, objectMode, sync', testGeneratorAll, false, 'utf8', true, false, true, false, execaSync);143-test('Can use generators with result.all = transform + pipe, objectMode, encoding "buffer", sync', testGeneratorAll, true, 'buffer', true, false, true, false, execaSync);144-test('Can use generators with error.all = transform + pipe, objectMode, encoding "buffer", sync', testGeneratorAll, false, 'buffer', true, false, true, false, execaSync);145-test('Can use generators with result.all = transform + pipe, objectMode, encoding "hex", sync', testGeneratorAll, true, 'hex', true, false, true, false, execaSync);146-test('Can use generators with error.all = transform + pipe, objectMode, encoding "hex", sync', testGeneratorAll, false, 'hex', true, false, true, false, execaSync);147-test('Can use generators with result.all = pipe + transform, objectMode, sync', testGeneratorAll, true, 'utf8', true, true, false, false, execaSync);148-test('Can use generators with error.all = pipe + transform, objectMode, sync', testGeneratorAll, false, 'utf8', true, true, false, false, execaSync);149-test('Can use generators with result.all = pipe + transform, objectMode, encoding "buffer", sync', testGeneratorAll, true, 'buffer', true, true, false, false, execaSync);150-test('Can use generators with error.all = pipe + transform, objectMode, encoding "buffer", sync', testGeneratorAll, false, 'buffer', true, true, false, false, execaSync);151-test('Can use generators with result.all = pipe + transform, objectMode, encoding "hex", sync', testGeneratorAll, true, 'hex', true, true, false, false, execaSync);152-test('Can use generators with error.all = pipe + transform, objectMode, encoding "hex", sync', testGeneratorAll, false, 'hex', true, true, false, false, execaSync);153-test('Can use generators with result.all = transform + transform, lines', testGeneratorAll, true, 'utf8', false, false, false, true, execa);154-test('Can use generators with error.all = transform + transform, lines', testGeneratorAll, false, 'utf8', false, false, false, true, execa);155-test('Can use generators with result.all = transform + transform, encoding "buffer", lines', testGeneratorAll, true, 'buffer', false, false, false, true, execa);156-test('Can use generators with error.all = transform + transform, encoding "buffer", lines', testGeneratorAll, false, 'buffer', false, false, false, true, execa);157-test('Can use generators with result.all = transform + transform, encoding "hex", lines', testGeneratorAll, true, 'hex', false, false, false, true, execa);158-test('Can use generators with error.all = transform + transform, encoding "hex", lines', testGeneratorAll, false, 'hex', false, false, false, true, execa);159-test('Can use generators with result.all = transform + pipe, lines', testGeneratorAll, true, 'utf8', false, false, true, true, execa);160-test('Can use generators with error.all = transform + pipe, lines', testGeneratorAll, false, 'utf8', false, false, true, true, execa);161-test('Can use generators with result.all = transform + pipe, encoding "buffer", lines', testGeneratorAll, true, 'buffer', false, false, true, true, execa);162-test('Can use generators with error.all = transform + pipe, encoding "buffer", lines', testGeneratorAll, false, 'buffer', false, false, true, true, execa);163-test('Can use generators with result.all = transform + pipe, encoding "hex", lines', testGeneratorAll, true, 'hex', false, false, true, true, execa);164-test('Can use generators with error.all = transform + pipe, encoding "hex", lines', testGeneratorAll, false, 'hex', false, false, true, true, execa);165-test('Can use generators with result.all = pipe + transform, lines', testGeneratorAll, true, 'utf8', false, true, false, true, execa);166-test('Can use generators with error.all = pipe + transform, lines', testGeneratorAll, false, 'utf8', false, true, false, true, execa);167-test('Can use generators with result.all = pipe + transform, encoding "buffer", lines', testGeneratorAll, true, 'buffer', false, true, false, true, execa);168-test('Can use generators with error.all = pipe + transform, encoding "buffer", lines', testGeneratorAll, false, 'buffer', false, true, false, true, execa);169-test('Can use generators with result.all = pipe + transform, encoding "hex", lines', testGeneratorAll, true, 'hex', false, true, false, true, execa);170-test('Can use generators with error.all = pipe + transform, encoding "hex", lines', testGeneratorAll, false, 'hex', false, true, false, true, execa);171-test('Can use generators with result.all = transform + transform, objectMode, lines', testGeneratorAll, true, 'utf8', true, false, false, true, execa);172-test('Can use generators with error.all = transform + transform, objectMode, lines', testGeneratorAll, false, 'utf8', true, false, false, true, execa);173-test('Can use generators with result.all = transform + transform, objectMode, encoding "buffer", lines', testGeneratorAll, true, 'buffer', true, false, false, true, execa);174-test('Can use generators with error.all = transform + transform, objectMode, encoding "buffer", lines', testGeneratorAll, false, 'buffer', true, false, false, true, execa);175-test('Can use generators with result.all = transform + transform, objectMode, encoding "hex", lines', testGeneratorAll, true, 'hex', true, false, false, true, execa);176-test('Can use generators with error.all = transform + transform, objectMode, encoding "hex", lines', testGeneratorAll, false, 'hex', true, false, false, true, execa);177-test('Can use generators with result.all = transform + pipe, objectMode, lines', testGeneratorAll, true, 'utf8', true, false, true, true, execa);178-test('Can use generators with error.all = transform + pipe, objectMode, lines', testGeneratorAll, false, 'utf8', true, false, true, true, execa);179-test('Can use generators with result.all = transform + pipe, objectMode, encoding "buffer", lines', testGeneratorAll, true, 'buffer', true, false, true, true, execa);180-test('Can use generators with error.all = transform + pipe, objectMode, encoding "buffer", lines', testGeneratorAll, false, 'buffer', true, false, true, true, execa);181-test('Can use generators with result.all = transform + pipe, objectMode, encoding "hex", lines', testGeneratorAll, true, 'hex', true, false, true, true, execa);182-test('Can use generators with error.all = transform + pipe, objectMode, encoding "hex", lines', testGeneratorAll, false, 'hex', true, false, true, true, execa);183-test('Can use generators with result.all = pipe + transform, objectMode, lines', testGeneratorAll, true, 'utf8', true, true, false, true, execa);184-test('Can use generators with error.all = pipe + transform, objectMode, lines', testGeneratorAll, false, 'utf8', true, true, false, true, execa);185-test('Can use generators with result.all = pipe + transform, objectMode, encoding "buffer", lines', testGeneratorAll, true, 'buffer', true, true, false, true, execa);186-test('Can use generators with error.all = pipe + transform, objectMode, encoding "buffer", lines', testGeneratorAll, false, 'buffer', true, true, false, true, execa);187-test('Can use generators with result.all = pipe + transform, objectMode, encoding "hex", lines', testGeneratorAll, true, 'hex', true, true, false, true, execa);188-test('Can use generators with error.all = pipe + transform, objectMode, encoding "hex", lines', testGeneratorAll, false, 'hex', true, true, false, true, execa);189-test('Can use generators with result.all = transform + transform, sync, lines', testGeneratorAll, true, 'utf8', false, false, false, true, execaSync);190-test('Can use generators with error.all = transform + transform, sync, lines', testGeneratorAll, false, 'utf8', false, false, false, true, execaSync);191-test('Can use generators with result.all = transform + transform, encoding "buffer", sync, lines', testGeneratorAll, true, 'buffer', false, false, false, true, execaSync);192-test('Can use generators with error.all = transform + transform, encoding "buffer", sync, lines', testGeneratorAll, false, 'buffer', false, false, false, true, execaSync);193-test('Can use generators with result.all = transform + transform, encoding "hex", sync, lines', testGeneratorAll, true, 'hex', false, false, false, true, execaSync);194-test('Can use generators with error.all = transform + transform, encoding "hex", sync, lines', testGeneratorAll, false, 'hex', false, false, false, true, execaSync);195-test('Can use generators with result.all = transform + pipe, sync, lines', testGeneratorAll, true, 'utf8', false, false, true, true, execaSync);196-test('Can use generators with error.all = transform + pipe, sync, lines', testGeneratorAll, false, 'utf8', false, false, true, true, execaSync);197-test('Can use generators with result.all = transform + pipe, encoding "buffer", sync, lines', testGeneratorAll, true, 'buffer', false, false, true, true, execaSync);198-test('Can use generators with error.all = transform + pipe, encoding "buffer", sync, lines', testGeneratorAll, false, 'buffer', false, false, true, true, execaSync);199-test('Can use generators with result.all = transform + pipe, encoding "hex", sync, lines', testGeneratorAll, true, 'hex', false, false, true, true, execaSync);200-test('Can use generators with error.all = transform + pipe, encoding "hex", sync, lines', testGeneratorAll, false, 'hex', false, false, true, true, execaSync);201-test('Can use generators with result.all = pipe + transform, sync, lines', testGeneratorAll, true, 'utf8', false, true, false, true, execaSync);202-test('Can use generators with error.all = pipe + transform, sync, lines', testGeneratorAll, false, 'utf8', false, true, false, true, execaSync);203-test('Can use generators with result.all = pipe + transform, encoding "buffer", sync, lines', testGeneratorAll, true, 'buffer', false, true, false, true, execaSync);204-test('Can use generators with error.all = pipe + transform, encoding "buffer", sync, lines', testGeneratorAll, false, 'buffer', false, true, false, true, execaSync);205-test('Can use generators with result.all = pipe + transform, encoding "hex", sync, lines', testGeneratorAll, true, 'hex', false, true, false, true, execaSync);206-test('Can use generators with error.all = pipe + transform, encoding "hex", sync, lines', testGeneratorAll, false, 'hex', false, true, false, true, execaSync);207-test('Can use generators with result.all = transform + transform, objectMode, sync, lines', testGeneratorAll, true, 'utf8', true, false, false, true, execaSync);208-test('Can use generators with error.all = transform + transform, objectMode, sync, lines', testGeneratorAll, false, 'utf8', true, false, false, true, execaSync);209-test('Can use generators with result.all = transform + transform, objectMode, encoding "buffer", sync, lines', testGeneratorAll, true, 'buffer', true, false, false, true, execaSync);210-test('Can use generators with error.all = transform + transform, objectMode, encoding "buffer", sync, lines', testGeneratorAll, false, 'buffer', true, false, false, true, execaSync);211-test('Can use generators with result.all = transform + transform, objectMode, encoding "hex", sync, lines', testGeneratorAll, true, 'hex', true, false, false, true, execaSync);212-test('Can use generators with error.all = transform + transform, objectMode, encoding "hex", sync, lines', testGeneratorAll, false, 'hex', true, false, false, true, execaSync);213-test('Can use generators with result.all = transform + pipe, objectMode, sync, lines', testGeneratorAll, true, 'utf8', true, false, true, true, execaSync);214-test('Can use generators with error.all = transform + pipe, objectMode, sync, lines', testGeneratorAll, false, 'utf8', true, false, true, true, execaSync);215-test('Can use generators with result.all = transform + pipe, objectMode, encoding "buffer", sync, lines', testGeneratorAll, true, 'buffer', true, false, true, true, execaSync);216-test('Can use generators with error.all = transform + pipe, objectMode, encoding "buffer", sync, lines', testGeneratorAll, false, 'buffer', true, false, true, true, execaSync);217-test('Can use generators with result.all = transform + pipe, objectMode, encoding "hex", sync, lines', testGeneratorAll, true, 'hex', true, false, true, true, execaSync);218-test('Can use generators with error.all = transform + pipe, objectMode, encoding "hex", sync, lines', testGeneratorAll, false, 'hex', true, false, true, true, execaSync);219-test('Can use generators with result.all = pipe + transform, objectMode, sync, lines', testGeneratorAll, true, 'utf8', true, true, false, true, execaSync);220-test('Can use generators with error.all = pipe + transform, objectMode, sync, lines', testGeneratorAll, false, 'utf8', true, true, false, true, execaSync);221-test('Can use generators with result.all = pipe + transform, objectMode, encoding "buffer", sync, lines', testGeneratorAll, true, 'buffer', true, true, false, true, execaSync);222-test('Can use generators with error.all = pipe + transform, objectMode, encoding "buffer", sync, lines', testGeneratorAll, false, 'buffer', true, true, false, true, execaSync);223-test('Can use generators with result.all = pipe + transform, objectMode, encoding "hex", sync, lines', testGeneratorAll, true, 'hex', true, true, false, true, execaSync);224-test('Can use generators with error.all = pipe + transform, objectMode, encoding "hex", sync, lines', testGeneratorAll, false, 'hex', true, true, false, true, execaSync);deleted:test/stdio/transform-error.js-89 removed
1-import {once} from 'node:events';2-import test from 'ava';3-import {execa, execaSync} from '../../index.js';4-import {foobarString} from '../helpers/input.js';5-import {noopGenerator, infiniteGenerator, convertTransformToFinal} from '../helpers/generator.js';6-import {generatorsMap} from '../helpers/map.js';7-import {setFixtureDir} from '../helpers/fixtures-dir.js';8-9-setFixtureDir();10-11-const assertProcessError = async (t, type, execaMethod, getSubprocess) => {12- const cause = new Error(foobarString);13- const transform = generatorsMap[type].throwing(cause)();14- const error = execaMethod === execa15- ? await t.throwsAsync(getSubprocess(transform))16- : t.throws(() => {17- getSubprocess(transform);18- });19- t.is(error.cause, cause);20-};21-22-const testThrowingGenerator = async (t, type, final, execaMethod) => {23- await assertProcessError(t, type, execaMethod, transform => execaMethod('noop.js', {24- stdout: convertTransformToFinal(transform, final),25- }));26-};27-28-test('Generators "transform" errors make subprocess fail', testThrowingGenerator, 'generator', false, execa);29-test('Generators "final" errors make subprocess fail', testThrowingGenerator, 'generator', true, execa);30-test('Generators "transform" errors make subprocess fail, sync', testThrowingGenerator, 'generator', false, execaSync);31-test('Generators "final" errors make subprocess fail, sync', testThrowingGenerator, 'generator', true, execaSync);32-test('Duplexes "transform" errors make subprocess fail', testThrowingGenerator, 'duplex', false, execa);33-test('WebTransform "transform" errors make subprocess fail', testThrowingGenerator, 'webTransform', false, execa);34-35-const testSingleErrorOutput = async (t, type, execaMethod) => {36- await assertProcessError(t, type, execaMethod, transform => execaMethod('noop.js', {37- stdout: [38- generatorsMap[type].noop(false),39- transform,40- generatorsMap[type].noop(false),41- ],42- }));43-};44-45-test('Generators errors make subprocess fail even when other output generators do not throw', testSingleErrorOutput, 'generator', execa);46-test('Generators errors make subprocess fail even when other output generators do not throw, sync', testSingleErrorOutput, 'generator', execaSync);47-test('Duplexes errors make subprocess fail even when other output generators do not throw', testSingleErrorOutput, 'duplex', execa);48-test('WebTransform errors make subprocess fail even when other output generators do not throw', testSingleErrorOutput, 'webTransform', execa);49-50-const testSingleErrorInput = async (t, type, execaMethod) => {51- await assertProcessError(t, type, execaMethod, transform => execaMethod('stdin.js', {52- stdin: [53- ['foobar\n'],54- generatorsMap[type].noop(false),55- transform,56- generatorsMap[type].noop(false),57- ],58- }));59-};60-61-test('Generators errors make subprocess fail even when other input generators do not throw', testSingleErrorInput, 'generator', execa);62-test('Generators errors make subprocess fail even when other input generators do not throw, sync', testSingleErrorInput, 'generator', execaSync);63-test('Duplexes errors make subprocess fail even when other input generators do not throw', testSingleErrorInput, 'duplex', execa);64-test('WebTransform errors make subprocess fail even when other input generators do not throw', testSingleErrorInput, 'webTransform', execa);65-66-const testGeneratorCancel = async (t, error) => {67- const subprocess = execa('noop.js', {stdout: infiniteGenerator()});68- await once(subprocess.stdout, 'data');69- subprocess.stdout.destroy(error);70- await (error === undefined ? t.notThrowsAsync(subprocess) : t.throwsAsync(subprocess));71-};72-73-test('Running generators are canceled on subprocess abort', testGeneratorCancel, undefined);74-test('Running generators are canceled on subprocess error', testGeneratorCancel, new Error('test'));75-76-const testGeneratorDestroy = async (t, transform) => {77- const subprocess = execa('forever.js', {stdout: transform});78- const cause = new Error('test');79- subprocess.stdout.destroy(cause);80- subprocess.kill();81- t.like(await t.throwsAsync(subprocess), {cause});82-};83-84-test('Generators are destroyed on subprocess error, sync', testGeneratorDestroy, noopGenerator(false));85-test('Generators are destroyed on subprocess error, async', testGeneratorDestroy, infiniteGenerator());86-87-test('Generators are destroyed on early subprocess exit', async t => {88- await t.throwsAsync(execa('noop.js', {stdout: infiniteGenerator(), uid: -1}));89-});deleted:test/stdio/transform-final.js-35 removed
1-import test from 'ava';2-import {execa, execaSync} from '../../index.js';3-import {foobarString} from '../helpers/input.js';4-import {getOutputAsyncGenerator, getOutputGenerator, convertTransformToFinal} from '../helpers/generator.js';5-import {setFixtureDir} from '../helpers/fixtures-dir.js';6-7-setFixtureDir();8-9-const testGeneratorFinal = async (t, fixtureName, execaMethod) => {10- const {stdout} = await execaMethod(fixtureName, {stdout: convertTransformToFinal(getOutputGenerator(foobarString)(), true)});11- t.is(stdout, foobarString);12-};13-14-test('Generators "final" can be used', testGeneratorFinal, 'noop.js', execa);15-test('Generators "final" is used even on empty streams', testGeneratorFinal, 'empty.js', execa);16-test('Generators "final" can be used, sync', testGeneratorFinal, 'noop.js', execaSync);17-test('Generators "final" is used even on empty streams, sync', testGeneratorFinal, 'empty.js', execaSync);18-19-const testFinalAlone = async (t, final, execaMethod) => {20- const {stdout} = await execaMethod('noop-fd.js', ['1', '.'], {stdout: {final: final(foobarString)().transform, binary: true}});21- t.is(stdout, `.${foobarString}`);22-};23-24-test('Generators "final" can be used without "transform"', testFinalAlone, getOutputGenerator, execa);25-test('Generators "final" can be used without "transform", sync', testFinalAlone, getOutputGenerator, execaSync);26-test('Generators "final" can be used without "transform", async', testFinalAlone, getOutputAsyncGenerator, execa);27-28-const testFinalNoOutput = async (t, final, execaMethod) => {29- const {stdout} = await execaMethod('empty.js', {stdout: {final: final(foobarString)().transform}});30- t.is(stdout, foobarString);31-};32-33-test('Generators "final" can be used without "transform" nor output', testFinalNoOutput, getOutputGenerator, execa);34-test('Generators "final" can be used without "transform" nor output, sync', testFinalNoOutput, getOutputGenerator, execaSync);35-test('Generators "final" can be used without "transform" nor output, async', testFinalNoOutput, getOutputAsyncGenerator, execa);deleted:test/stdio/transform-input.js-158 removed
1-import {Buffer} from 'node:buffer';2-import test from 'ava';3-import {execa, execaSync} from '../../index.js';4-import {setFixtureDir} from '../helpers/fixtures-dir.js';5-import {getStdio} from '../helpers/stdio.js';6-import {7- foobarString,8- foobarUppercase,9- foobarHex,10- foobarUint8Array,11- foobarBuffer,12- foobarObject,13- foobarObjectString,14-} from '../helpers/input.js';15-import {generatorsMap} from '../helpers/map.js';16-17-setFixtureDir();18-19-const getInputObjectMode = (objectMode, addNoopTransform, type) => objectMode20- ? {21- input: [foobarObject],22- generators: generatorsMap[type].addNoop(generatorsMap[type].serialize(objectMode), addNoopTransform, objectMode),23- output: foobarObjectString,24- }25- : {26- input: foobarUint8Array,27- generators: generatorsMap[type].addNoop(generatorsMap[type].uppercase(objectMode), addNoopTransform, objectMode),28- output: foobarUppercase,29- };30-31-// eslint-disable-next-line max-params32-const testGeneratorInput = async (t, fdNumber, objectMode, addNoopTransform, type, execaMethod) => {33- const {input, generators, output} = getInputObjectMode(objectMode, addNoopTransform, type);34- const {stdout} = await execaMethod('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, [input, ...generators]));35- t.is(stdout, output);36-};37-38-test('Can use generators with result.stdin', testGeneratorInput, 0, false, false, 'generator', execa);39-test('Can use generators with result.stdio[*] as input', testGeneratorInput, 3, false, false, 'generator', execa);40-test('Can use generators with result.stdin, objectMode', testGeneratorInput, 0, true, false, 'generator', execa);41-test('Can use generators with result.stdio[*] as input, objectMode', testGeneratorInput, 3, true, false, 'generator', execa);42-test('Can use generators with result.stdin, noop transform', testGeneratorInput, 0, false, true, 'generator', execa);43-test('Can use generators with result.stdio[*] as input, noop transform', testGeneratorInput, 3, false, true, 'generator', execa);44-test('Can use generators with result.stdin, objectMode, noop transform', testGeneratorInput, 0, true, true, 'generator', execa);45-test('Can use generators with result.stdio[*] as input, objectMode, noop transform', testGeneratorInput, 3, true, true, 'generator', execa);46-test('Can use generators with result.stdin, sync', testGeneratorInput, 0, false, false, 'generator', execaSync);47-test('Can use generators with result.stdin, objectMode, sync', testGeneratorInput, 0, true, false, 'generator', execaSync);48-test('Can use generators with result.stdin, noop transform, sync', testGeneratorInput, 0, false, true, 'generator', execaSync);49-test('Can use generators with result.stdin, objectMode, noop transform, sync', testGeneratorInput, 0, true, true, 'generator', execaSync);50-test('Can use duplexes with result.stdin', testGeneratorInput, 0, false, false, 'duplex', execa);51-test('Can use duplexes with result.stdio[*] as input', testGeneratorInput, 3, false, false, 'duplex', execa);52-test('Can use duplexes with result.stdin, objectMode', testGeneratorInput, 0, true, false, 'duplex', execa);53-test('Can use duplexes with result.stdio[*] as input, objectMode', testGeneratorInput, 3, true, false, 'duplex', execa);54-test('Can use duplexes with result.stdin, noop transform', testGeneratorInput, 0, false, true, 'duplex', execa);55-test('Can use duplexes with result.stdio[*] as input, noop transform', testGeneratorInput, 3, false, true, 'duplex', execa);56-test('Can use duplexes with result.stdin, objectMode, noop transform', testGeneratorInput, 0, true, true, 'duplex', execa);57-test('Can use duplexes with result.stdio[*] as input, objectMode, noop transform', testGeneratorInput, 3, true, true, 'duplex', execa);58-test('Can use webTransforms with result.stdin', testGeneratorInput, 0, false, false, 'webTransform', execa);59-test('Can use webTransforms with result.stdio[*] as input', testGeneratorInput, 3, false, false, 'webTransform', execa);60-test('Can use webTransforms with result.stdin, objectMode', testGeneratorInput, 0, true, false, 'webTransform', execa);61-test('Can use webTransforms with result.stdio[*] as input, objectMode', testGeneratorInput, 3, true, false, 'webTransform', execa);62-test('Can use webTransforms with result.stdin, noop transform', testGeneratorInput, 0, false, true, 'webTransform', execa);63-test('Can use webTransforms with result.stdio[*] as input, noop transform', testGeneratorInput, 3, false, true, 'webTransform', execa);64-test('Can use webTransforms with result.stdin, objectMode, noop transform', testGeneratorInput, 0, true, true, 'webTransform', execa);65-test('Can use webTransforms with result.stdio[*] as input, objectMode, noop transform', testGeneratorInput, 3, true, true, 'webTransform', execa);66-67-// eslint-disable-next-line max-params68-const testGeneratorInputPipe = async (t, useShortcutProperty, objectMode, addNoopTransform, type, input) => {69- const {generators, output} = getInputObjectMode(objectMode, addNoopTransform, type);70- const subprocess = execa('stdin-fd.js', ['0'], getStdio(0, generators));71- const stream = useShortcutProperty ? subprocess.stdin : subprocess.stdio[0];72- stream.end(...input);73- const {stdout} = await subprocess;74- const expectedOutput = input[1] === 'utf16le' ? Buffer.from(output, input[1]).toString() : output;75- t.is(stdout, expectedOutput);76-};77-78-test('Can use generators with subprocess.stdio[0] and default encoding', testGeneratorInputPipe, false, false, false, 'generator', [foobarString, 'utf8']);79-test('Can use generators with subprocess.stdin and default encoding', testGeneratorInputPipe, true, false, false, 'generator', [foobarString, 'utf8']);80-test('Can use generators with subprocess.stdio[0] and encoding "utf16le"', testGeneratorInputPipe, false, false, false, 'generator', [foobarString, 'utf16le']);81-test('Can use generators with subprocess.stdin and encoding "utf16le"', testGeneratorInputPipe, true, false, false, 'generator', [foobarString, 'utf16le']);82-test('Can use generators with subprocess.stdio[0] and encoding "buffer"', testGeneratorInputPipe, false, false, false, 'generator', [foobarBuffer, 'buffer']);83-test('Can use generators with subprocess.stdin and encoding "buffer"', testGeneratorInputPipe, true, false, false, 'generator', [foobarBuffer, 'buffer']);84-test('Can use generators with subprocess.stdio[0] and encoding "hex"', testGeneratorInputPipe, false, false, false, 'generator', [foobarHex, 'hex']);85-test('Can use generators with subprocess.stdin and encoding "hex"', testGeneratorInputPipe, true, false, false, 'generator', [foobarHex, 'hex']);86-test('Can use generators with subprocess.stdio[0], objectMode', testGeneratorInputPipe, false, true, false, 'generator', [foobarObject]);87-test('Can use generators with subprocess.stdin, objectMode', testGeneratorInputPipe, true, true, false, 'generator', [foobarObject]);88-test('Can use generators with subprocess.stdio[0] and default encoding, noop transform', testGeneratorInputPipe, false, false, true, 'generator', [foobarString, 'utf8']);89-test('Can use generators with subprocess.stdin and default encoding, noop transform', testGeneratorInputPipe, true, false, true, 'generator', [foobarString, 'utf8']);90-test('Can use generators with subprocess.stdio[0] and encoding "utf16le", noop transform', testGeneratorInputPipe, false, false, true, 'generator', [foobarString, 'utf16le']);91-test('Can use generators with subprocess.stdin and encoding "utf16le", noop transform', testGeneratorInputPipe, true, false, true, 'generator', [foobarString, 'utf16le']);92-test('Can use generators with subprocess.stdio[0] and encoding "buffer", noop transform', testGeneratorInputPipe, false, false, true, 'generator', [foobarBuffer, 'buffer']);93-test('Can use generators with subprocess.stdin and encoding "buffer", noop transform', testGeneratorInputPipe, true, false, true, 'generator', [foobarBuffer, 'buffer']);94-test('Can use generators with subprocess.stdio[0] and encoding "hex", noop transform', testGeneratorInputPipe, false, false, true, 'generator', [foobarHex, 'hex']);95-test('Can use generators with subprocess.stdin and encoding "hex", noop transform', testGeneratorInputPipe, true, false, true, 'generator', [foobarHex, 'hex']);96-test('Can use generators with subprocess.stdio[0], objectMode, noop transform', testGeneratorInputPipe, false, true, true, 'generator', [foobarObject]);97-test('Can use generators with subprocess.stdin, objectMode, noop transform', testGeneratorInputPipe, true, true, true, 'generator', [foobarObject]);98-test('Can use duplexes with subprocess.stdio[0] and default encoding', testGeneratorInputPipe, false, false, false, 'duplex', [foobarString, 'utf8']);99-test('Can use duplexes with subprocess.stdin and default encoding', testGeneratorInputPipe, true, false, false, 'duplex', [foobarString, 'utf8']);100-test('Can use duplexes with subprocess.stdio[0] and encoding "utf16le"', testGeneratorInputPipe, false, false, false, 'duplex', [foobarString, 'utf16le']);101-test('Can use duplexes with subprocess.stdin and encoding "utf16le"', testGeneratorInputPipe, true, false, false, 'duplex', [foobarString, 'utf16le']);102-test('Can use duplexes with subprocess.stdio[0] and encoding "buffer"', testGeneratorInputPipe, false, false, false, 'duplex', [foobarBuffer, 'buffer']);103-test('Can use duplexes with subprocess.stdin and encoding "buffer"', testGeneratorInputPipe, true, false, false, 'duplex', [foobarBuffer, 'buffer']);104-test('Can use duplexes with subprocess.stdio[0] and encoding "hex"', testGeneratorInputPipe, false, false, false, 'duplex', [foobarHex, 'hex']);105-test('Can use duplexes with subprocess.stdin and encoding "hex"', testGeneratorInputPipe, true, false, false, 'duplex', [foobarHex, 'hex']);106-test('Can use duplexes with subprocess.stdio[0], objectMode', testGeneratorInputPipe, false, true, false, 'duplex', [foobarObject]);107-test('Can use duplexes with subprocess.stdin, objectMode', testGeneratorInputPipe, true, true, false, 'duplex', [foobarObject]);108-test('Can use duplexes with subprocess.stdio[0] and default encoding, noop transform', testGeneratorInputPipe, false, false, true, 'duplex', [foobarString, 'utf8']);109-test('Can use duplexes with subprocess.stdin and default encoding, noop transform', testGeneratorInputPipe, true, false, true, 'duplex', [foobarString, 'utf8']);110-test('Can use duplexes with subprocess.stdio[0] and encoding "utf16le", noop transform', testGeneratorInputPipe, false, false, true, 'duplex', [foobarString, 'utf16le']);111-test('Can use duplexes with subprocess.stdin and encoding "utf16le", noop transform', testGeneratorInputPipe, true, false, true, 'duplex', [foobarString, 'utf16le']);112-test('Can use duplexes with subprocess.stdio[0] and encoding "buffer", noop transform', testGeneratorInputPipe, false, false, true, 'duplex', [foobarBuffer, 'buffer']);113-test('Can use duplexes with subprocess.stdin and encoding "buffer", noop transform', testGeneratorInputPipe, true, false, true, 'duplex', [foobarBuffer, 'buffer']);114-test('Can use duplexes with subprocess.stdio[0] and encoding "hex", noop transform', testGeneratorInputPipe, false, false, true, 'duplex', [foobarHex, 'hex']);115-test('Can use duplexes with subprocess.stdin and encoding "hex", noop transform', testGeneratorInputPipe, true, false, true, 'duplex', [foobarHex, 'hex']);116-test('Can use duplexes with subprocess.stdio[0], objectMode, noop transform', testGeneratorInputPipe, false, true, true, 'duplex', [foobarObject]);117-test('Can use duplexes with subprocess.stdin, objectMode, noop transform', testGeneratorInputPipe, true, true, true, 'duplex', [foobarObject]);118-test('Can use webTransforms with subprocess.stdio[0] and default encoding', testGeneratorInputPipe, false, false, false, 'webTransform', [foobarString, 'utf8']);119-test('Can use webTransforms with subprocess.stdin and default encoding', testGeneratorInputPipe, true, false, false, 'webTransform', [foobarString, 'utf8']);120-test('Can use webTransforms with subprocess.stdio[0] and encoding "utf16le"', testGeneratorInputPipe, false, false, false, 'webTransform', [foobarString, 'utf16le']);121-test('Can use webTransforms with subprocess.stdin and encoding "utf16le"', testGeneratorInputPipe, true, false, false, 'webTransform', [foobarString, 'utf16le']);122-test('Can use webTransforms with subprocess.stdio[0] and encoding "buffer"', testGeneratorInputPipe, false, false, false, 'webTransform', [foobarBuffer, 'buffer']);123-test('Can use webTransforms with subprocess.stdin and encoding "buffer"', testGeneratorInputPipe, true, false, false, 'webTransform', [foobarBuffer, 'buffer']);124-test('Can use webTransforms with subprocess.stdio[0] and encoding "hex"', testGeneratorInputPipe, false, false, false, 'webTransform', [foobarHex, 'hex']);125-test('Can use webTransforms with subprocess.stdin and encoding "hex"', testGeneratorInputPipe, true, false, false, 'webTransform', [foobarHex, 'hex']);126-test('Can use webTransforms with subprocess.stdio[0], objectMode', testGeneratorInputPipe, false, true, false, 'webTransform', [foobarObject]);127-test('Can use webTransforms with subprocess.stdin, objectMode', testGeneratorInputPipe, true, true, false, 'webTransform', [foobarObject]);128-test('Can use webTransforms with subprocess.stdio[0] and default encoding, noop transform', testGeneratorInputPipe, false, false, true, 'webTransform', [foobarString, 'utf8']);129-test('Can use webTransforms with subprocess.stdin and default encoding, noop transform', testGeneratorInputPipe, true, false, true, 'webTransform', [foobarString, 'utf8']);130-test('Can use webTransforms with subprocess.stdio[0] and encoding "utf16le", noop transform', testGeneratorInputPipe, false, false, true, 'webTransform', [foobarString, 'utf16le']);131-test('Can use webTransforms with subprocess.stdin and encoding "utf16le", noop transform', testGeneratorInputPipe, true, false, true, 'webTransform', [foobarString, 'utf16le']);132-test('Can use webTransforms with subprocess.stdio[0] and encoding "buffer", noop transform', testGeneratorInputPipe, false, false, true, 'webTransform', [foobarBuffer, 'buffer']);133-test('Can use webTransforms with subprocess.stdin and encoding "buffer", noop transform', testGeneratorInputPipe, true, false, true, 'webTransform', [foobarBuffer, 'buffer']);134-test('Can use webTransforms with subprocess.stdio[0] and encoding "hex", noop transform', testGeneratorInputPipe, false, false, true, 'webTransform', [foobarHex, 'hex']);135-test('Can use webTransforms with subprocess.stdin and encoding "hex", noop transform', testGeneratorInputPipe, true, false, true, 'webTransform', [foobarHex, 'hex']);136-test('Can use webTransforms with subprocess.stdio[0], objectMode, noop transform', testGeneratorInputPipe, false, true, true, 'webTransform', [foobarObject]);137-test('Can use webTransforms with subprocess.stdin, objectMode, noop transform', testGeneratorInputPipe, true, true, true, 'webTransform', [foobarObject]);138-139-const testGeneratorStdioInputPipe = async (t, objectMode, addNoopTransform, type) => {140- const {input, generators, output} = getInputObjectMode(objectMode, addNoopTransform, type);141- const subprocess = execa('stdin-fd.js', ['3'], getStdio(3, [[], ...generators]));142- subprocess.stdio[3].write(Array.isArray(input) ? input[0] : input);143- const {stdout} = await subprocess;144- t.is(stdout, output);145-};146-147-test('Can use generators with subprocess.stdio[*] as input', testGeneratorStdioInputPipe, false, false, 'generator');148-test('Can use generators with subprocess.stdio[*] as input, objectMode', testGeneratorStdioInputPipe, true, false, 'generator');149-test('Can use generators with subprocess.stdio[*] as input, noop transform', testGeneratorStdioInputPipe, false, true, 'generator');150-test('Can use generators with subprocess.stdio[*] as input, objectMode, noop transform', testGeneratorStdioInputPipe, true, true, 'generator');151-test('Can use duplexes with subprocess.stdio[*] as input', testGeneratorStdioInputPipe, false, false, 'duplex');152-test('Can use duplexes with subprocess.stdio[*] as input, objectMode', testGeneratorStdioInputPipe, true, false, 'duplex');153-test('Can use duplexes with subprocess.stdio[*] as input, noop transform', testGeneratorStdioInputPipe, false, true, 'duplex');154-test('Can use duplexes with subprocess.stdio[*] as input, objectMode, noop transform', testGeneratorStdioInputPipe, true, true, 'duplex');155-test('Can use webTransforms with subprocess.stdio[*] as input', testGeneratorStdioInputPipe, false, false, 'webTransform');156-test('Can use webTransforms with subprocess.stdio[*] as input, objectMode', testGeneratorStdioInputPipe, true, false, 'webTransform');157-test('Can use webTransforms with subprocess.stdio[*] as input, noop transform', testGeneratorStdioInputPipe, false, true, 'webTransform');158-test('Can use webTransforms with subprocess.stdio[*] as input, objectMode, noop transform', testGeneratorStdioInputPipe, true, true, 'webTransform');deleted:test/stdio/transform-mixed.js-104 removed
1-import {readFile, writeFile, rm} from 'node:fs/promises';2-import {PassThrough} from 'node:stream';3-import test from 'ava';4-import getStream from 'get-stream';5-import tempfile from 'tempfile';6-import {execa, execaSync} from '../../index.js';7-import {setFixtureDir} from '../helpers/fixtures-dir.js';8-import {foobarString, foobarUppercase, foobarUint8Array} from '../helpers/input.js';9-import {uppercaseGenerator} from '../helpers/generator.js';10-import {uppercaseBufferDuplex} from '../helpers/duplex.js';11-import {uppercaseBufferWebTransform} from '../helpers/web-transform.js';12-import {generatorsMap} from '../helpers/map.js';13-14-setFixtureDir();15-16-const testInputOption = async (t, type, execaMethod) => {17- const {stdout} = await execaMethod('stdin-fd.js', ['0'], {stdin: generatorsMap[type].uppercase(), input: foobarUint8Array});18- t.is(stdout, foobarUppercase);19-};20-21-test('Can use generators with input option', testInputOption, 'generator', execa);22-test('Can use generators with input option, sync', testInputOption, 'generator', execaSync);23-test('Can use duplexes with input option', testInputOption, 'duplex', execa);24-test('Can use webTransforms with input option', testInputOption, 'webTransform', execa);25-26-// eslint-disable-next-line max-params27-const testInputFile = async (t, stdinOption, useInputFile, reversed, execaMethod) => {28- const filePath = tempfile();29- await writeFile(filePath, foobarString);30- const options = useInputFile31- ? {inputFile: filePath, stdin: stdinOption}32- : {stdin: [{file: filePath}, stdinOption]};33- options.stdin = reversed ? options.stdin.reverse() : options.stdin;34- const {stdout} = await execaMethod('stdin-fd.js', ['0'], options);35- t.is(stdout, foobarUppercase);36- await rm(filePath);37-};38-39-test('Can use generators with a file as input', testInputFile, uppercaseGenerator(), false, false, execa);40-test('Can use generators with a file as input, reversed', testInputFile, uppercaseGenerator(), false, true, execa);41-test('Can use generators with inputFile option', testInputFile, uppercaseGenerator(), true, false, execa);42-test('Can use generators with a file as input, sync', testInputFile, uppercaseGenerator(), false, false, execaSync);43-test('Can use generators with a file as input, reversed, sync', testInputFile, uppercaseGenerator(), false, true, execaSync);44-test('Can use generators with inputFile option, sync', testInputFile, uppercaseGenerator(), true, false, execaSync);45-test('Can use duplexes with a file as input', testInputFile, uppercaseBufferDuplex(), false, false, execa);46-test('Can use duplexes with a file as input, reversed', testInputFile, uppercaseBufferDuplex(), false, true, execa);47-test('Can use duplexes with inputFile option', testInputFile, uppercaseBufferDuplex(), true, false, execa);48-test('Can use webTransforms with a file as input', testInputFile, uppercaseBufferWebTransform(), false, false, execa);49-test('Can use webTransforms with a file as input, reversed', testInputFile, uppercaseBufferWebTransform(), false, true, execa);50-test('Can use webTransforms with inputFile option', testInputFile, uppercaseBufferWebTransform(), true, false, execa);51-52-const testOutputFile = async (t, reversed, type, execaMethod) => {53- const filePath = tempfile();54- const stdoutOption = [generatorsMap[type].uppercaseBuffer(false, true), {file: filePath}];55- const reversedStdoutOption = reversed ? stdoutOption.reverse() : stdoutOption;56- const {stdout} = await execaMethod('noop-fd.js', ['1'], {stdout: reversedStdoutOption});57- t.is(stdout, foobarUppercase);58- t.is(await readFile(filePath, 'utf8'), foobarUppercase);59- await rm(filePath);60-};61-62-test('Can use generators with a file as output', testOutputFile, false, 'generator', execa);63-test('Can use generators with a file as output, reversed', testOutputFile, true, 'generator', execa);64-test('Can use generators with a file as output, sync', testOutputFile, false, 'generator', execaSync);65-test('Can use generators with a file as output, reversed, sync', testOutputFile, true, 'generator', execaSync);66-test('Can use duplexes with a file as output', testOutputFile, false, 'duplex', execa);67-test('Can use duplexes with a file as output, reversed', testOutputFile, true, 'duplex', execa);68-test('Can use webTransforms with a file as output', testOutputFile, false, 'webTransform', execa);69-test('Can use webTransforms with a file as output, reversed', testOutputFile, true, 'webTransform', execa);70-71-const testWritableDestination = async (t, type) => {72- const passThrough = new PassThrough();73- const [{stdout}, streamOutput] = await Promise.all([74- execa('noop-fd.js', ['1', foobarString], {stdout: [generatorsMap[type].uppercaseBuffer(false, true), passThrough]}),75- getStream(passThrough),76- ]);77- t.is(stdout, foobarUppercase);78- t.is(streamOutput, foobarUppercase);79-};80-81-test('Can use generators to a Writable stream', testWritableDestination, 'generator');82-test('Can use duplexes to a Writable stream', testWritableDestination, 'duplex');83-test('Can use webTransforms to a Writable stream', testWritableDestination, 'webTransform');84-85-const testReadableSource = async (t, type) => {86- const passThrough = new PassThrough();87- const subprocess = execa('stdin-fd.js', ['0'], {stdin: [passThrough, generatorsMap[type].uppercase()]});88- passThrough.end(foobarString);89- const {stdout} = await subprocess;90- t.is(stdout, foobarUppercase);91-};92-93-test('Can use generators from a Readable stream', testReadableSource, 'generator');94-test('Can use duplexes from a Readable stream', testReadableSource, 'duplex');95-test('Can use webTransforms from a Readable stream', testReadableSource, 'webTransform');96-97-const testInherit = async (t, type) => {98- const {stdout} = await execa('nested-inherit.js', [type]);99- t.is(stdout, foobarUppercase);100-};101-102-test('Can use generators with "inherit"', testInherit, 'generator');103-test('Can use duplexes with "inherit"', testInherit, 'duplex');104-test('Can use webTransforms with "inherit"', testInherit, 'webTransform');deleted:test/stdio/transform-output.js-261 removed
1-import test from 'ava';2-import getStream, {getStreamAsArray} from 'get-stream';3-import {execa, execaSync} from '../../index.js';4-import {setFixtureDir} from '../helpers/fixtures-dir.js';5-import {getStdio} from '../helpers/stdio.js';6-import {foobarString, foobarUppercase, foobarObject} from '../helpers/input.js';7-import {generatorsMap} from '../helpers/map.js';8-9-setFixtureDir();10-11-const getOutputObjectMode = (objectMode, addNoopTransform, type, binary) => objectMode12- ? {13- generators: generatorsMap[type].addNoop(generatorsMap[type].outputObject(), addNoopTransform, objectMode, binary),14- output: [foobarObject],15- getStreamMethod: getStreamAsArray,16- }17- : {18- generators: generatorsMap[type].addNoop(generatorsMap[type].uppercaseBuffer(objectMode, true), addNoopTransform, objectMode, binary),19- output: foobarUppercase,20- getStreamMethod: getStream,21- };22-23-// eslint-disable-next-line max-params24-const testGeneratorOutput = async (t, fdNumber, reject, useShortcutProperty, objectMode, addNoopTransform, type, execaMethod) => {25- const {generators, output} = getOutputObjectMode(objectMode, addNoopTransform, type);26- const fixtureName = reject ? 'noop-fd.js' : 'noop-fail.js';27- const {stdout, stderr, stdio} = await execaMethod(fixtureName, [`${fdNumber}`, foobarString], {...getStdio(fdNumber, generators), reject});28- const result = useShortcutProperty ? [stdout, stderr][fdNumber - 1] : stdio[fdNumber];29- t.deepEqual(result, output);30-};31-32-test('Can use generators with result.stdio[1]', testGeneratorOutput, 1, true, false, false, false, 'generator', execa);33-test('Can use generators with result.stdout', testGeneratorOutput, 1, true, true, false, false, 'generator', execa);34-test('Can use generators with result.stdio[2]', testGeneratorOutput, 2, true, false, false, false, 'generator', execa);35-test('Can use generators with result.stderr', testGeneratorOutput, 2, true, true, false, false, 'generator', execa);36-test('Can use generators with result.stdio[*] as output', testGeneratorOutput, 3, true, false, false, false, 'generator', execa);37-test('Can use generators with error.stdio[1]', testGeneratorOutput, 1, false, false, false, false, 'generator', execa);38-test('Can use generators with error.stdout', testGeneratorOutput, 1, false, true, false, false, 'generator', execa);39-test('Can use generators with error.stdio[2]', testGeneratorOutput, 2, false, false, false, false, 'generator', execa);40-test('Can use generators with error.stderr', testGeneratorOutput, 2, false, true, false, false, 'generator', execa);41-test('Can use generators with error.stdio[*] as output', testGeneratorOutput, 3, false, false, false, false, 'generator', execa);42-test('Can use generators with result.stdio[1], objectMode', testGeneratorOutput, 1, true, false, true, false, 'generator', execa);43-test('Can use generators with result.stdout, objectMode', testGeneratorOutput, 1, true, true, true, false, 'generator', execa);44-test('Can use generators with result.stdio[2], objectMode', testGeneratorOutput, 2, true, false, true, false, 'generator', execa);45-test('Can use generators with result.stderr, objectMode', testGeneratorOutput, 2, true, true, true, false, 'generator', execa);46-test('Can use generators with result.stdio[*] as output, objectMode', testGeneratorOutput, 3, true, false, true, false, 'generator', execa);47-test('Can use generators with error.stdio[1], objectMode', testGeneratorOutput, 1, false, false, true, false, 'generator', execa);48-test('Can use generators with error.stdout, objectMode', testGeneratorOutput, 1, false, true, true, false, 'generator', execa);49-test('Can use generators with error.stdio[2], objectMode', testGeneratorOutput, 2, false, false, true, false, 'generator', execa);50-test('Can use generators with error.stderr, objectMode', testGeneratorOutput, 2, false, true, true, false, 'generator', execa);51-test('Can use generators with error.stdio[*] as output, objectMode', testGeneratorOutput, 3, false, false, true, false, 'generator', execa);52-test('Can use generators with result.stdio[1], noop transform', testGeneratorOutput, 1, true, false, false, true, 'generator', execa);53-test('Can use generators with result.stdout, noop transform', testGeneratorOutput, 1, true, true, false, true, 'generator', execa);54-test('Can use generators with result.stdio[2], noop transform', testGeneratorOutput, 2, true, false, false, true, 'generator', execa);55-test('Can use generators with result.stderr, noop transform', testGeneratorOutput, 2, true, true, false, true, 'generator', execa);56-test('Can use generators with result.stdio[*] as output, noop transform', testGeneratorOutput, 3, true, false, false, true, 'generator', execa);57-test('Can use generators with error.stdio[1], noop transform', testGeneratorOutput, 1, false, false, false, true, 'generator', execa);58-test('Can use generators with error.stdout, noop transform', testGeneratorOutput, 1, false, true, false, true, 'generator', execa);59-test('Can use generators with error.stdio[2], noop transform', testGeneratorOutput, 2, false, false, false, true, 'generator', execa);60-test('Can use generators with error.stderr, noop transform', testGeneratorOutput, 2, false, true, false, true, 'generator', execa);61-test('Can use generators with error.stdio[*] as output, noop transform', testGeneratorOutput, 3, false, false, false, true, 'generator', execa);62-test('Can use generators with result.stdio[1], objectMode, noop transform', testGeneratorOutput, 1, true, false, true, true, 'generator', execa);63-test('Can use generators with result.stdout, objectMode, noop transform', testGeneratorOutput, 1, true, true, true, true, 'generator', execa);64-test('Can use generators with result.stdio[2], objectMode, noop transform', testGeneratorOutput, 2, true, false, true, true, 'generator', execa);65-test('Can use generators with result.stderr, objectMode, noop transform', testGeneratorOutput, 2, true, true, true, true, 'generator', execa);66-test('Can use generators with result.stdio[*] as output, objectMode, noop transform', testGeneratorOutput, 3, true, false, true, true, 'generator', execa);67-test('Can use generators with error.stdio[1], objectMode, noop transform', testGeneratorOutput, 1, false, false, true, true, 'generator', execa);68-test('Can use generators with error.stdout, objectMode, noop transform', testGeneratorOutput, 1, false, true, true, true, 'generator', execa);69-test('Can use generators with error.stdio[2], objectMode, noop transform', testGeneratorOutput, 2, false, false, true, true, 'generator', execa);70-test('Can use generators with error.stderr, objectMode, noop transform', testGeneratorOutput, 2, false, true, true, true, 'generator', execa);71-test('Can use generators with error.stdio[*] as output, objectMode, noop transform', testGeneratorOutput, 3, false, false, true, true, 'generator', execa);72-test('Can use generators with result.stdio[1], sync', testGeneratorOutput, 1, true, false, false, false, 'generator', execaSync);73-test('Can use generators with result.stdout, sync', testGeneratorOutput, 1, true, true, false, false, 'generator', execaSync);74-test('Can use generators with result.stdio[2], sync', testGeneratorOutput, 2, true, false, false, false, 'generator', execaSync);75-test('Can use generators with result.stderr, sync', testGeneratorOutput, 2, true, true, false, false, 'generator', execaSync);76-test('Can use generators with result.stdio[*] as output, sync', testGeneratorOutput, 3, true, false, false, false, 'generator', execaSync);77-test('Can use generators with error.stdio[1], sync', testGeneratorOutput, 1, false, false, false, false, 'generator', execaSync);78-test('Can use generators with error.stdout, sync', testGeneratorOutput, 1, false, true, false, false, 'generator', execaSync);79-test('Can use generators with error.stdio[2], sync', testGeneratorOutput, 2, false, false, false, false, 'generator', execaSync);80-test('Can use generators with error.stderr, sync', testGeneratorOutput, 2, false, true, false, false, 'generator', execaSync);81-test('Can use generators with error.stdio[*] as output, sync', testGeneratorOutput, 3, false, false, false, false, 'generator', execaSync);82-test('Can use generators with result.stdio[1], objectMode, sync', testGeneratorOutput, 1, true, false, true, false, 'generator', execaSync);83-test('Can use generators with result.stdout, objectMode, sync', testGeneratorOutput, 1, true, true, true, false, 'generator', execaSync);84-test('Can use generators with result.stdio[2], objectMode, sync', testGeneratorOutput, 2, true, false, true, false, 'generator', execaSync);85-test('Can use generators with result.stderr, objectMode, sync', testGeneratorOutput, 2, true, true, true, false, 'generator', execaSync);86-test('Can use generators with result.stdio[*] as output, objectMode, sync', testGeneratorOutput, 3, true, false, true, false, 'generator', execaSync);87-test('Can use generators with error.stdio[1], objectMode, sync', testGeneratorOutput, 1, false, false, true, false, 'generator', execaSync);88-test('Can use generators with error.stdout, objectMode, sync', testGeneratorOutput, 1, false, true, true, false, 'generator', execaSync);89-test('Can use generators with error.stdio[2], objectMode, sync', testGeneratorOutput, 2, false, false, true, false, 'generator', execaSync);90-test('Can use generators with error.stderr, objectMode, sync', testGeneratorOutput, 2, false, true, true, false, 'generator', execaSync);91-test('Can use generators with error.stdio[*] as output, objectMode, sync', testGeneratorOutput, 3, false, false, true, false, 'generator', execaSync);92-test('Can use generators with result.stdio[1], noop transform, sync', testGeneratorOutput, 1, true, false, false, true, 'generator', execaSync);93-test('Can use generators with result.stdout, noop transform, sync', testGeneratorOutput, 1, true, true, false, true, 'generator', execaSync);94-test('Can use generators with result.stdio[2], noop transform, sync', testGeneratorOutput, 2, true, false, false, true, 'generator', execaSync);95-test('Can use generators with result.stderr, noop transform, sync', testGeneratorOutput, 2, true, true, false, true, 'generator', execaSync);96-test('Can use generators with result.stdio[*] as output, noop transform, sync', testGeneratorOutput, 3, true, false, false, true, 'generator', execaSync);97-test('Can use generators with error.stdio[1], noop transform, sync', testGeneratorOutput, 1, false, false, false, true, 'generator', execaSync);98-test('Can use generators with error.stdout, noop transform, sync', testGeneratorOutput, 1, false, true, false, true, 'generator', execaSync);99-test('Can use generators with error.stdio[2], noop transform, sync', testGeneratorOutput, 2, false, false, false, true, 'generator', execaSync);100-test('Can use generators with error.stderr, noop transform, sync', testGeneratorOutput, 2, false, true, false, true, 'generator', execaSync);101-test('Can use generators with error.stdio[*] as output, noop transform, sync', testGeneratorOutput, 3, false, false, false, true, 'generator', execaSync);102-test('Can use generators with result.stdio[1], objectMode, noop transform, sync', testGeneratorOutput, 1, true, false, true, true, 'generator', execaSync);103-test('Can use generators with result.stdout, objectMode, noop transform, sync', testGeneratorOutput, 1, true, true, true, true, 'generator', execaSync);104-test('Can use generators with result.stdio[2], objectMode, noop transform, sync', testGeneratorOutput, 2, true, false, true, true, 'generator', execaSync);105-test('Can use generators with result.stderr, objectMode, noop transform, sync', testGeneratorOutput, 2, true, true, true, true, 'generator', execaSync);106-test('Can use generators with result.stdio[*] as output, objectMode, noop transform, sync', testGeneratorOutput, 3, true, false, true, true, 'generator', execaSync);107-test('Can use generators with error.stdio[1], objectMode, noop transform, sync', testGeneratorOutput, 1, false, false, true, true, 'generator', execaSync);108-test('Can use generators with error.stdout, objectMode, noop transform, sync', testGeneratorOutput, 1, false, true, true, true, 'generator', execaSync);109-test('Can use generators with error.stdio[2], objectMode, noop transform, sync', testGeneratorOutput, 2, false, false, true, true, 'generator', execaSync);110-test('Can use generators with error.stderr, objectMode, noop transform, sync', testGeneratorOutput, 2, false, true, true, true, 'generator', execaSync);111-test('Can use generators with error.stdio[*] as output, objectMode, noop transform, sync', testGeneratorOutput, 3, false, false, true, true, 'generator', execaSync);112-test('Can use duplexes with result.stdio[1]', testGeneratorOutput, 1, true, false, false, false, 'duplex', execa);113-test('Can use duplexes with result.stdout', testGeneratorOutput, 1, true, true, false, false, 'duplex', execa);114-test('Can use duplexes with result.stdio[2]', testGeneratorOutput, 2, true, false, false, false, 'duplex', execa);115-test('Can use duplexes with result.stderr', testGeneratorOutput, 2, true, true, false, false, 'duplex', execa);116-test('Can use duplexes with result.stdio[*] as output', testGeneratorOutput, 3, true, false, false, false, 'duplex', execa);117-test('Can use duplexes with error.stdio[1]', testGeneratorOutput, 1, false, false, false, false, 'duplex', execa);118-test('Can use duplexes with error.stdout', testGeneratorOutput, 1, false, true, false, false, 'duplex', execa);119-test('Can use duplexes with error.stdio[2]', testGeneratorOutput, 2, false, false, false, false, 'duplex', execa);120-test('Can use duplexes with error.stderr', testGeneratorOutput, 2, false, true, false, false, 'duplex', execa);121-test('Can use duplexes with error.stdio[*] as output', testGeneratorOutput, 3, false, false, false, false, 'duplex', execa);122-test('Can use duplexes with result.stdio[1], objectMode', testGeneratorOutput, 1, true, false, true, false, 'duplex', execa);123-test('Can use duplexes with result.stdout, objectMode', testGeneratorOutput, 1, true, true, true, false, 'duplex', execa);124-test('Can use duplexes with result.stdio[2], objectMode', testGeneratorOutput, 2, true, false, true, false, 'duplex', execa);125-test('Can use duplexes with result.stderr, objectMode', testGeneratorOutput, 2, true, true, true, false, 'duplex', execa);126-test('Can use duplexes with result.stdio[*] as output, objectMode', testGeneratorOutput, 3, true, false, true, false, 'duplex', execa);127-test('Can use duplexes with error.stdio[1], objectMode', testGeneratorOutput, 1, false, false, true, false, 'duplex', execa);128-test('Can use duplexes with error.stdout, objectMode', testGeneratorOutput, 1, false, true, true, false, 'duplex', execa);129-test('Can use duplexes with error.stdio[2], objectMode', testGeneratorOutput, 2, false, false, true, false, 'duplex', execa);130-test('Can use duplexes with error.stderr, objectMode', testGeneratorOutput, 2, false, true, true, false, 'duplex', execa);131-test('Can use duplexes with error.stdio[*] as output, objectMode', testGeneratorOutput, 3, false, false, true, false, 'duplex', execa);132-test('Can use duplexes with result.stdio[1], noop transform', testGeneratorOutput, 1, true, false, false, true, 'duplex', execa);133-test('Can use duplexes with result.stdout, noop transform', testGeneratorOutput, 1, true, true, false, true, 'duplex', execa);134-test('Can use duplexes with result.stdio[2], noop transform', testGeneratorOutput, 2, true, false, false, true, 'duplex', execa);135-test('Can use duplexes with result.stderr, noop transform', testGeneratorOutput, 2, true, true, false, true, 'duplex', execa);136-test('Can use duplexes with result.stdio[*] as output, noop transform', testGeneratorOutput, 3, true, false, false, true, 'duplex', execa);137-test('Can use duplexes with error.stdio[1], noop transform', testGeneratorOutput, 1, false, false, false, true, 'duplex', execa);138-test('Can use duplexes with error.stdout, noop transform', testGeneratorOutput, 1, false, true, false, true, 'duplex', execa);139-test('Can use duplexes with error.stdio[2], noop transform', testGeneratorOutput, 2, false, false, false, true, 'duplex', execa);140-test('Can use duplexes with error.stderr, noop transform', testGeneratorOutput, 2, false, true, false, true, 'duplex', execa);141-test('Can use duplexes with error.stdio[*] as output, noop transform', testGeneratorOutput, 3, false, false, false, true, 'duplex', execa);142-test('Can use duplexes with result.stdio[1], objectMode, noop transform', testGeneratorOutput, 1, true, false, true, true, 'duplex', execa);143-test('Can use duplexes with result.stdout, objectMode, noop transform', testGeneratorOutput, 1, true, true, true, true, 'duplex', execa);144-test('Can use duplexes with result.stdio[2], objectMode, noop transform', testGeneratorOutput, 2, true, false, true, true, 'duplex', execa);145-test('Can use duplexes with result.stderr, objectMode, noop transform', testGeneratorOutput, 2, true, true, true, true, 'duplex', execa);146-test('Can use duplexes with result.stdio[*] as output, objectMode, noop transform', testGeneratorOutput, 3, true, false, true, true, 'duplex', execa);147-test('Can use duplexes with error.stdio[1], objectMode, noop transform', testGeneratorOutput, 1, false, false, true, true, 'duplex', execa);148-test('Can use duplexes with error.stdout, objectMode, noop transform', testGeneratorOutput, 1, false, true, true, true, 'duplex', execa);149-test('Can use duplexes with error.stdio[2], objectMode, noop transform', testGeneratorOutput, 2, false, false, true, true, 'duplex', execa);150-test('Can use duplexes with error.stderr, objectMode, noop transform', testGeneratorOutput, 2, false, true, true, true, 'duplex', execa);151-test('Can use duplexes with error.stdio[*] as output, objectMode, noop transform', testGeneratorOutput, 3, false, false, true, true, 'duplex', execa);152-test('Can use webTransforms with result.stdio[1]', testGeneratorOutput, 1, true, false, false, false, 'webTransform', execa);153-test('Can use webTransforms with result.stdout', testGeneratorOutput, 1, true, true, false, false, 'webTransform', execa);154-test('Can use webTransforms with result.stdio[2]', testGeneratorOutput, 2, true, false, false, false, 'webTransform', execa);155-test('Can use webTransforms with result.stderr', testGeneratorOutput, 2, true, true, false, false, 'webTransform', execa);156-test('Can use webTransforms with result.stdio[*] as output', testGeneratorOutput, 3, true, false, false, false, 'webTransform', execa);157-test('Can use webTransforms with error.stdio[1]', testGeneratorOutput, 1, false, false, false, false, 'webTransform', execa);158-test('Can use webTransforms with error.stdout', testGeneratorOutput, 1, false, true, false, false, 'webTransform', execa);159-test('Can use webTransforms with error.stdio[2]', testGeneratorOutput, 2, false, false, false, false, 'webTransform', execa);160-test('Can use webTransforms with error.stderr', testGeneratorOutput, 2, false, true, false, false, 'webTransform', execa);161-test('Can use webTransforms with error.stdio[*] as output', testGeneratorOutput, 3, false, false, false, false, 'webTransform', execa);162-test('Can use webTransforms with result.stdio[1], objectMode', testGeneratorOutput, 1, true, false, true, false, 'webTransform', execa);163-test('Can use webTransforms with result.stdout, objectMode', testGeneratorOutput, 1, true, true, true, false, 'webTransform', execa);164-test('Can use webTransforms with result.stdio[2], objectMode', testGeneratorOutput, 2, true, false, true, false, 'webTransform', execa);165-test('Can use webTransforms with result.stderr, objectMode', testGeneratorOutput, 2, true, true, true, false, 'webTransform', execa);166-test('Can use webTransforms with result.stdio[*] as output, objectMode', testGeneratorOutput, 3, true, false, true, false, 'webTransform', execa);167-test('Can use webTransforms with error.stdio[1], objectMode', testGeneratorOutput, 1, false, false, true, false, 'webTransform', execa);168-test('Can use webTransforms with error.stdout, objectMode', testGeneratorOutput, 1, false, true, true, false, 'webTransform', execa);169-test('Can use webTransforms with error.stdio[2], objectMode', testGeneratorOutput, 2, false, false, true, false, 'webTransform', execa);170-test('Can use webTransforms with error.stderr, objectMode', testGeneratorOutput, 2, false, true, true, false, 'webTransform', execa);171-test('Can use webTransforms with error.stdio[*] as output, objectMode', testGeneratorOutput, 3, false, false, true, false, 'webTransform', execa);172-test('Can use webTransforms with result.stdio[1], noop transform', testGeneratorOutput, 1, true, false, false, true, 'webTransform', execa);173-test('Can use webTransforms with result.stdout, noop transform', testGeneratorOutput, 1, true, true, false, true, 'webTransform', execa);174-test('Can use webTransforms with result.stdio[2], noop transform', testGeneratorOutput, 2, true, false, false, true, 'webTransform', execa);175-test('Can use webTransforms with result.stderr, noop transform', testGeneratorOutput, 2, true, true, false, true, 'webTransform', execa);176-test('Can use webTransforms with result.stdio[*] as output, noop transform', testGeneratorOutput, 3, true, false, false, true, 'webTransform', execa);177-test('Can use webTransforms with error.stdio[1], noop transform', testGeneratorOutput, 1, false, false, false, true, 'webTransform', execa);178-test('Can use webTransforms with error.stdout, noop transform', testGeneratorOutput, 1, false, true, false, true, 'webTransform', execa);179-test('Can use webTransforms with error.stdio[2], noop transform', testGeneratorOutput, 2, false, false, false, true, 'webTransform', execa);180-test('Can use webTransforms with error.stderr, noop transform', testGeneratorOutput, 2, false, true, false, true, 'webTransform', execa);181-test('Can use webTransforms with error.stdio[*] as output, noop transform', testGeneratorOutput, 3, false, false, false, true, 'webTransform', execa);182-test('Can use webTransforms with result.stdio[1], objectMode, noop transform', testGeneratorOutput, 1, true, false, true, true, 'webTransform', execa);183-test('Can use webTransforms with result.stdout, objectMode, noop transform', testGeneratorOutput, 1, true, true, true, true, 'webTransform', execa);184-test('Can use webTransforms with result.stdio[2], objectMode, noop transform', testGeneratorOutput, 2, true, false, true, true, 'webTransform', execa);185-test('Can use webTransforms with result.stderr, objectMode, noop transform', testGeneratorOutput, 2, true, true, true, true, 'webTransform', execa);186-test('Can use webTransforms with result.stdio[*] as output, objectMode, noop transform', testGeneratorOutput, 3, true, false, true, true, 'webTransform', execa);187-test('Can use webTransforms with error.stdio[1], objectMode, noop transform', testGeneratorOutput, 1, false, false, true, true, 'webTransform', execa);188-test('Can use webTransforms with error.stdout, objectMode, noop transform', testGeneratorOutput, 1, false, true, true, true, 'webTransform', execa);189-test('Can use webTransforms with error.stdio[2], objectMode, noop transform', testGeneratorOutput, 2, false, false, true, true, 'webTransform', execa);190-test('Can use webTransforms with error.stderr, objectMode, noop transform', testGeneratorOutput, 2, false, true, true, true, 'webTransform', execa);191-test('Can use webTransforms with error.stdio[*] as output, objectMode, noop transform', testGeneratorOutput, 3, false, false, true, true, 'webTransform', execa);192-193-// eslint-disable-next-line max-params194-const testGeneratorOutputPipe = async (t, fdNumber, useShortcutProperty, objectMode, addNoopTransform, type) => {195- const {generators, output, getStreamMethod} = getOutputObjectMode(objectMode, addNoopTransform, type, true);196- const subprocess = execa('noop-fd.js', [`${fdNumber}`, foobarString], getStdio(fdNumber, generators));197- const stream = useShortcutProperty ? [subprocess.stdout, subprocess.stderr][fdNumber - 1] : subprocess.stdio[fdNumber];198- const [result] = await Promise.all([getStreamMethod(stream), subprocess]);199- t.deepEqual(result, output);200-};201-202-test('Can use generators with subprocess.stdio[1]', testGeneratorOutputPipe, 1, false, false, false, 'generator');203-test('Can use generators with subprocess.stdout', testGeneratorOutputPipe, 1, true, false, false, 'generator');204-test('Can use generators with subprocess.stdio[2]', testGeneratorOutputPipe, 2, false, false, false, 'generator');205-test('Can use generators with subprocess.stderr', testGeneratorOutputPipe, 2, true, false, false, 'generator');206-test('Can use generators with subprocess.stdio[*] as output', testGeneratorOutputPipe, 3, false, false, false, 'generator');207-test('Can use generators with subprocess.stdio[1], objectMode', testGeneratorOutputPipe, 1, false, true, false, 'generator');208-test('Can use generators with subprocess.stdout, objectMode', testGeneratorOutputPipe, 1, true, true, false, 'generator');209-test('Can use generators with subprocess.stdio[2], objectMode', testGeneratorOutputPipe, 2, false, true, false, 'generator');210-test('Can use generators with subprocess.stderr, objectMode', testGeneratorOutputPipe, 2, true, true, false, 'generator');211-test('Can use generators with subprocess.stdio[*] as output, objectMode', testGeneratorOutputPipe, 3, false, true, false, 'generator');212-test('Can use generators with subprocess.stdio[1], noop transform', testGeneratorOutputPipe, 1, false, false, true, 'generator');213-test('Can use generators with subprocess.stdout, noop transform', testGeneratorOutputPipe, 1, true, false, true, 'generator');214-test('Can use generators with subprocess.stdio[2], noop transform', testGeneratorOutputPipe, 2, false, false, true, 'generator');215-test('Can use generators with subprocess.stderr, noop transform', testGeneratorOutputPipe, 2, true, false, true, 'generator');216-test('Can use generators with subprocess.stdio[*] as output, noop transform', testGeneratorOutputPipe, 3, false, false, true, 'generator');217-test('Can use generators with subprocess.stdio[1], objectMode, noop transform', testGeneratorOutputPipe, 1, false, true, true, 'generator');218-test('Can use generators with subprocess.stdout, objectMode, noop transform', testGeneratorOutputPipe, 1, true, true, true, 'generator');219-test('Can use generators with subprocess.stdio[2], objectMode, noop transform', testGeneratorOutputPipe, 2, false, true, true, 'generator');220-test('Can use generators with subprocess.stderr, objectMode, noop transform', testGeneratorOutputPipe, 2, true, true, true, 'generator');221-test('Can use generators with subprocess.stdio[*] as output, objectMode, noop transform', testGeneratorOutputPipe, 3, false, true, true, 'generator');222-test('Can use duplexes with subprocess.stdio[1]', testGeneratorOutputPipe, 1, false, false, false, 'duplex');223-test('Can use duplexes with subprocess.stdout', testGeneratorOutputPipe, 1, true, false, false, 'duplex');224-test('Can use duplexes with subprocess.stdio[2]', testGeneratorOutputPipe, 2, false, false, false, 'duplex');225-test('Can use duplexes with subprocess.stderr', testGeneratorOutputPipe, 2, true, false, false, 'duplex');226-test('Can use duplexes with subprocess.stdio[*] as output', testGeneratorOutputPipe, 3, false, false, false, 'duplex');227-test('Can use duplexes with subprocess.stdio[1], objectMode', testGeneratorOutputPipe, 1, false, true, false, 'duplex');228-test('Can use duplexes with subprocess.stdout, objectMode', testGeneratorOutputPipe, 1, true, true, false, 'duplex');229-test('Can use duplexes with subprocess.stdio[2], objectMode', testGeneratorOutputPipe, 2, false, true, false, 'duplex');230-test('Can use duplexes with subprocess.stderr, objectMode', testGeneratorOutputPipe, 2, true, true, false, 'duplex');231-test('Can use duplexes with subprocess.stdio[*] as output, objectMode', testGeneratorOutputPipe, 3, false, true, false, 'duplex');232-test('Can use duplexes with subprocess.stdio[1], noop transform', testGeneratorOutputPipe, 1, false, false, true, 'duplex');233-test('Can use duplexes with subprocess.stdout, noop transform', testGeneratorOutputPipe, 1, true, false, true, 'duplex');234-test('Can use duplexes with subprocess.stdio[2], noop transform', testGeneratorOutputPipe, 2, false, false, true, 'duplex');235-test('Can use duplexes with subprocess.stderr, noop transform', testGeneratorOutputPipe, 2, true, false, true, 'duplex');236-test('Can use duplexes with subprocess.stdio[*] as output, noop transform', testGeneratorOutputPipe, 3, false, false, true, 'duplex');237-test('Can use duplexes with subprocess.stdio[1], objectMode, noop transform', testGeneratorOutputPipe, 1, false, true, true, 'duplex');238-test('Can use duplexes with subprocess.stdout, objectMode, noop transform', testGeneratorOutputPipe, 1, true, true, true, 'duplex');239-test('Can use duplexes with subprocess.stdio[2], objectMode, noop transform', testGeneratorOutputPipe, 2, false, true, true, 'duplex');240-test('Can use duplexes with subprocess.stderr, objectMode, noop transform', testGeneratorOutputPipe, 2, true, true, true, 'duplex');241-test('Can use duplexes with subprocess.stdio[*] as output, objectMode, noop transform', testGeneratorOutputPipe, 3, false, true, true, 'duplex');242-test('Can use webTransforms with subprocess.stdio[1]', testGeneratorOutputPipe, 1, false, false, false, 'webTransform');243-test('Can use webTransforms with subprocess.stdout', testGeneratorOutputPipe, 1, true, false, false, 'webTransform');244-test('Can use webTransforms with subprocess.stdio[2]', testGeneratorOutputPipe, 2, false, false, false, 'webTransform');245-test('Can use webTransforms with subprocess.stderr', testGeneratorOutputPipe, 2, true, false, false, 'webTransform');246-test('Can use webTransforms with subprocess.stdio[*] as output', testGeneratorOutputPipe, 3, false, false, false, 'webTransform');247-test('Can use webTransforms with subprocess.stdio[1], objectMode', testGeneratorOutputPipe, 1, false, true, false, 'webTransform');248-test('Can use webTransforms with subprocess.stdout, objectMode', testGeneratorOutputPipe, 1, true, true, false, 'webTransform');249-test('Can use webTransforms with subprocess.stdio[2], objectMode', testGeneratorOutputPipe, 2, false, true, false, 'webTransform');250-test('Can use webTransforms with subprocess.stderr, objectMode', testGeneratorOutputPipe, 2, true, true, false, 'webTransform');251-test('Can use webTransforms with subprocess.stdio[*] as output, objectMode', testGeneratorOutputPipe, 3, false, true, false, 'webTransform');252-test('Can use webTransforms with subprocess.stdio[1], noop transform', testGeneratorOutputPipe, 1, false, false, true, 'webTransform');253-test('Can use webTransforms with subprocess.stdout, noop transform', testGeneratorOutputPipe, 1, true, false, true, 'webTransform');254-test('Can use webTransforms with subprocess.stdio[2], noop transform', testGeneratorOutputPipe, 2, false, false, true, 'webTransform');255-test('Can use webTransforms with subprocess.stderr, noop transform', testGeneratorOutputPipe, 2, true, false, true, 'webTransform');256-test('Can use webTransforms with subprocess.stdio[*] as output, noop transform', testGeneratorOutputPipe, 3, false, false, true, 'webTransform');257-test('Can use webTransforms with subprocess.stdio[1], objectMode, noop transform', testGeneratorOutputPipe, 1, false, true, true, 'webTransform');258-test('Can use webTransforms with subprocess.stdout, objectMode, noop transform', testGeneratorOutputPipe, 1, true, true, true, 'webTransform');259-test('Can use webTransforms with subprocess.stdio[2], objectMode, noop transform', testGeneratorOutputPipe, 2, false, true, true, 'webTransform');260-test('Can use webTransforms with subprocess.stderr, objectMode, noop transform', testGeneratorOutputPipe, 2, true, true, true, 'webTransform');261-test('Can use webTransforms with subprocess.stdio[*] as output, objectMode, noop transform', testGeneratorOutputPipe, 3, false, true, true, 'webTransform');deleted:test/stdio/transform-run.js-185 removed
1-import {Buffer} from 'node:buffer';2-import {scheduler} from 'node:timers/promises';3-import test from 'ava';4-import {getStreamAsArray} from 'get-stream';5-import {execa, execaSync} from '../../index.js';6-import {foobarString} from '../helpers/input.js';7-import {8- noopGenerator,9- outputObjectGenerator,10- convertTransformToFinal,11- prefix,12- suffix,13-} from '../helpers/generator.js';14-import {generatorsMap} from '../helpers/map.js';15-import {defaultHighWaterMark} from '../helpers/stream.js';16-import {setFixtureDir} from '../helpers/fixtures-dir.js';17-import {maxBuffer, assertErrorMessage} from '../helpers/max-buffer.js';18-19-setFixtureDir();20-21-const repeatCount = defaultHighWaterMark * 3;22-23-const writerGenerator = function * () {24- for (let index = 0; index < repeatCount; index += 1) {25- yield '\n';26- }27-};28-29-const getLengthGenerator = function * (t, chunk) {30- t.is(chunk.length, 1);31- yield chunk;32-};33-34-// eslint-disable-next-line max-params35-const testHighWaterMark = async (t, passThrough, binary, objectMode, execaMethod) => {36- const {stdout} = await execaMethod('noop.js', {37- stdout: [38- ...(objectMode ? [outputObjectGenerator()] : []),39- writerGenerator,40- ...(passThrough ? [noopGenerator(false, binary)] : []),41- {transform: getLengthGenerator.bind(undefined, t), preserveNewlines: true, objectMode: true},42- ],43- });44- t.is(stdout.length, repeatCount);45- t.true(stdout.every(chunk => chunk === '\n'));46-};47-48-test('Synchronous yields are not buffered, no passThrough', testHighWaterMark, false, false, false, execa);49-test('Synchronous yields are not buffered, line-wise passThrough', testHighWaterMark, true, false, false, execa);50-test('Synchronous yields are not buffered, binary passThrough', testHighWaterMark, true, true, false, execa);51-test('Synchronous yields are not buffered, objectMode as input but not output', testHighWaterMark, false, false, true, execa);52-test('Synchronous yields are not buffered, no passThrough, sync', testHighWaterMark, false, false, false, execaSync);53-test('Synchronous yields are not buffered, line-wise passThrough, sync', testHighWaterMark, true, false, false, execaSync);54-test('Synchronous yields are not buffered, binary passThrough, sync', testHighWaterMark, true, true, false, execaSync);55-test('Synchronous yields are not buffered, objectMode as input but not output, sync', testHighWaterMark, false, false, true, execaSync);56-57-// eslint-disable-next-line max-params58-const testNoYield = async (t, type, objectMode, final, output, execaMethod) => {59- const {stdout} = await execaMethod('noop.js', {stdout: convertTransformToFinal(generatorsMap[type].noYield(objectMode), final)});60- t.deepEqual(stdout, output);61-};62-63-test('Generator can filter "transform" by not calling yield', testNoYield, 'generator', false, false, '', execa);64-test('Generator can filter "transform" by not calling yield, objectMode', testNoYield, 'generator', true, false, [], execa);65-test('Generator can filter "final" by not calling yield', testNoYield, 'generator', false, true, '', execa);66-test('Generator can filter "final" by not calling yield, objectMode', testNoYield, 'generator', true, true, [], execa);67-test('Generator can filter "transform" by not calling yield, sync', testNoYield, 'generator', false, false, '', execaSync);68-test('Generator can filter "transform" by not calling yield, objectMode, sync', testNoYield, 'generator', true, false, [], execaSync);69-test('Generator can filter "final" by not calling yield, sync', testNoYield, 'generator', false, true, '', execaSync);70-test('Generator can filter "final" by not calling yield, objectMode, sync', testNoYield, 'generator', true, true, [], execaSync);71-test('Duplex can filter by not calling push', testNoYield, 'duplex', false, false, '', execa);72-test('Duplex can filter by not calling push, objectMode', testNoYield, 'duplex', true, false, [], execa);73-test('WebTransform can filter by not calling push', testNoYield, 'webTransform', false, false, '', execa);74-test('WebTransform can filter by not calling push, objectMode', testNoYield, 'webTransform', true, false, [], execa);75-76-const testMultipleYields = async (t, type, final, binary) => {77- const {stdout} = await execa('noop-fd.js', ['1', foobarString], {stdout: convertTransformToFinal(generatorsMap[type].multipleYield(), final)});78- const newline = binary ? '' : '\n';79- t.is(stdout, `${prefix}${newline}${foobarString}${newline}${suffix}`);80-};81-82-test('Generator can yield "transform" multiple times at different moments', testMultipleYields, 'generator', false, false);83-test('Generator can yield "final" multiple times at different moments', testMultipleYields, 'generator', true, false);84-test('Duplex can push multiple times at different moments', testMultipleYields, 'duplex', false, true);85-test('WebTransform can push multiple times at different moments', testMultipleYields, 'webTransform', false, true);86-87-const partsPerChunk = 4;88-const chunksPerCall = 10;89-const callCount = 5;90-const fullString = '\n'.repeat(defaultHighWaterMark / partsPerChunk);91-92-const yieldFullStrings = function * () {93- yield * Array.from({length: partsPerChunk * chunksPerCall}).fill(fullString);94-};95-96-const manyYieldGenerator = async function * () {97- for (let index = 0; index < callCount; index += 1) {98- yield * yieldFullStrings();99- // eslint-disable-next-line no-await-in-loop100- await scheduler.yield();101- }102-};103-104-const testManyYields = async (t, final) => {105- const subprocess = execa('noop.js', {stdout: convertTransformToFinal(manyYieldGenerator, final), stripFinalNewline: false});106- const [chunks, {stdout}] = await Promise.all([getStreamAsArray(subprocess.stdout), subprocess]);107- const expectedChunk = Buffer.from(fullString);108- t.deepEqual(chunks, Array.from({length: callCount * partsPerChunk * chunksPerCall}).fill(expectedChunk));109- t.is(chunks.join(''), stdout);110-};111-112-test('Generator "transform" yields are sent right away', testManyYields, false);113-test('Generator "final" yields are sent right away', testManyYields, true);114-115-const testMaxBuffer = async (t, type) => {116- const bigString = '.'.repeat(maxBuffer);117- const {stdout} = await execa('noop.js', {118- maxBuffer,119- stdout: generatorsMap[type].getOutput(bigString)(false, true),120- });121- t.is(stdout, bigString);122-123- const {isMaxBuffer, shortMessage} = await t.throwsAsync(execa('noop.js', {124- maxBuffer,125- stdout: generatorsMap[type].getOutput(`${bigString}.`)(false, true),126- }));127- t.true(isMaxBuffer);128- assertErrorMessage(t, shortMessage);129-};130-131-test('Generators take "maxBuffer" into account', testMaxBuffer, 'generator');132-test('Duplexes take "maxBuffer" into account', testMaxBuffer, 'duplex');133-test('WebTransforms take "maxBuffer" into account', testMaxBuffer, 'webTransform');134-135-test('Generators does not take "maxBuffer" into account, sync', t => {136- const bigString = '.'.repeat(maxBuffer);137- const {isMaxBuffer, stdout} = execaSync('noop.js', {138- maxBuffer,139- stdout: generatorsMap.generator.getOutput(`${bigString}.`)(false, true),140- });141- t.false(isMaxBuffer);142- t.is(stdout.length, maxBuffer + 1);143-});144-145-const testMaxBufferObject = async (t, type) => {146- const bigArray = Array.from({length: maxBuffer}).fill('..');147- const {stdout} = await execa('noop.js', {148- maxBuffer,149- stdout: generatorsMap[type].getOutputs(bigArray)(true, true),150- });151- t.is(stdout.length, maxBuffer);152-153- const {isMaxBuffer, shortMessage} = await t.throwsAsync(execa('noop.js', {154- maxBuffer,155- stdout: generatorsMap[type].getOutputs([...bigArray, ''])(true, true),156- }));157- t.true(isMaxBuffer);158- assertErrorMessage(t, shortMessage, {unit: 'objects'});159-};160-161-test('Generators take "maxBuffer" into account, objectMode', testMaxBufferObject, 'generator');162-test('Duplexes take "maxBuffer" into account, objectMode', testMaxBufferObject, 'duplex');163-test('WebTransforms take "maxBuffer" into account, objectMode', testMaxBufferObject, 'webTransform');164-165-test('Generators does not take "maxBuffer" into account, objectMode, sync', t => {166- const bigArray = Array.from({length: maxBuffer}).fill('..');167- const {isMaxBuffer, stdout} = execaSync('noop.js', {168- maxBuffer,169- stdout: generatorsMap.generator.getOutputs([...bigArray, ''])(true, true),170- });171- t.false(isMaxBuffer);172- t.is(stdout.length, maxBuffer + 1);173-});174-175-const testAsyncGenerators = async (t, type, final) => {176- const {stdout} = await execa('noop.js', {177- stdout: convertTransformToFinal(generatorsMap[type].timeout(1e2)(), final),178- });179- t.is(stdout, foobarString);180-};181-182-test('Generators "transform" is awaited on success', testAsyncGenerators, 'generator', false);183-test('Generators "final" is awaited on success', testAsyncGenerators, 'generator', true);184-test('Duplex is awaited on success', testAsyncGenerators, 'duplex', false);185-test('WebTransform is awaited on success', testAsyncGenerators, 'webTransform', false);deleted:test/stdio/validate.js-95 removed
1-import {Buffer} from 'node:buffer';2-import test from 'ava';3-import {execa, execaSync} from '../../index.js';4-import {setFixtureDir} from '../helpers/fixtures-dir.js';5-import {getStdio} from '../helpers/stdio.js';6-import {foobarUint8Array, foobarBuffer, foobarObject} from '../helpers/input.js';7-import {serializeGenerator, getOutputGenerator, convertTransformToFinal} from '../helpers/generator.js';8-9-setFixtureDir();10-11-const getMessage = input => {12- if (input === null || input === undefined) {13- return 'not be called at all';14- }15-16- if (Buffer.isBuffer(input)) {17- return 'not a buffer';18- }19-20- return 'a string or an Uint8Array';21-};22-23-const lastInputGenerator = input => objectMode => [foobarUint8Array, getOutputGenerator(input)(objectMode)];24-const inputGenerator = input => objectMode => [...lastInputGenerator(input)(objectMode), serializeGenerator(true)];25-26-// eslint-disable-next-line max-params27-const testGeneratorReturn = async (t, fdNumber, generator, input, objectMode, isInput) => {28- const fixtureName = isInput ? 'stdin-fd.js' : 'noop-fd.js';29- const {message} = await t.throwsAsync(execa(fixtureName, [`${fdNumber}`], getStdio(fdNumber, generator(input)(objectMode))));30- t.true(message.includes(getMessage(input)));31-};32-33-test('Generators with result.stdin cannot return an object if not in objectMode', testGeneratorReturn, 0, inputGenerator, foobarObject, false, true);34-test('Generators with result.stdio[*] as input cannot return an object if not in objectMode', testGeneratorReturn, 3, inputGenerator, foobarObject, false, true);35-test('The last generator with result.stdin cannot return an object even in objectMode', testGeneratorReturn, 0, lastInputGenerator, foobarObject, true, true);36-test('The last generator with result.stdio[*] as input cannot return an object even in objectMode', testGeneratorReturn, 3, lastInputGenerator, foobarObject, true, true);37-test('Generators with result.stdout cannot return an object if not in objectMode', testGeneratorReturn, 1, getOutputGenerator, foobarObject, false, false);38-test('Generators with result.stderr cannot return an object if not in objectMode', testGeneratorReturn, 2, getOutputGenerator, foobarObject, false, false);39-test('Generators with result.stdio[*] as output cannot return an object if not in objectMode', testGeneratorReturn, 3, getOutputGenerator, foobarObject, false, false);40-test('Generators with result.stdin cannot return a Buffer if not in objectMode', testGeneratorReturn, 0, inputGenerator, foobarBuffer, false, true);41-test('Generators with result.stdio[*] as input cannot return a Buffer if not in objectMode', testGeneratorReturn, 3, inputGenerator, foobarBuffer, false, true);42-test('The last generator with result.stdin cannot return a Buffer even in objectMode', testGeneratorReturn, 0, lastInputGenerator, foobarBuffer, true, true);43-test('The last generator with result.stdio[*] as input cannot return a Buffer even in objectMode', testGeneratorReturn, 3, lastInputGenerator, foobarBuffer, true, true);44-test('Generators with result.stdout cannot return a Buffer if not in objectMode', testGeneratorReturn, 1, getOutputGenerator, foobarBuffer, false, false);45-test('Generators with result.stderr cannot return a Buffer if not in objectMode', testGeneratorReturn, 2, getOutputGenerator, foobarBuffer, false, false);46-test('Generators with result.stdio[*] as output cannot return a Buffer if not in objectMode', testGeneratorReturn, 3, getOutputGenerator, foobarBuffer, false, false);47-test('Generators with result.stdin cannot return null if not in objectMode', testGeneratorReturn, 0, inputGenerator, null, false, true);48-test('Generators with result.stdin cannot return null if in objectMode', testGeneratorReturn, 0, inputGenerator, null, true, true);49-test('Generators with result.stdout cannot return null if not in objectMode', testGeneratorReturn, 1, getOutputGenerator, null, false, false);50-test('Generators with result.stdout cannot return null if in objectMode', testGeneratorReturn, 1, getOutputGenerator, null, true, false);51-test('Generators with result.stdin cannot return undefined if not in objectMode', testGeneratorReturn, 0, inputGenerator, undefined, false, true);52-test('Generators with result.stdin cannot return undefined if in objectMode', testGeneratorReturn, 0, inputGenerator, undefined, true, true);53-test('Generators with result.stdout cannot return undefined if not in objectMode', testGeneratorReturn, 1, getOutputGenerator, undefined, false, false);54-test('Generators with result.stdout cannot return undefined if in objectMode', testGeneratorReturn, 1, getOutputGenerator, undefined, true, false);55-56-// eslint-disable-next-line max-params57-const testGeneratorReturnSync = (t, fdNumber, generator, input, objectMode, isInput) => {58- const fixtureName = isInput ? 'stdin-fd.js' : 'noop-fd.js';59- const {message} = t.throws(() => {60- execaSync(fixtureName, [`${fdNumber}`], getStdio(fdNumber, generator(input)(objectMode)));61- });62- t.true(message.includes(getMessage(input)));63-};64-65-test('Generators with result.stdin cannot return an object if not in objectMode, sync', testGeneratorReturnSync, 0, inputGenerator, foobarObject, false, true);66-test('The last generator with result.stdin cannot return an object even in objectMode, sync', testGeneratorReturnSync, 0, lastInputGenerator, foobarObject, true, true);67-test('Generators with result.stdout cannot return an object if not in objectMode, sync', testGeneratorReturnSync, 1, getOutputGenerator, foobarObject, false, false);68-test('Generators with result.stderr cannot return an object if not in objectMode, sync', testGeneratorReturnSync, 2, getOutputGenerator, foobarObject, false, false);69-test('Generators with result.stdio[*] as output cannot return an object if not in objectMode, sync', testGeneratorReturnSync, 3, getOutputGenerator, foobarObject, false, false);70-test('Generators with result.stdin cannot return a Buffer if not in objectMode, sync', testGeneratorReturnSync, 0, inputGenerator, foobarBuffer, false, true);71-test('The last generator with result.stdin cannot return a Buffer even in objectMode, sync', testGeneratorReturnSync, 0, lastInputGenerator, foobarBuffer, true, true);72-test('Generators with result.stdout cannot return a Buffer if not in objectMode, sync', testGeneratorReturnSync, 1, getOutputGenerator, foobarBuffer, false, false);73-test('Generators with result.stderr cannot return a Buffer if not in objectMode, sync', testGeneratorReturnSync, 2, getOutputGenerator, foobarBuffer, false, false);74-test('Generators with result.stdio[*] as output cannot return a Buffer if not in objectMode, sync', testGeneratorReturnSync, 3, getOutputGenerator, foobarBuffer, false, false);75-test('Generators with result.stdin cannot return null if not in objectMode, sync', testGeneratorReturnSync, 0, inputGenerator, null, false, true);76-test('Generators with result.stdin cannot return null if in objectMode, sync', testGeneratorReturnSync, 0, inputGenerator, null, true, true);77-test('Generators with result.stdout cannot return null if not in objectMode, sync', testGeneratorReturnSync, 1, getOutputGenerator, null, false, false);78-test('Generators with result.stdout cannot return null if in objectMode, sync', testGeneratorReturnSync, 1, getOutputGenerator, null, true, false);79-test('Generators with result.stdin cannot return undefined if not in objectMode, sync', testGeneratorReturnSync, 0, inputGenerator, undefined, false, true);80-test('Generators with result.stdin cannot return undefined if in objectMode, sync', testGeneratorReturnSync, 0, inputGenerator, undefined, true, true);81-test('Generators with result.stdout cannot return undefined if not in objectMode, sync', testGeneratorReturnSync, 1, getOutputGenerator, undefined, false, false);82-test('Generators with result.stdout cannot return undefined if in objectMode, sync', testGeneratorReturnSync, 1, getOutputGenerator, undefined, true, false);83-84-test('Generators "final" return value is validated', async t => {85- await t.throwsAsync(86- execa('noop.js', {stdout: convertTransformToFinal(getOutputGenerator(null)(true), true)}),87- {message: /not be called at all/},88- );89-});90-91-test('Generators "final" return value is validated, sync', t => {92- t.throws(() => {93- execaSync('noop.js', {stdout: convertTransformToFinal(getOutputGenerator(null)(true), true)});94- }, {message: /not be called at all/});95-});deleted:test/stream/all.js-171 removed
1-import test from 'ava';2-import {execa, execaSync} from '../../index.js';3-import {setFixtureDir} from '../helpers/fixtures-dir.js';4-import {defaultHighWaterMark} from '../helpers/stream.js';5-import {foobarString} from '../helpers/input.js';6-7-setFixtureDir();8-9-const textEncoder = new TextEncoder();10-const foobarStringFull = `${foobarString}\n`;11-const doubleFoobarStringFull = `${foobarStringFull}${foobarStringFull}`;12-const doubleFoobarString = `${foobarStringFull}${foobarString}`;13-const doubleFoobarUint8ArrayFull = textEncoder.encode(doubleFoobarStringFull);14-const doubleFoobarUint8Array = textEncoder.encode(doubleFoobarString);15-const doubleFoobarArrayFull = [foobarStringFull, foobarStringFull];16-const doubleFoobarArray = [foobarString, foobarString];17-18-// eslint-disable-next-line max-params19-const testAllBoth = async (t, expectedOutput, encoding, lines, stripFinalNewline, isFailure, execaMethod) => {20- const fixtureName = isFailure ? 'noop-both-fail.js' : 'noop-both.js';21- const {exitCode, all} = await execaMethod(fixtureName, [foobarString], {all: true, encoding, lines, stripFinalNewline, reject: !isFailure});22- t.is(exitCode, isFailure ? 1 : 0);23- t.deepEqual(all, expectedOutput);24-};25-26-const fdOne = {stderr: true};27-const fdBoth = {stdout: true, stderr: true};28-29-test('result.all is defined', testAllBoth, doubleFoobarStringFull, 'utf8', false, false, false, execa);30-test('result.all is defined, encoding "buffer"', testAllBoth, doubleFoobarUint8ArrayFull, 'buffer', false, false, false, execa);31-test('result.all is defined, lines', testAllBoth, doubleFoobarArrayFull, 'utf8', true, false, false, execa);32-test('result.all is defined, lines, fd-specific one', testAllBoth, doubleFoobarArrayFull, 'utf8', fdOne, false, false, execa);33-test('result.all is defined, lines, fd-specific both', testAllBoth, doubleFoobarArrayFull, 'utf8', fdBoth, false, false, execa);34-test('result.all is defined, stripFinalNewline', testAllBoth, doubleFoobarString, 'utf8', false, true, false, execa);35-test('result.all is defined, stripFinalNewline, fd-specific one', testAllBoth, doubleFoobarString, 'utf8', false, fdOne, false, execa);36-test('result.all is defined, stripFinalNewline, fd-specific both', testAllBoth, doubleFoobarString, 'utf8', false, fdBoth, false, execa);37-test('result.all is defined, encoding "buffer", stripFinalNewline', testAllBoth, doubleFoobarUint8Array, 'buffer', false, true, false, execa);38-test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific one', testAllBoth, doubleFoobarUint8Array, 'buffer', false, fdOne, false, execa);39-test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific both', testAllBoth, doubleFoobarUint8Array, 'buffer', false, fdBoth, false, execa);40-test('result.all is defined, lines, stripFinalNewline', testAllBoth, doubleFoobarArray, 'utf8', true, true, false, execa);41-test('result.all is defined, lines, fd-specific one, stripFinalNewline', testAllBoth, doubleFoobarArray, 'utf8', fdOne, true, false, execa);42-test('result.all is defined, lines, fd-specific both, stripFinalNewline', testAllBoth, doubleFoobarArray, 'utf8', fdBoth, true, false, execa);43-test('result.all is defined, lines, stripFinalNewline, fd-specific one', testAllBoth, doubleFoobarArray, 'utf8', true, fdOne, false, execa);44-test('result.all is defined, lines, stripFinalNewline, fd-specific both', testAllBoth, doubleFoobarArray, 'utf8', true, fdBoth, false, execa);45-test('result.all is defined, failure', testAllBoth, doubleFoobarStringFull, 'utf8', false, false, true, execa);46-test('result.all is defined, encoding "buffer", failure', testAllBoth, doubleFoobarUint8ArrayFull, 'buffer', false, false, true, execa);47-test('result.all is defined, lines, failure', testAllBoth, doubleFoobarArrayFull, 'utf8', true, false, true, execa);48-test('result.all is defined, lines, fd-specific one, failure', testAllBoth, doubleFoobarArrayFull, 'utf8', fdOne, false, true, execa);49-test('result.all is defined, lines, fd-specific both, failure', testAllBoth, doubleFoobarArrayFull, 'utf8', fdBoth, false, true, execa);50-test('result.all is defined, stripFinalNewline, failure', testAllBoth, doubleFoobarString, 'utf8', false, true, true, execa);51-test('result.all is defined, stripFinalNewline, fd-specific one, failure', testAllBoth, doubleFoobarString, 'utf8', false, fdOne, true, execa);52-test('result.all is defined, stripFinalNewline, fd-specific both, failure', testAllBoth, doubleFoobarString, 'utf8', false, fdBoth, true, execa);53-test('result.all is defined, encoding "buffer", stripFinalNewline, failure', testAllBoth, doubleFoobarUint8Array, 'buffer', false, true, true, execa);54-test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific one, failure', testAllBoth, doubleFoobarUint8Array, 'buffer', false, fdOne, true, execa);55-test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific both, failure', testAllBoth, doubleFoobarUint8Array, 'buffer', false, fdBoth, true, execa);56-test('result.all is defined, lines, stripFinalNewline, failure', testAllBoth, doubleFoobarArray, 'utf8', true, true, true, execa);57-test('result.all is defined, lines, fd-specific one, stripFinalNewline, failure', testAllBoth, doubleFoobarArray, 'utf8', fdOne, true, true, execa);58-test('result.all is defined, lines, fd-specific both, stripFinalNewline, failure', testAllBoth, doubleFoobarArray, 'utf8', fdBoth, true, true, execa);59-test('result.all is defined, lines, stripFinalNewline, fd-specific one, failure', testAllBoth, doubleFoobarArray, 'utf8', true, fdOne, true, execa);60-test('result.all is defined, lines, stripFinalNewline, fd-specific both, failure', testAllBoth, doubleFoobarArray, 'utf8', true, fdBoth, true, execa);61-test('result.all is defined, sync', testAllBoth, doubleFoobarStringFull, 'utf8', false, false, false, execaSync);62-test('result.all is defined, encoding "buffer", sync', testAllBoth, doubleFoobarUint8ArrayFull, 'buffer', false, false, false, execaSync);63-test('result.all is defined, lines, sync', testAllBoth, doubleFoobarArrayFull, 'utf8', true, false, false, execaSync);64-test('result.all is defined, lines, fd-specific one, sync', testAllBoth, doubleFoobarArrayFull, 'utf8', fdOne, false, false, execaSync);65-test('result.all is defined, lines, fd-specific both, sync', testAllBoth, doubleFoobarArrayFull, 'utf8', fdBoth, false, false, execaSync);66-test('result.all is defined, stripFinalNewline, sync', testAllBoth, doubleFoobarString, 'utf8', false, true, false, execaSync);67-test('result.all is defined, stripFinalNewline, fd-specific one, sync', testAllBoth, doubleFoobarString, 'utf8', false, fdOne, false, execaSync);68-test('result.all is defined, stripFinalNewline, fd-specific both, sync', testAllBoth, doubleFoobarString, 'utf8', false, fdBoth, false, execaSync);69-test('result.all is defined, encoding "buffer", stripFinalNewline, sync', testAllBoth, doubleFoobarUint8Array, 'buffer', false, true, false, execaSync);70-test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific one, sync', testAllBoth, doubleFoobarUint8Array, 'buffer', false, fdOne, false, execaSync);71-test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific both, sync', testAllBoth, doubleFoobarUint8Array, 'buffer', false, fdBoth, false, execaSync);72-test('result.all is defined, lines, stripFinalNewline, sync', testAllBoth, doubleFoobarArray, 'utf8', true, true, false, execaSync);73-test('result.all is defined, lines, fd-specific one, stripFinalNewline, sync', testAllBoth, doubleFoobarArray, 'utf8', fdOne, true, false, execaSync);74-test('result.all is defined, lines, fd-specific both, stripFinalNewline, sync', testAllBoth, doubleFoobarArray, 'utf8', fdBoth, true, false, execaSync);75-test('result.all is defined, lines, stripFinalNewline, fd-specific one, sync', testAllBoth, doubleFoobarArray, 'utf8', true, fdOne, false, execaSync);76-test('result.all is defined, lines, stripFinalNewline, fd-specific both, sync', testAllBoth, doubleFoobarArray, 'utf8', true, fdBoth, false, execaSync);77-test('result.all is defined, failure, sync', testAllBoth, doubleFoobarStringFull, 'utf8', false, false, true, execaSync);78-test('result.all is defined, encoding "buffer", failure, sync', testAllBoth, doubleFoobarUint8ArrayFull, 'buffer', false, false, true, execaSync);79-test('result.all is defined, lines, failure, sync', testAllBoth, doubleFoobarArrayFull, 'utf8', true, false, true, execaSync);80-test('result.all is defined, lines, fd-specific one, failure, sync', testAllBoth, doubleFoobarArrayFull, 'utf8', fdOne, false, true, execaSync);81-test('result.all is defined, lines, fd-specific both, failure, sync', testAllBoth, doubleFoobarArrayFull, 'utf8', fdBoth, false, true, execaSync);82-test('result.all is defined, stripFinalNewline, failure, sync', testAllBoth, doubleFoobarString, 'utf8', false, true, true, execaSync);83-test('result.all is defined, stripFinalNewline, fd-specific one, failure, sync', testAllBoth, doubleFoobarString, 'utf8', false, fdOne, true, execaSync);84-test('result.all is defined, stripFinalNewline, fd-specific both, failure, sync', testAllBoth, doubleFoobarString, 'utf8', false, fdBoth, true, execaSync);85-test('result.all is defined, encoding "buffer", stripFinalNewline, failure, sync', testAllBoth, doubleFoobarUint8Array, 'buffer', false, true, true, execaSync);86-test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific one, failure, sync', testAllBoth, doubleFoobarUint8Array, 'buffer', false, fdOne, true, execaSync);87-test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific both, failure, sync', testAllBoth, doubleFoobarUint8Array, 'buffer', false, fdBoth, true, execaSync);88-test('result.all is defined, lines, stripFinalNewline, failure, sync', testAllBoth, doubleFoobarArray, 'utf8', true, true, true, execaSync);89-test('result.all is defined, lines, fd-specific one, stripFinalNewline, failure, sync', testAllBoth, doubleFoobarArray, 'utf8', fdOne, true, true, execaSync);90-test('result.all is defined, lines, fd-specific both, stripFinalNewline, failure, sync', testAllBoth, doubleFoobarArray, 'utf8', fdBoth, true, true, execaSync);91-test('result.all is defined, lines, stripFinalNewline, fd-specific one, failure, sync', testAllBoth, doubleFoobarArray, 'utf8', true, fdOne, true, execaSync);92-test('result.all is defined, lines, stripFinalNewline, fd-specific both, failure, sync', testAllBoth, doubleFoobarArray, 'utf8', true, fdBoth, true, execaSync);93-94-test.serial('result.all shows both `stdout` and `stderr` intermixed', async t => {95- const {all} = await execa('noop-132.js', {all: true});96- t.is(all, '1\n2\n3');97-});98-99-test.serial('result.all shows both `stdout` and `stderr` not intermixed, sync', t => {100- const {all} = execaSync('noop-132.js', {all: true});101- t.is(all, '1\n3\n2');102-});103-104-const testAllIgnored = async (t, options, execaMethod) => {105- const {all} = await execaMethod('noop.js');106- t.is(all, undefined);107-};108-109-test('result.all is undefined unless opts.all is true', testAllIgnored, {}, execa);110-test('result.all is undefined if opts.all is false', testAllIgnored, {all: false}, execa);111-test('result.all is undefined if ignored', testAllIgnored, {stdio: 'ignore', all: true}, execa);112-test('result.all is undefined unless opts.all is true, sync', testAllIgnored, {}, execaSync);113-test('result.all is undefined if opts.all is false, sync', testAllIgnored, {all: false}, execaSync);114-test('result.all is undefined if ignored, sync', testAllIgnored, {stdio: 'ignore', all: true}, execaSync);115-116-const testAllProperties = async (t, options) => {117- const subprocess = execa('empty.js', {...options, all: true});118- t.is(subprocess.all.readableObjectMode, false);119- t.is(subprocess.all.readableHighWaterMark, defaultHighWaterMark);120- await subprocess;121-};122-123-test('subprocess.all has the right objectMode and highWaterMark - stdout + stderr', testAllProperties, {});124-test('subprocess.all has the right objectMode and highWaterMark - stdout only', testAllProperties, {stderr: 'ignore'});125-test('subprocess.all has the right objectMode and highWaterMark - stderr only', testAllProperties, {stdout: 'ignore'});126-127-const testAllIgnore = async (t, streamName, otherStreamName) => {128- const subprocess = execa('noop-both.js', {[otherStreamName]: 'ignore', all: true});129- t.is(subprocess[otherStreamName], null);130- t.not(subprocess[streamName], null);131- t.not(subprocess.all, null);132- t.is(subprocess.all.readableObjectMode, subprocess[streamName].readableObjectMode);133- t.is(subprocess.all.readableHighWaterMark, subprocess[streamName].readableHighWaterMark);134-135- const result = await subprocess;136- t.is(result[otherStreamName], undefined);137- t.is(result[streamName], foobarString);138- t.is(result.all, foobarString);139-};140-141-test('can use all: true with stdout: ignore', testAllIgnore, 'stderr', 'stdout');142-test('can use all: true with stderr: ignore', testAllIgnore, 'stdout', 'stderr');143-144-const testAllIgnoreSync = (t, streamName, otherStreamName) => {145- const result = execaSync('noop-both.js', {[otherStreamName]: 'ignore', all: true});146- t.is(result[otherStreamName], undefined);147- t.is(result[streamName], foobarString);148- t.is(result.all, foobarString);149-};150-151-test('can use all: true with stdout: ignore, sync', testAllIgnoreSync, 'stderr', 'stdout');152-test('can use all: true with stderr: ignore, sync', testAllIgnoreSync, 'stdout', 'stderr');153-154-test('can use all: true with stdout: ignore + stderr: ignore', async t => {155- const subprocess = execa('noop-both.js', {stdout: 'ignore', stderr: 'ignore', all: true});156- t.is(subprocess.stdout, null);157- t.is(subprocess.stderr, null);158- t.is(subprocess.all, undefined);159-160- const {stdout, stderr, all} = await subprocess;161- t.is(stdout, undefined);162- t.is(stderr, undefined);163- t.is(all, undefined);164-});165-166-test('can use all: true with stdout: ignore + stderr: ignore, sync', t => {167- const {stdout, stderr, all} = execaSync('noop-both.js', {stdout: 'ignore', stderr: 'ignore', all: true});168- t.is(stdout, undefined);169- t.is(stderr, undefined);170- t.is(all, undefined);171-});deleted:test/stream/buffer-end.js-78 removed
1-import {once} from 'node:events';2-import {setTimeout} from 'node:timers/promises';3-import test from 'ava';4-import {execa} from '../../index.js';5-import {setFixtureDir} from '../helpers/fixtures-dir.js';6-import {fullStdio, getStdio} from '../helpers/stdio.js';7-8-setFixtureDir();9-10-const testBufferIgnore = async (t, fdNumber, all) => {11- await t.notThrowsAsync(execa('max-buffer.js', [`${fdNumber}`], {...getStdio(fdNumber, 'ignore'), buffer: false, all}));12-};13-14-test('Subprocess buffers stdout, which does not prevent exit if ignored', testBufferIgnore, 1, false);15-test('Subprocess buffers stderr, which does not prevent exit if ignored', testBufferIgnore, 2, false);16-test('Subprocess buffers all, which does not prevent exit if ignored', testBufferIgnore, 1, true);17-18-const testBufferNotRead = async (t, fdNumber, all) => {19- const subprocess = execa('max-buffer.js', [`${fdNumber}`], {...fullStdio, buffer: false, all});20- await t.notThrowsAsync(subprocess);21-};22-23-test('Subprocess buffers stdout, which does not prevent exit if not read and buffer is false', testBufferNotRead, 1, false);24-test('Subprocess buffers stderr, which does not prevent exit if not read and buffer is false', testBufferNotRead, 2, false);25-test('Subprocess buffers stdio[*], which does not prevent exit if not read and buffer is false', testBufferNotRead, 3, false);26-test('Subprocess buffers all, which does not prevent exit if not read and buffer is false', testBufferNotRead, 1, true);27-28-const testBufferRead = async (t, fdNumber, all) => {29- const subprocess = execa('max-buffer.js', [`${fdNumber}`], {...fullStdio, buffer: false, all});30- const stream = all ? subprocess.all : subprocess.stdio[fdNumber];31- stream.resume();32- await t.notThrowsAsync(subprocess);33-};34-35-test('Subprocess buffers stdout, which does not prevent exit if read and buffer is false', testBufferRead, 1, false);36-test('Subprocess buffers stderr, which does not prevent exit if read and buffer is false', testBufferRead, 2, false);37-test('Subprocess buffers stdio[*], which does not prevent exit if read and buffer is false', testBufferRead, 3, false);38-test('Subprocess buffers all, which does not prevent exit if read and buffer is false', testBufferRead, 1, true);39-40-const testBufferExit = async (t, fdNumber, fixtureName, reject) => {41- const subprocess = execa(fixtureName, [`${fdNumber}`], {...fullStdio, reject});42- await setTimeout(100);43- const {stdio} = await subprocess;44- t.is(stdio[fdNumber], 'foobar');45-};46-47-test('Subprocess buffers stdout before it is read', testBufferExit, 1, 'noop-delay.js', true);48-test('Subprocess buffers stderr before it is read', testBufferExit, 2, 'noop-delay.js', true);49-test('Subprocess buffers stdio[*] before it is read', testBufferExit, 3, 'noop-delay.js', true);50-test('Subprocess buffers stdout right away, on successfully exit', testBufferExit, 1, 'noop-fd.js', true);51-test('Subprocess buffers stderr right away, on successfully exit', testBufferExit, 2, 'noop-fd.js', true);52-test('Subprocess buffers stdio[*] right away, on successfully exit', testBufferExit, 3, 'noop-fd.js', true);53-test('Subprocess buffers stdout right away, on failure', testBufferExit, 1, 'noop-fail.js', false);54-test('Subprocess buffers stderr right away, on failure', testBufferExit, 2, 'noop-fail.js', false);55-test('Subprocess buffers stdio[*] right away, on failure', testBufferExit, 3, 'noop-fail.js', false);56-57-const testBufferDirect = async (t, fdNumber) => {58- const subprocess = execa('noop-fd.js', [`${fdNumber}`], fullStdio);59- const data = await once(subprocess.stdio[fdNumber], 'data');60- t.is(data.toString().trim(), 'foobar');61- const result = await subprocess;62- t.is(result.stdio[fdNumber], 'foobar');63-};64-65-test('Subprocess buffers stdout right away, even if directly read', testBufferDirect, 1);66-test('Subprocess buffers stderr right away, even if directly read', testBufferDirect, 2);67-test('Subprocess buffers stdio[*] right away, even if directly read', testBufferDirect, 3);68-69-const testBufferDestroyOnEnd = async (t, fdNumber) => {70- const subprocess = execa('noop-fd.js', [`${fdNumber}`], fullStdio);71- const result = await subprocess;72- t.is(result.stdio[fdNumber], 'foobar');73- t.true(subprocess.stdio[fdNumber].destroyed);74-};75-76-test('subprocess.stdout must be read right away', testBufferDestroyOnEnd, 1);77-test('subprocess.stderr must be read right away', testBufferDestroyOnEnd, 2);78-test('subprocess.stdio[*] must be read right away', testBufferDestroyOnEnd, 3);deleted:test/stream/exit.js-85 removed
1-import process from 'node:process';2-import test from 'ava';3-import {execa} from '../../index.js';4-import {setFixtureDir} from '../helpers/fixtures-dir.js';5-6-const isWindows = process.platform === 'win32';7-8-setFixtureDir();9-10-test('exitCode is 0 on success', async t => {11- const {exitCode} = await execa('noop.js', ['foo']);12- t.is(exitCode, 0);13-});14-15-const testExitCode = async (t, expectedExitCode) => {16- const {exitCode, originalMessage, shortMessage, message} = await t.throwsAsync(17- execa('exit.js', [`${expectedExitCode}`]),18- );19- t.is(exitCode, expectedExitCode);20- t.is(originalMessage, '');21- t.is(shortMessage, `Command failed with exit code ${expectedExitCode}: exit.js ${expectedExitCode}`);22- t.is(message, shortMessage);23-};24-25-test('exitCode is 2', testExitCode, 2);26-test('exitCode is 3', testExitCode, 3);27-test('exitCode is 4', testExitCode, 4);28-29-if (!isWindows) {30- test('error.signal is SIGINT', async t => {31- const subprocess = execa('forever.js');32-33- process.kill(subprocess.pid, 'SIGINT');34-35- const {signal} = await t.throwsAsync(subprocess, {message: /was killed with SIGINT/});36- t.is(signal, 'SIGINT');37- });38-39- test('error.signalDescription is defined', async t => {40- const subprocess = execa('forever.js');41-42- process.kill(subprocess.pid, 'SIGINT');43-44- const {signalDescription} = await t.throwsAsync(subprocess, {message: /User interruption with CTRL-C/});45- t.is(signalDescription, 'User interruption with CTRL-C');46- });47-48- test('error.signal is SIGTERM', async t => {49- const subprocess = execa('forever.js');50-51- process.kill(subprocess.pid, 'SIGTERM');52-53- const {signal} = await t.throwsAsync(subprocess, {message: /was killed with SIGTERM/});54- t.is(signal, 'SIGTERM');55- });56-57- test('error.signal uses killSignal', async t => {58- const {signal} = await t.throwsAsync(execa('forever.js', {killSignal: 'SIGINT', timeout: 1, message: /timed out after/}));59- t.is(signal, 'SIGINT');60- });61-62- test('exitCode is undefined on signal termination', async t => {63- const subprocess = execa('forever.js');64-65- process.kill(subprocess.pid);66-67- const {exitCode} = await t.throwsAsync(subprocess);68- t.is(exitCode, undefined);69- });70-}71-72-test('result.signal is undefined for successful execution', async t => {73- const {signal} = await execa('noop.js');74- t.is(signal, undefined);75-});76-77-test('result.signal is undefined if subprocess failed, but was not killed', async t => {78- const {signal} = await t.throwsAsync(execa('fail.js'));79- t.is(signal, undefined);80-});81-82-test('result.signalDescription is undefined for successful execution', async t => {83- const {signalDescription} = await execa('noop.js');84- t.is(signalDescription, undefined);85-});deleted:test/stream/max-buffer.js-265 removed
1-import {Buffer} from 'node:buffer';2-import test from 'ava';3-import getStream from 'get-stream';4-import {execa, execaSync} from '../../index.js';5-import {setFixtureDir} from '../helpers/fixtures-dir.js';6-import {fullStdio} from '../helpers/stdio.js';7-import {getEarlyErrorSubprocess, getEarlyErrorSubprocessSync} from '../helpers/early-error.js';8-import {maxBuffer, assertErrorMessage} from '../helpers/max-buffer.js';9-10-setFixtureDir();11-12-const maxBufferMessage = {message: /maxBuffer exceeded/};13-const maxBufferCodeSync = {code: 'ENOBUFS'};14-15-const runMaxBuffer = async (t, execaMethod, fdNumber, options) => {16- const error = execaMethod === execa17- ? await t.throwsAsync(getMaxBufferSubprocess(execaMethod, fdNumber, options), maxBufferMessage)18- : t.throws(() => {19- getMaxBufferSubprocess(execaMethod, fdNumber, options);20- }, maxBufferCodeSync);21- t.true(error.isMaxBuffer);22- t.is(error.maxBufferInfo, undefined);23- return error;24-};25-26-const getMaxBufferSubprocess = (execaMethod, fdNumber, {length = maxBuffer, ...options} = {}) =>27- execaMethod('max-buffer.js', [`${fdNumber}`, `${length + 1}`], {...fullStdio, maxBuffer, ...options});28-29-const getExpectedOutput = (length = maxBuffer) => '.'.repeat(length);30-31-const testMaxBufferSuccess = async (t, execaMethod, fdNumber, all) => {32- const {isMaxBuffer} = await getMaxBufferSubprocess(execaMethod, fdNumber, {all, length: maxBuffer - 1});33- t.false(isMaxBuffer);34-};35-36-test('maxBuffer does not affect stdout if too high', testMaxBufferSuccess, execa, 1, false);37-test('maxBuffer does not affect stderr if too high', testMaxBufferSuccess, execa, 2, false);38-test('maxBuffer does not affect stdio[*] if too high', testMaxBufferSuccess, execa, 3, false);39-test('maxBuffer does not affect all if too high', testMaxBufferSuccess, execa, 1, true);40-test('maxBuffer does not affect stdout if too high, sync', testMaxBufferSuccess, execaSync, 1, false);41-test('maxBuffer does not affect stderr if too high, sync', testMaxBufferSuccess, execaSync, 2, false);42-test('maxBuffer does not affect stdio[*] if too high, sync', testMaxBufferSuccess, execaSync, 3, false);43-test('maxBuffer does not affect all if too high, sync', testMaxBufferSuccess, execaSync, 1, true);44-45-const testGracefulExit = async (t, fixtureName, expectedExitCode) => {46- const {isMaxBuffer, shortMessage, exitCode, signal, stdout} = await t.throwsAsync(47- execa(fixtureName, ['1', '.'.repeat(maxBuffer + 1)], {maxBuffer}),48- maxBufferMessage,49- );50- t.true(isMaxBuffer);51- assertErrorMessage(t, shortMessage);52- t.is(exitCode, expectedExitCode);53- t.is(signal, undefined);54- t.is(stdout, getExpectedOutput());55-};56-57-test('maxBuffer terminates stream gracefully, more writes', testGracefulExit, 'noop-repeat.js', 1);58-test('maxBuffer terminates stream gracefully, no more writes', testGracefulExit, 'noop-fd.js', 0);59-60-const testGracefulExitSync = (t, fixtureName) => {61- const {isMaxBuffer, shortMessage, exitCode, signal, stdout} = t.throws(() => {62- execaSync(fixtureName, ['1', '.'.repeat(maxBuffer + 1)], {maxBuffer, killSignal: 'SIGINT'});63- }, maxBufferCodeSync);64- t.true(isMaxBuffer);65- assertErrorMessage(t, shortMessage, {execaMethod: execaSync});66- t.is(exitCode, undefined);67- t.is(signal, 'SIGINT');68- t.is(stdout, getExpectedOutput());69-};70-71-test('maxBuffer terminate stream with killSignal, more writes, sync', testGracefulExitSync, 'noop-repeat.js');72-test('maxBuffer terminate stream with killSignal, no more writes, sync', testGracefulExitSync, 'noop-fd.js');73-74-const testMaxBufferLimit = async (t, execaMethod, fdNumber, all) => {75- const length = all && execaMethod === execa ? maxBuffer * 2 : maxBuffer;76- const {shortMessage, all: allOutput, stdio} = await runMaxBuffer(t, execaMethod, fdNumber, {all, length});77- assertErrorMessage(t, shortMessage, {execaMethod, fdNumber});78- t.is(all ? allOutput : stdio[fdNumber], getExpectedOutput(length));79-};80-81-test('maxBuffer truncates stdout', testMaxBufferLimit, execa, 1, false);82-test('maxBuffer truncates stderr', testMaxBufferLimit, execa, 2, false);83-test('maxBuffer truncates stdio[*]', testMaxBufferLimit, execa, 3, false);84-test('maxBuffer truncates all', testMaxBufferLimit, execa, 1, true);85-test('maxBuffer truncates stdout, sync', testMaxBufferLimit, execaSync, 1, false);86-test('maxBuffer truncates stderr, sync', testMaxBufferLimit, execaSync, 2, false);87-test('maxBuffer truncates stdio[*], sync', testMaxBufferLimit, execaSync, 3, false);88-test('maxBuffer truncates all, sync', testMaxBufferLimit, execaSync, 1, true);89-90-const MAX_BUFFER_DEFAULT = 1e8;91-92-const testMaxBufferDefault = async (t, execaMethod, fdNumber, maxBuffer) => {93- const length = MAX_BUFFER_DEFAULT;94- const {shortMessage, stdio} = await runMaxBuffer(t, execaMethod, fdNumber, {length: MAX_BUFFER_DEFAULT + 1, maxBuffer});95- assertErrorMessage(t, shortMessage, {execaMethod, fdNumber, length});96- t.is(stdio[fdNumber], getExpectedOutput(length));97-};98-99-test('maxBuffer has a default value with stdout', testMaxBufferDefault, execa, 1, undefined);100-test('maxBuffer has a default value with stderr', testMaxBufferDefault, execa, 2, undefined);101-test('maxBuffer has a default value with stdio[*]', testMaxBufferDefault, execa, 3, undefined);102-test('maxBuffer has a default value with stdout, sync', testMaxBufferDefault, execaSync, 1, undefined);103-test('maxBuffer has a default value with stderr, sync', testMaxBufferDefault, execaSync, 2, undefined);104-test('maxBuffer has a default value with stdio[*], sync', testMaxBufferDefault, execaSync, 3, undefined);105-test('maxBuffer has a default value with stdout with fd-specific options', testMaxBufferDefault, execa, 1, {stderr: 1e9});106-test('maxBuffer has a default value with stderr with fd-specific options', testMaxBufferDefault, execa, 2, {stdout: 1e9});107-test('maxBuffer has a default value with stdio[*] with fd-specific options', testMaxBufferDefault, execa, 3, {stdout: 1e9});108-test('maxBuffer has a default value with stdout with empty fd-specific options', testMaxBufferDefault, execa, 1, {});109-110-const testFdSpecific = async (t, fdNumber, fdName, execaMethod) => {111- const length = 1;112- const {shortMessage, stdio} = await runMaxBuffer(t, execaMethod, fdNumber, {maxBuffer: {[fdName]: length}});113- assertErrorMessage(t, shortMessage, {execaMethod, fdNumber, length});114- t.is(stdio[fdNumber], getExpectedOutput(length));115-};116-117-test('maxBuffer truncates file descriptors with fd-specific options, stdout', testFdSpecific, 1, 'stdout', execa);118-test('maxBuffer truncates file descriptors with fd-specific options, fd1', testFdSpecific, 1, 'fd1', execa);119-test('maxBuffer truncates file descriptors with fd-specific options, stderr', testFdSpecific, 2, 'stderr', execa);120-test('maxBuffer truncates file descriptors with fd-specific options, fd2', testFdSpecific, 2, 'fd2', execa);121-test('maxBuffer truncates file descriptors with fd-specific options, stdout, all', testFdSpecific, 1, 'all', execa);122-test('maxBuffer truncates file descriptors with fd-specific options, stderr, all', testFdSpecific, 2, 'all', execa);123-test('maxBuffer truncates file descriptors with fd-specific options, fd3', testFdSpecific, 3, 'fd3', execa);124-test('maxBuffer.stdout is used for stdout with fd-specific options, stdout, sync', testFdSpecific, 1, 'stdout', execaSync);125-126-test('maxBuffer does not affect other file descriptors with fd-specific options', async t => {127- const {isMaxBuffer} = await getMaxBufferSubprocess(execa, 2, {maxBuffer: {stdout: 1}});128- t.false(isMaxBuffer);129-});130-131-test('maxBuffer.stdout is used for other file descriptors with fd-specific options, sync', async t => {132- const length = 1;133- const {shortMessage, stderr} = await runMaxBuffer(t, execaSync, 2, {maxBuffer: {stdout: length}});134- assertErrorMessage(t, shortMessage, {execaMethod: execaSync, fdNumber: 2, length});135- t.is(stderr, getExpectedOutput(length));136-});137-138-const testAll = async (t, shouldFail) => {139- const difference = shouldFail ? 0 : 1;140- const maxBufferStdout = 2;141- const maxBufferStderr = 4 - difference;142- const {isMaxBuffer, shortMessage, stdout, stderr, all} = await execa(143- 'noop-both.js',144- ['\n'.repeat(maxBufferStdout - 1), '\n'.repeat(maxBufferStderr - difference)],145- {maxBuffer: {stdout: maxBufferStdout, stderr: maxBufferStderr}, all: true, stripFinalNewline: false, reject: false},146- );147- t.is(isMaxBuffer, shouldFail);148- if (shouldFail) {149- assertErrorMessage(t, shortMessage, {fdNumber: 2, length: maxBufferStderr});150- }151-152- t.is(stdout, '\n'.repeat(maxBufferStdout));153- t.is(stderr, '\n'.repeat(maxBufferStderr));154- t.is(all, '\n'.repeat(maxBufferStdout + maxBufferStderr));155-};156-157-test('maxBuffer.stdout can differ from maxBuffer.stderr, combined with all, below threshold', testAll, false);158-test('maxBuffer.stdout can differ from maxBuffer.stderr, combined with all, above threshold', testAll, true);159-160-const testInvalidFd = async (t, fdName, execaMethod) => {161- const {message} = t.throws(() => {162- execaMethod('empty.js', {maxBuffer: {[fdName]: 0}});163- });164- t.true(message.includes(`"maxBuffer.${fdName}" is invalid`));165-};166-167-test('maxBuffer.stdin is invalid', testInvalidFd, 'stdin', execa);168-test('maxBuffer.fd0 is invalid', testInvalidFd, 'fd0', execa);169-test('maxBuffer.other is invalid', testInvalidFd, 'other', execa);170-test('maxBuffer.fd10 is invalid', testInvalidFd, 'fd10', execa);171-test('maxBuffer.stdin is invalid, sync', testInvalidFd, 'stdin', execaSync);172-test('maxBuffer.fd0 is invalid, sync', testInvalidFd, 'fd0', execaSync);173-test('maxBuffer.other is invalid, sync', testInvalidFd, 'other', execaSync);174-test('maxBuffer.fd10 is invalid, sync', testInvalidFd, 'fd10', execaSync);175-176-const testMaxBufferEncoding = async (t, execaMethod, fdNumber) => {177- const {shortMessage, stdio} = await runMaxBuffer(t, execaMethod, fdNumber, {encoding: 'buffer'});178- assertErrorMessage(t, shortMessage, {execaMethod, fdNumber, unit: 'bytes'});179- const stream = stdio[fdNumber];180- t.true(stream instanceof Uint8Array);181- t.is(Buffer.from(stream).toString(), getExpectedOutput());182-};183-184-test('maxBuffer works with encoding buffer and stdout', testMaxBufferEncoding, execa, 1);185-test('maxBuffer works with encoding buffer and stderr', testMaxBufferEncoding, execa, 2);186-test('maxBuffer works with encoding buffer and stdio[*]', testMaxBufferEncoding, execa, 3);187-test('maxBuffer works with encoding buffer and stdout, sync', testMaxBufferEncoding, execaSync, 1);188-test('maxBuffer works with encoding buffer and stderr, sync', testMaxBufferEncoding, execaSync, 2);189-test('maxBuffer works with encoding buffer and stdio[*], sync', testMaxBufferEncoding, execaSync, 3);190-191-const testMaxBufferHex = async (t, fdNumber) => {192- const length = maxBuffer / 2;193- const {shortMessage, stdio} = await runMaxBuffer(t, execa, fdNumber, {length, encoding: 'hex'});194- assertErrorMessage(t, shortMessage, {fdNumber});195- t.is(stdio[fdNumber], Buffer.from(getExpectedOutput(length)).toString('hex'));196-};197-198-test('maxBuffer works with other encodings and stdout', testMaxBufferHex, 1);199-test('maxBuffer works with other encodings and stderr', testMaxBufferHex, 2);200-test('maxBuffer works with other encodings and stdio[*]', testMaxBufferHex, 3);201-202-const testMaxBufferHexSync = async (t, fdNumber) => {203- const length = maxBuffer / 2;204- const {isMaxBuffer, stdio} = await getMaxBufferSubprocess(execaSync, fdNumber, {length, encoding: 'hex'});205- t.false(isMaxBuffer);206- t.is(stdio[fdNumber], Buffer.from(getExpectedOutput(length + 1)).toString('hex'));207-};208-209-test('maxBuffer ignores other encodings and stdout, sync', testMaxBufferHexSync, 1);210-test('maxBuffer ignores other encodings and stderr, sync', testMaxBufferHexSync, 2);211-test('maxBuffer ignores other encodings and stdio[*], sync', testMaxBufferHexSync, 3);212-213-const testNoMaxBuffer = async (t, fdNumber, buffer) => {214- const subprocess = getMaxBufferSubprocess(execa, fdNumber, {buffer});215- const [{isMaxBuffer, stdio}, output] = await Promise.all([216- subprocess,217- getStream(subprocess.stdio[fdNumber]),218- ]);219- t.false(isMaxBuffer);220- t.is(stdio[fdNumber], undefined);221- t.is(output, getExpectedOutput(maxBuffer + 1));222-};223-224-test('do not buffer stdout when `buffer` set to `false`', testNoMaxBuffer, 1, false);225-test('do not buffer stdout when `buffer` set to `false`, fd-specific', testNoMaxBuffer, 1, {stdout: false});226-test('do not buffer stderr when `buffer` set to `false`', testNoMaxBuffer, 2, false);227-test('do not buffer stderr when `buffer` set to `false`, fd-specific', testNoMaxBuffer, 2, {stderr: false});228-test('do not buffer stdio[*] when `buffer` set to `false`', testNoMaxBuffer, 3, false);229-test('do not buffer stdio[*] when `buffer` set to `false`, fd-specific', testNoMaxBuffer, 3, {fd3: false});230-231-const testNoMaxBufferSync = (t, fdNumber, buffer) => {232- const {isMaxBuffer, stdio} = getMaxBufferSubprocess(execaSync, fdNumber, {buffer});233- t.false(isMaxBuffer);234- t.is(stdio[fdNumber], undefined);235-};236-237-// @todo: add tests for fd3 once the following Node.js bug is fixed.238-// https://github.com/nodejs/node/issues/52422239-test('do not buffer stdout when `buffer` set to `false`, sync', testNoMaxBufferSync, 1, false);240-test('do not buffer stdout when `buffer` set to `false`, fd-specific, sync', testNoMaxBufferSync, 1, {stdout: false});241-test('do not buffer stderr when `buffer` set to `false`, sync', testNoMaxBufferSync, 2, false);242-test('do not buffer stderr when `buffer` set to `false`, fd-specific, sync', testNoMaxBufferSync, 2, {stderr: false});243-244-const testMaxBufferAbort = async (t, fdNumber) => {245- const subprocess = getMaxBufferSubprocess(execa, fdNumber);246- const [{isMaxBuffer, shortMessage}] = await Promise.all([247- t.throwsAsync(subprocess, maxBufferMessage),248- t.throwsAsync(getStream(subprocess.stdio[fdNumber]), {code: 'ERR_STREAM_PREMATURE_CLOSE'}),249- ]);250- t.true(isMaxBuffer);251- assertErrorMessage(t, shortMessage, {execaMethod: execa, fdNumber});252-};253-254-test('abort stream when hitting maxBuffer with stdout', testMaxBufferAbort, 1);255-test('abort stream when hitting maxBuffer with stderr', testMaxBufferAbort, 2);256-test('abort stream when hitting maxBuffer with stdio[*]', testMaxBufferAbort, 3);257-258-const testEarlyError = async (t, getSubprocess) => {259- const {failed, isMaxBuffer} = await getSubprocess({reject: false, maxBuffer: 1});260- t.true(failed);261- t.false(isMaxBuffer);262-};263-264-test('error.isMaxBuffer is false on early errors', testEarlyError, getEarlyErrorSubprocess);265-test('error.isMaxBuffer is false on early errors, sync', testEarlyError, getEarlyErrorSubprocessSync);deleted:test/stream/no-buffer.js-192 removed
1-import {once} from 'node:events';2-import test from 'ava';3-import getStream from 'get-stream';4-import {execa, execaSync} from '../../index.js';5-import {setFixtureDir} from '../helpers/fixtures-dir.js';6-import {fullStdio, getStdio} from '../helpers/stdio.js';7-import {foobarString, foobarUppercase, foobarUppercaseUint8Array} from '../helpers/input.js';8-import {resultGenerator, uppercaseGenerator, uppercaseBufferGenerator} from '../helpers/generator.js';9-10-setFixtureDir();11-12-const testLateStream = async (t, fdNumber, all) => {13- const subprocess = execa('noop-fd-ipc.js', [`${fdNumber}`, foobarString], {...getStdio(4, 'ipc', 4), buffer: false, all});14- await once(subprocess, 'message');15- const [output, allOutput] = await Promise.all([16- getStream(subprocess.stdio[fdNumber]),17- all ? getStream(subprocess.all) : undefined,18- subprocess,19- ]);20-21- t.is(output, '');22-23- if (all) {24- t.is(allOutput, '');25- }26-};27-28-test('Lacks some data when stdout is read too late `buffer` set to `false`', testLateStream, 1, false);29-test('Lacks some data when stderr is read too late `buffer` set to `false`', testLateStream, 2, false);30-test('Lacks some data when stdio[*] is read too late `buffer` set to `false`', testLateStream, 3, false);31-test('Lacks some data when all is read too late `buffer` set to `false`', testLateStream, 1, true);32-33-const getFirstDataEvent = async stream => {34- const [output] = await once(stream, 'data');35- return output.toString();36-};37-38-// eslint-disable-next-line max-params39-const testIterationBuffer = async (t, fdNumber, buffer, useDataEvents, all) => {40- const subprocess = execa('noop-fd.js', [`${fdNumber}`, foobarString], {...fullStdio, buffer, all});41- const getOutput = useDataEvents ? getFirstDataEvent : getStream;42- const [result, output, allOutput] = await Promise.all([43- subprocess,44- getOutput(subprocess.stdio[fdNumber]),45- all ? getOutput(subprocess.all) : undefined,46- ]);47-48- const expectedResult = buffer ? foobarString : undefined;49-50- t.is(result.stdio[fdNumber], expectedResult);51- t.is(output, foobarString);52-53- if (all) {54- t.is(result.all, expectedResult);55- t.is(allOutput, foobarString);56- }57-};58-59-test('Can iterate stdout when `buffer` set to `false`', testIterationBuffer, 1, false, false, false);60-test('Can iterate stderr when `buffer` set to `false`', testIterationBuffer, 2, false, false, false);61-test('Can iterate stdio[*] when `buffer` set to `false`', testIterationBuffer, 3, false, false, false);62-test('Can iterate all when `buffer` set to `false`', testIterationBuffer, 1, false, false, true);63-test('Can iterate stdout when `buffer` set to `true`', testIterationBuffer, 1, true, false, false);64-test('Can iterate stderr when `buffer` set to `true`', testIterationBuffer, 2, true, false, false);65-test('Can iterate stdio[*] when `buffer` set to `true`', testIterationBuffer, 3, true, false, false);66-test('Can iterate all when `buffer` set to `true`', testIterationBuffer, 1, true, false, true);67-test('Can listen to `data` events on stdout when `buffer` set to `false`', testIterationBuffer, 1, false, true, false);68-test('Can listen to `data` events on stderr when `buffer` set to `false`', testIterationBuffer, 2, false, true, false);69-test('Can listen to `data` events on stdio[*] when `buffer` set to `false`', testIterationBuffer, 3, false, true, false);70-test('Can listen to `data` events on all when `buffer` set to `false`', testIterationBuffer, 1, false, true, true);71-test('Can listen to `data` events on stdout when `buffer` set to `true`', testIterationBuffer, 1, true, true, false);72-test('Can listen to `data` events on stderr when `buffer` set to `true`', testIterationBuffer, 2, true, true, false);73-test('Can listen to `data` events on stdio[*] when `buffer` set to `true`', testIterationBuffer, 3, true, true, false);74-test('Can listen to `data` events on all when `buffer` set to `true`', testIterationBuffer, 1, true, true, true);75-76-const testNoBufferStreamError = async (t, fdNumber, all) => {77- const subprocess = execa('noop-fd.js', [`${fdNumber}`], {...fullStdio, buffer: false, all});78- const stream = all ? subprocess.all : subprocess.stdio[fdNumber];79- const cause = new Error('test');80- stream.destroy(cause);81- t.like(await t.throwsAsync(subprocess), {cause});82-};83-84-test('Listen to stdout errors even when `buffer` is `false`', testNoBufferStreamError, 1, false);85-test('Listen to stderr errors even when `buffer` is `false`', testNoBufferStreamError, 2, false);86-test('Listen to stdio[*] errors even when `buffer` is `false`', testNoBufferStreamError, 3, false);87-test('Listen to all errors even when `buffer` is `false`', testNoBufferStreamError, 1, true);88-89-const testOutput = async (t, buffer, execaMethod) => {90- const {stdout} = await execaMethod('noop-fd.js', ['1', foobarString], {buffer});91- t.is(stdout, foobarString);92-};93-94-test('buffer: true returns output', testOutput, true, execa);95-test('buffer: true returns output, fd-specific', testOutput, {stderr: false}, execa);96-test('buffer: default returns output', testOutput, undefined, execa);97-test('buffer: default returns output, fd-specific', testOutput, {}, execa);98-99-const testNoOutput = async (t, stdioOption, buffer, execaMethod) => {100- const {stdout} = await execaMethod('noop.js', {stdout: stdioOption, buffer});101- t.is(stdout, undefined);102-};103-104-test('buffer: false does not return output', testNoOutput, 'pipe', false, execa);105-test('buffer: false does not return output, fd-specific', testNoOutput, 'pipe', {stdout: false}, execa);106-test('buffer: false does not return output, stdout undefined', testNoOutput, undefined, false, execa);107-test('buffer: false does not return output, stdout null', testNoOutput, null, false, execa);108-test('buffer: false does not return output, stdout ["pipe"]', testNoOutput, ['pipe'], false, execa);109-test('buffer: false does not return output, stdout [undefined]', testNoOutput, [undefined], false, execa);110-test('buffer: false does not return output, stdout [null]', testNoOutput, [null], false, execa);111-test('buffer: false does not return output, stdout ["pipe", undefined]', testNoOutput, ['pipe', undefined], false, execa);112-test('buffer: false does not return output, sync', testNoOutput, 'pipe', false, execaSync);113-test('buffer: false does not return output, fd-specific, sync', testNoOutput, 'pipe', {stdout: false}, execaSync);114-test('buffer: false does not return output, stdout undefined, sync', testNoOutput, undefined, false, execaSync);115-test('buffer: false does not return output, stdout null, sync', testNoOutput, null, false, execaSync);116-test('buffer: false does not return output, stdout ["pipe"], sync', testNoOutput, ['pipe'], false, execaSync);117-test('buffer: false does not return output, stdout [undefined], sync', testNoOutput, [undefined], false, execaSync);118-test('buffer: false does not return output, stdout [null], sync', testNoOutput, [null], false, execaSync);119-test('buffer: false does not return output, stdout ["pipe", undefined], sync', testNoOutput, ['pipe', undefined], false, execaSync);120-121-const testNoOutputFail = async (t, execaMethod) => {122- const {exitCode, stdout} = await execaMethod('fail.js', {buffer: false, reject: false});123- t.is(exitCode, 2);124- t.is(stdout, undefined);125-};126-127-test('buffer: false does not return output, failure', testNoOutputFail, execa);128-test('buffer: false does not return output, failure, sync', testNoOutputFail, execaSync);129-130-// eslint-disable-next-line max-params131-const testNoOutputAll = async (t, buffer, bufferStdout, bufferStderr, execaMethod) => {132- const {stdout, stderr, all} = await execaMethod('noop-both.js', {all: true, buffer, stripFinalNewline: false});133- t.is(stdout, bufferStdout ? `${foobarString}\n` : undefined);134- t.is(stderr, bufferStderr ? `${foobarString}\n` : undefined);135- const stdoutStderr = [stdout, stderr].filter(Boolean);136- t.is(all, stdoutStderr.length === 0 ? undefined : stdoutStderr.join(''));137-};138-139-test('buffer: {}, all: true', testNoOutputAll, {}, true, true, execa);140-test('buffer: {stdout: false}, all: true', testNoOutputAll, {stdout: false}, false, true, execa);141-test('buffer: {stderr: false}, all: true', testNoOutputAll, {stderr: false}, true, false, execa);142-test('buffer: {all: false}, all: true', testNoOutputAll, {all: false}, false, false, execa);143-test('buffer: {}, all: true, sync', testNoOutputAll, {}, true, true, execaSync);144-test('buffer: {stdout: false}, all: true, sync', testNoOutputAll, {stdout: false}, false, true, execaSync);145-test('buffer: {stderr: false}, all: true, sync', testNoOutputAll, {stderr: false}, true, false, execaSync);146-test('buffer: {all: false}, all: true, sync', testNoOutputAll, {all: false}, false, false, execaSync);147-148-const testTransform = async (t, objectMode, execaMethod) => {149- const lines = [];150- const {stdout} = await execaMethod('noop.js', {151- buffer: false,152- stdout: [uppercaseGenerator(objectMode), resultGenerator(lines)(objectMode)],153- });154- t.is(stdout, undefined);155- t.deepEqual(lines, [foobarUppercase]);156-};157-158-test('buffer: false still runs transforms', testTransform, false, execa);159-test('buffer: false still runs transforms, objectMode', testTransform, true, execa);160-test('buffer: false still runs transforms, sync', testTransform, false, execaSync);161-test('buffer: false still runs transforms, objectMode, sync', testTransform, true, execaSync);162-163-const testTransformBinary = async (t, objectMode, execaMethod) => {164- const lines = [];165- const {stdout} = await execaMethod('noop-fd.js', ['1', foobarString], {166- buffer: false,167- stdout: [uppercaseBufferGenerator(objectMode, true), resultGenerator(lines)(objectMode)],168- encoding: 'buffer',169- });170- t.is(stdout, undefined);171- t.deepEqual(lines, [foobarUppercaseUint8Array]);172-};173-174-test('buffer: false still runs transforms, encoding "buffer"', testTransformBinary, false, execa);175-test('buffer: false still runs transforms, encoding "buffer", objectMode', testTransformBinary, true, execa);176-test('buffer: false still runs transforms, encoding "buffer", sync', testTransformBinary, false, execaSync);177-test('buffer: false still runs transforms, encoding "buffer", objectMode, sync', testTransformBinary, true, execaSync);178-179-const testStreamEnd = async (t, fdNumber, buffer) => {180- const subprocess = execa('wrong command', {...fullStdio, buffer});181- await Promise.all([182- t.throwsAsync(subprocess, {message: /wrong command/}),183- once(subprocess.stdio[fdNumber], 'end'),184- ]);185-};186-187-test('buffer: false > emits end event on stdout when promise is rejected', testStreamEnd, 1, false);188-test('buffer: false > emits end event on stderr when promise is rejected', testStreamEnd, 2, false);189-test('buffer: false > emits end event on stdio[*] when promise is rejected', testStreamEnd, 3, false);190-test('buffer: true > emits end event on stdout when promise is rejected', testStreamEnd, 1, true);191-test('buffer: true > emits end event on stderr when promise is rejected', testStreamEnd, 2, true);192-test('buffer: true > emits end event on stdio[*] when promise is rejected', testStreamEnd, 3, true);deleted:test/stream/resolve.js-49 removed
1-import test from 'ava';2-import {execa, execaSync} from '../../index.js';3-import {setFixtureDir} from '../helpers/fixtures-dir.js';4-import {getStdio} from '../helpers/stdio.js';5-6-setFixtureDir();7-8-const testIgnore = async (t, fdNumber, execaMethod) => {9- const result = await execaMethod('noop.js', getStdio(fdNumber, 'ignore'));10- t.is(result.stdio[fdNumber], undefined);11-};12-13-test('stdout is undefined if ignored', testIgnore, 1, execa);14-test('stderr is undefined if ignored', testIgnore, 2, execa);15-test('stdio[*] is undefined if ignored', testIgnore, 3, execa);16-test('stdout is undefined if ignored - sync', testIgnore, 1, execaSync);17-test('stderr is undefined if ignored - sync', testIgnore, 2, execaSync);18-test('stdio[*] is undefined if ignored - sync', testIgnore, 3, execaSync);19-20-const testSubprocessEventsCleanup = async (t, fixtureName) => {21- const subprocess = execa(fixtureName, {reject: false});22- t.deepEqual(subprocess.eventNames().map(String).sort(), ['Symbol(error)', 'error', 'exit', 'spawn']);23- await subprocess;24- t.deepEqual(subprocess.eventNames(), []);25-};26-27-test('subprocess listeners are cleaned up on success', testSubprocessEventsCleanup, 'empty.js');28-test('subprocess listeners are cleaned up on failure', testSubprocessEventsCleanup, 'fail.js');29-30-test('Aborting stdout should not abort stderr nor all', async t => {31- const subprocess = execa('empty.js', {all: true});32-33- subprocess.stdout.destroy();34- t.false(subprocess.stdout.readable);35- t.true(subprocess.stderr.readable);36- t.true(subprocess.all.readable);37-38- await subprocess;39-40- t.false(subprocess.stdout.readableEnded);41- t.is(subprocess.stdout.errored, null);42- t.true(subprocess.stdout.destroyed);43- t.true(subprocess.stderr.readableEnded);44- t.is(subprocess.stderr.errored, null);45- t.true(subprocess.stderr.destroyed);46- t.true(subprocess.all.readableEnded);47- t.is(subprocess.all.errored, null);48- t.true(subprocess.all.destroyed);49-});deleted:test/stream/subprocess.js-117 removed
1-import {setTimeout} from 'node:timers/promises';2-import test from 'ava';3-import {execa} from '../../index.js';4-import {setFixtureDir} from '../helpers/fixtures-dir.js';5-import {fullStdio, getStdio, prematureClose, assertEpipe} from '../helpers/stdio.js';6-import {infiniteGenerator} from '../helpers/generator.js';7-8-setFixtureDir();9-10-const getStreamInputSubprocess = fdNumber => execa('stdin-fd.js', [`${fdNumber}`], fdNumber === 311- ? getStdio(3, [new Uint8Array(), infiniteGenerator()])12- : {});13-const getStreamOutputSubprocess = fdNumber => execa('noop-repeat.js', [`${fdNumber}`], fdNumber === 3 ? fullStdio : {});14-15-const assertStreamInputError = (t, {exitCode, signal, isTerminated, failed}) => {16- t.is(exitCode, 0);17- t.is(signal, undefined);18- t.false(isTerminated);19- t.true(failed);20-};21-22-const assertStreamOutputError = (t, fdNumber, {exitCode, signal, isTerminated, failed, stderr}) => {23- if (fdNumber !== 3) {24- t.is(exitCode, 1);25- }26-27- t.is(signal, undefined);28- t.false(isTerminated);29- t.true(failed);30-31- assertEpipe(t, stderr, fdNumber);32-};33-34-const testStreamInputAbort = async (t, fdNumber) => {35- const subprocess = getStreamInputSubprocess(fdNumber);36- subprocess.stdio[fdNumber].destroy();37- const error = await t.throwsAsync(subprocess, prematureClose);38- assertStreamInputError(t, error);39-};40-41-test('Aborting stdin should not make the subprocess exit', testStreamInputAbort, 0);42-test('Aborting input stdio[*] should not make the subprocess exit', testStreamInputAbort, 3);43-44-const testStreamOutputAbort = async (t, fdNumber) => {45- const subprocess = getStreamOutputSubprocess(fdNumber);46- subprocess.stdio[fdNumber].destroy();47- const error = await t.throwsAsync(subprocess);48- assertStreamOutputError(t, fdNumber, error);49-};50-51-test('Aborting stdout should not make the subprocess exit', testStreamOutputAbort, 1);52-test('Aborting stderr should not make the subprocess exit', testStreamOutputAbort, 2);53-test('Aborting output stdio[*] should not make the subprocess exit', testStreamOutputAbort, 3);54-55-const testStreamInputDestroy = async (t, fdNumber) => {56- const subprocess = getStreamInputSubprocess(fdNumber);57- const cause = new Error('test');58- subprocess.stdio[fdNumber].destroy(cause);59- const error = await t.throwsAsync(subprocess);60- t.is(error.cause, cause);61- assertStreamInputError(t, error);62-};63-64-test('Destroying stdin should not make the subprocess exit', testStreamInputDestroy, 0);65-test('Destroying input stdio[*] should not make the subprocess exit', testStreamInputDestroy, 3);66-67-const testStreamOutputDestroy = async (t, fdNumber) => {68- const subprocess = getStreamOutputSubprocess(fdNumber);69- const cause = new Error('test');70- subprocess.stdio[fdNumber].destroy(cause);71- const error = await t.throwsAsync(subprocess);72- t.is(error.cause, cause);73- assertStreamOutputError(t, fdNumber, error);74-};75-76-test('Destroying stdout should not make the subprocess exit', testStreamOutputDestroy, 1);77-test('Destroying stderr should not make the subprocess exit', testStreamOutputDestroy, 2);78-test('Destroying output stdio[*] should not make the subprocess exit', testStreamOutputDestroy, 3);79-80-const testStreamInputError = async (t, fdNumber) => {81- const subprocess = getStreamInputSubprocess(fdNumber);82- const cause = new Error('test');83- const stream = subprocess.stdio[fdNumber];84- stream.emit('error', cause);85- stream.end();86- const error = await t.throwsAsync(subprocess);87- t.is(error.cause, cause);88- assertStreamInputError(t, error);89-};90-91-test('Errors on stdin should not make the subprocess exit', testStreamInputError, 0);92-test('Errors on input stdio[*] should not make the subprocess exit', testStreamInputError, 3);93-94-const testStreamOutputError = async (t, fdNumber) => {95- const subprocess = getStreamOutputSubprocess(fdNumber);96- const cause = new Error('test');97- const stream = subprocess.stdio[fdNumber];98- stream.emit('error', cause);99- const error = await t.throwsAsync(subprocess);100- t.is(error.cause, cause);101- assertStreamOutputError(t, fdNumber, error);102-};103-104-test('Errors on stdout should make the subprocess exit', testStreamOutputError, 1);105-test('Errors on stderr should make the subprocess exit', testStreamOutputError, 2);106-test('Errors on output stdio[*] should make the subprocess exit', testStreamOutputError, 3);107-108-const testWaitOnStreamEnd = async (t, fdNumber) => {109- const subprocess = execa('stdin-fd.js', [`${fdNumber}`], fullStdio);110- await setTimeout(100);111- subprocess.stdio[fdNumber].end('foobar');112- const {stdout} = await subprocess;113- t.is(stdout, 'foobar');114-};115-116-test('Subprocess waits on stdin before exiting', testWaitOnStreamEnd, 0);117-test('Subprocess waits on stdio[*] before exiting', testWaitOnStreamEnd, 3);deleted:test/stream/wait-abort.js-99 removed
1-import {setImmediate} from 'node:timers/promises';2-import test from 'ava';3-import {execa} from '../../index.js';4-import {setFixtureDir} from '../helpers/fixtures-dir.js';5-import {prematureClose} from '../helpers/stdio.js';6-import {noopReadable, noopWritable, noopDuplex} from '../helpers/stream.js';7-import {endOptionStream, destroyOptionStream, destroySubprocessStream, getStreamStdio} from '../helpers/wait.js';8-9-setFixtureDir();10-11-const noop = () => {};12-13-// eslint-disable-next-line max-params14-const testStreamAbortWait = async (t, streamMethod, stream, fdNumber, useTransform) => {15- const subprocess = execa('noop-stdin-fd.js', [`${fdNumber}`], getStreamStdio(fdNumber, stream, useTransform));16- streamMethod({stream, subprocess, fdNumber});17- subprocess.stdin.end();18- await setImmediate();19- stream.destroy();20-21- const {stdout} = await subprocess;22- t.is(stdout, '');23- t.true(stream.destroyed);24-};25-26-test('Keeps running when stdin option is used and subprocess.stdin ends', testStreamAbortWait, noop, noopReadable(), 0, false);27-test('Keeps running when stdin option is used and subprocess.stdin Duplex ends', testStreamAbortWait, noop, noopDuplex(), 0, false);28-test('Keeps running when input stdio[*] option is used and input subprocess.stdio[*] ends', testStreamAbortWait, noop, noopReadable(), 3, false);29-test('Keeps running when stdin option is used and subprocess.stdin ends, with a transform', testStreamAbortWait, noop, noopReadable(), 0, true);30-test('Keeps running when stdin option is used and subprocess.stdin Duplex ends, with a transform', testStreamAbortWait, noop, noopDuplex(), 0, true);31-test('Keeps running when input stdio[*] option is used and input subprocess.stdio[*] ends, with a transform', testStreamAbortWait, noop, noopReadable(), 3, true);32-33-// eslint-disable-next-line max-params34-const testStreamAbortSuccess = async (t, streamMethod, stream, fdNumber, useTransform) => {35- const subprocess = execa('noop-stdin-fd.js', [`${fdNumber}`], getStreamStdio(fdNumber, stream, useTransform));36- streamMethod({stream, subprocess, fdNumber});37- subprocess.stdin.end();38-39- const {stdout} = await subprocess;40- t.is(stdout, '');41- t.true(stream.destroyed);42-};43-44-test('Passes when stdin option aborts', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 0, false);45-test('Passes when stdin option Duplex aborts', testStreamAbortSuccess, destroyOptionStream, noopDuplex(), 0, false);46-test('Passes when input stdio[*] option aborts', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 3, false);47-test('Passes when stdout option ends with no more writes', testStreamAbortSuccess, endOptionStream, noopWritable(), 1, false);48-test('Passes when stderr option ends with no more writes', testStreamAbortSuccess, endOptionStream, noopWritable(), 2, false);49-test('Passes when output stdio[*] option ends with no more writes', testStreamAbortSuccess, endOptionStream, noopWritable(), 3, false);50-test('Passes when subprocess.stdout aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 1, false);51-test('Passes when subprocess.stdout Duplex aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 1, false);52-test('Passes when subprocess.stderr aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 2, false);53-test('Passes when subprocess.stderr Duplex aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 2, false);54-test('Passes when output subprocess.stdio[*] aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 3, false);55-test('Passes when output subprocess.stdio[*] Duplex aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 3, false);56-test('Passes when stdin option aborts, with a transform', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 0, true);57-test('Passes when stdin option Duplex aborts, with a transform', testStreamAbortSuccess, destroyOptionStream, noopDuplex(), 0, true);58-test('Passes when input stdio[*] option aborts, with a transform', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 3, true);59-test('Passes when stdout option ends with no more writes, with a transform', testStreamAbortSuccess, endOptionStream, noopWritable(), 1, true);60-test('Passes when stderr option ends with no more writes, with a transform', testStreamAbortSuccess, endOptionStream, noopWritable(), 2, true);61-test('Passes when output stdio[*] option ends with no more writes, with a transform', testStreamAbortSuccess, endOptionStream, noopWritable(), 3, true);62-test('Passes when subprocess.stdout aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 1, true);63-test('Passes when subprocess.stdout Duplex aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 1, true);64-test('Passes when subprocess.stderr aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 2, true);65-test('Passes when subprocess.stderr Duplex aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 2, true);66-test('Passes when output subprocess.stdio[*] aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 3, true);67-test('Passes when output subprocess.stdio[*] Duplex aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 3, true);68-69-// eslint-disable-next-line max-params70-const testStreamAbortFail = async (t, streamMethod, stream, fdNumber, useTransform) => {71- const subprocess = execa('noop-stdin-fd.js', [`${fdNumber}`], getStreamStdio(fdNumber, stream, useTransform));72- streamMethod({stream, subprocess, fdNumber});73- if (fdNumber !== 0) {74- subprocess.stdin.end();75- }76-77- const error = await t.throwsAsync(subprocess);78- t.like(error, {...prematureClose, exitCode: 0});79- t.true(stream.destroyed);80-};81-82-test('Throws abort error when subprocess.stdin aborts', testStreamAbortFail, destroySubprocessStream, noopReadable(), 0, false);83-test('Throws abort error when subprocess.stdin Duplex aborts', testStreamAbortFail, destroySubprocessStream, noopDuplex(), 0, false);84-test('Throws abort error when input subprocess.stdio[*] aborts', testStreamAbortFail, destroySubprocessStream, noopReadable(), 3, false);85-test('Throws abort error when stdout option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopWritable(), 1, false);86-test('Throws abort error when stdout option Duplex aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopDuplex(), 1, false);87-test('Throws abort error when stderr option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopWritable(), 2, false);88-test('Throws abort error when stderr option Duplex aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopDuplex(), 2, false);89-test('Throws abort error when output stdio[*] option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopWritable(), 3, false);90-test('Throws abort error when output stdio[*] Duplex option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopDuplex(), 3, false);91-test('Throws abort error when subprocess.stdin aborts, with a transform', testStreamAbortFail, destroySubprocessStream, noopReadable(), 0, true);92-test('Throws abort error when subprocess.stdin Duplex aborts, with a transform', testStreamAbortFail, destroySubprocessStream, noopDuplex(), 0, true);93-test('Throws abort error when input subprocess.stdio[*] aborts, with a transform', testStreamAbortFail, destroySubprocessStream, noopReadable(), 3, true);94-test('Throws abort error when stdout option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopWritable(), 1, true);95-test('Throws abort error when stdout option Duplex aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopDuplex(), 1, true);96-test('Throws abort error when stderr option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopWritable(), 2, true);97-test('Throws abort error when stderr option Duplex aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopDuplex(), 2, true);98-test('Throws abort error when output stdio[*] option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopWritable(), 3, true);99-test('Throws abort error when output stdio[*] Duplex option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopDuplex(), 3, true);deleted:test/stream/wait-epipe.js-55 removed
1-import {setImmediate} from 'node:timers/promises';2-import test from 'ava';3-import {execa} from '../../index.js';4-import {setFixtureDir} from '../helpers/fixtures-dir.js';5-import {assertEpipe} from '../helpers/stdio.js';6-import {foobarString} from '../helpers/input.js';7-import {noopWritable, noopDuplex} from '../helpers/stream.js';8-import {endOptionStream, destroyOptionStream, destroySubprocessStream, getStreamStdio} from '../helpers/wait.js';9-10-setFixtureDir();11-12-// eslint-disable-next-line max-params13-const testStreamEpipeFail = async (t, streamMethod, stream, fdNumber, useTransform) => {14- const subprocess = execa('noop-stdin-fd.js', [`${fdNumber}`], getStreamStdio(fdNumber, stream, useTransform));15- streamMethod({stream, subprocess, fdNumber});16- await setImmediate();17- subprocess.stdin.end(foobarString);18-19- const {exitCode, stdio, stderr} = await t.throwsAsync(subprocess);20- t.is(exitCode, 1);21- t.is(stdio[fdNumber], '');22- t.true(stream.destroyed);23- assertEpipe(t, stderr, fdNumber);24-};25-26-test('Throws EPIPE when stdout option ends with more writes', testStreamEpipeFail, endOptionStream, noopWritable(), 1, false);27-test('Throws EPIPE when stdout option aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopWritable(), 1, false);28-test('Throws EPIPE when stdout option Duplex aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 1, false);29-test('Throws EPIPE when stderr option ends with more writes', testStreamEpipeFail, endOptionStream, noopWritable(), 2, false);30-test('Throws EPIPE when stderr option aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopWritable(), 2, false);31-test('Throws EPIPE when stderr option Duplex aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 2, false);32-test('Throws EPIPE when output stdio[*] option ends with more writes', testStreamEpipeFail, endOptionStream, noopWritable(), 3, false);33-test('Throws EPIPE when output stdio[*] option aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopWritable(), 3, false);34-test('Throws EPIPE when output stdio[*] option Duplex aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 3, false);35-test('Throws EPIPE when subprocess.stdout aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 1, false);36-test('Throws EPIPE when subprocess.stdout Duplex aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 1, false);37-test('Throws EPIPE when subprocess.stderr aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 2, false);38-test('Throws EPIPE when subprocess.stderr Duplex aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 2, false);39-test('Throws EPIPE when output subprocess.stdio[*] aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 3, false);40-test('Throws EPIPE when output subprocess.stdio[*] Duplex aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 3, false);41-test('Throws EPIPE when stdout option ends with more writes, with a transform', testStreamEpipeFail, endOptionStream, noopWritable(), 1, true);42-test('Throws EPIPE when stdout option aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopWritable(), 1, true);43-test('Throws EPIPE when stdout option Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 1, true);44-test('Throws EPIPE when stderr option ends with more writes, with a transform', testStreamEpipeFail, endOptionStream, noopWritable(), 2, true);45-test('Throws EPIPE when stderr option aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopWritable(), 2, true);46-test('Throws EPIPE when stderr option Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 2, true);47-test('Throws EPIPE when output stdio[*] option ends with more writes, with a transform', testStreamEpipeFail, endOptionStream, noopWritable(), 3, true);48-test('Throws EPIPE when output stdio[*] option aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopWritable(), 3, true);49-test('Throws EPIPE when output stdio[*] option Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 3, true);50-test('Throws EPIPE when subprocess.stdout aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 1, true);51-test('Throws EPIPE when subprocess.stdout Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 1, true);52-test('Throws EPIPE when subprocess.stderr aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 2, true);53-test('Throws EPIPE when subprocess.stderr Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 2, true);54-test('Throws EPIPE when output subprocess.stdio[*] aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 3, true);55-test('Throws EPIPE when output subprocess.stdio[*] Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 3, true);deleted:test/stream/wait-error.js-59 removed
1-import test from 'ava';2-import {execa} from '../../index.js';3-import {setFixtureDir} from '../helpers/fixtures-dir.js';4-import {noopReadable, noopWritable, noopDuplex} from '../helpers/stream.js';5-import {destroyOptionStream, destroySubprocessStream, getStreamStdio} from '../helpers/wait.js';6-7-setFixtureDir();8-9-// eslint-disable-next-line max-params10-const testStreamError = async (t, streamMethod, stream, fdNumber, useTransform) => {11- const subprocess = execa('empty.js', getStreamStdio(fdNumber, stream, useTransform));12- const cause = new Error('test');13- streamMethod({stream, subprocess, fdNumber, error: cause});14-15- const error = await t.throwsAsync(subprocess);16- t.is(error.cause, cause);17- t.is(error.exitCode, 0);18- t.is(error.signal, undefined);19- t.false(error.isTerminated);20- t.true(error.failed);21- t.true(stream.destroyed);22-};23-24-test('Throws stream error when stdin option errors', testStreamError, destroyOptionStream, noopReadable(), 0, false);25-test('Throws stream error when stdin option Duplex errors', testStreamError, destroyOptionStream, noopDuplex(), 0, false);26-test('Throws stream error when stdout option errors', testStreamError, destroyOptionStream, noopWritable(), 1, false);27-test('Throws stream error when stdout option Duplex errors', testStreamError, destroyOptionStream, noopDuplex(), 1, false);28-test('Throws stream error when stderr option errors', testStreamError, destroyOptionStream, noopWritable(), 2, false);29-test('Throws stream error when stderr option Duplex errors', testStreamError, destroyOptionStream, noopDuplex(), 2, false);30-test('Throws stream error when output stdio[*] option errors', testStreamError, destroyOptionStream, noopWritable(), 3, false);31-test('Throws stream error when output stdio[*] Duplex option errors', testStreamError, destroyOptionStream, noopDuplex(), 3, false);32-test('Throws stream error when input stdio[*] option errors', testStreamError, destroyOptionStream, noopReadable(), 3, false);33-test('Throws stream error when subprocess.stdin errors', testStreamError, destroySubprocessStream, noopReadable(), 0, false);34-test('Throws stream error when subprocess.stdin Duplex errors', testStreamError, destroySubprocessStream, noopDuplex(), 0, false);35-test('Throws stream error when subprocess.stdout errors', testStreamError, destroySubprocessStream, noopWritable(), 1, false);36-test('Throws stream error when subprocess.stdout Duplex errors', testStreamError, destroySubprocessStream, noopDuplex(), 1, false);37-test('Throws stream error when subprocess.stderr errors', testStreamError, destroySubprocessStream, noopWritable(), 2, false);38-test('Throws stream error when subprocess.stderr Duplex errors', testStreamError, destroySubprocessStream, noopDuplex(), 2, false);39-test('Throws stream error when output subprocess.stdio[*] errors', testStreamError, destroySubprocessStream, noopWritable(), 3, false);40-test('Throws stream error when output subprocess.stdio[*] Duplex errors', testStreamError, destroySubprocessStream, noopDuplex(), 3, false);41-test('Throws stream error when input subprocess.stdio[*] errors', testStreamError, destroySubprocessStream, noopReadable(), 3, false);42-test('Throws stream error when stdin option errors, with a transform', testStreamError, destroyOptionStream, noopReadable(), 0, true);43-test('Throws stream error when stdin option Duplex errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 0, true);44-test('Throws stream error when stdout option errors, with a transform', testStreamError, destroyOptionStream, noopWritable(), 1, true);45-test('Throws stream error when stdout option Duplex errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 1, true);46-test('Throws stream error when stderr option errors, with a transform', testStreamError, destroyOptionStream, noopWritable(), 2, true);47-test('Throws stream error when stderr option Duplex errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 2, true);48-test('Throws stream error when output stdio[*] option errors, with a transform', testStreamError, destroyOptionStream, noopWritable(), 3, true);49-test('Throws stream error when output stdio[*] Duplex option errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 3, true);50-test('Throws stream error when input stdio[*] option errors, with a transform', testStreamError, destroyOptionStream, noopReadable(), 3, true);51-test('Throws stream error when subprocess.stdin errors, with a transform', testStreamError, destroySubprocessStream, noopReadable(), 0, true);52-test('Throws stream error when subprocess.stdin Duplex errors, with a transform', testStreamError, destroySubprocessStream, noopDuplex(), 0, true);53-test('Throws stream error when subprocess.stdout errors, with a transform', testStreamError, destroySubprocessStream, noopWritable(), 1, true);54-test('Throws stream error when subprocess.stdout Duplex errors, with a transform', testStreamError, destroySubprocessStream, noopDuplex(), 1, true);55-test('Throws stream error when subprocess.stderr errors, with a transform', testStreamError, destroySubprocessStream, noopWritable(), 2, true);56-test('Throws stream error when subprocess.stderr Duplex errors, with a transform', testStreamError, destroySubprocessStream, noopDuplex(), 2, true);57-test('Throws stream error when output subprocess.stdio[*] errors, with a transform', testStreamError, destroySubprocessStream, noopWritable(), 3, true);58-test('Throws stream error when output subprocess.stdio[*] Duplex errors, with a transform', testStreamError, destroySubprocessStream, noopDuplex(), 3, true);59-test('Throws stream error when input subprocess.stdio[*] errors, with a transform', testStreamError, destroySubprocessStream, noopReadable(), 3, true);added:test/terminate/cancel.js+92 added
1+import {once} from 'node:events';2+import test from 'ava';3+import {execa, execaSync} from '../../index.js';4+import {setFixtureDir} from '../helpers/fixtures-dir.js';5+6+setFixtureDir();7+8+test('result.isCanceled is false when abort isn\'t called (success)', async t => {9+ const {isCanceled} = await execa('noop.js');10+ t.false(isCanceled);11+});12+13+test('result.isCanceled is false when abort isn\'t called (failure)', async t => {14+ const {isCanceled} = await t.throwsAsync(execa('fail.js'));15+ t.false(isCanceled);16+});17+18+test('result.isCanceled is false when abort isn\'t called in sync mode (success)', t => {19+ const {isCanceled} = execaSync('noop.js');20+ t.false(isCanceled);21+});22+23+test('result.isCanceled is false when abort isn\'t called in sync mode (failure)', t => {24+ const {isCanceled} = t.throws(() => {25+ execaSync('fail.js');26+ });27+ t.false(isCanceled);28+});29+30+test('error.isCanceled is true when abort is used', async t => {31+ const abortController = new AbortController();32+ const subprocess = execa('noop.js', {cancelSignal: abortController.signal});33+ abortController.abort();34+ const {isCanceled} = await t.throwsAsync(subprocess);35+ t.true(isCanceled);36+});37+38+test('error.isCanceled is false when kill method is used', async t => {39+ const abortController = new AbortController();40+ const subprocess = execa('noop.js', {cancelSignal: abortController.signal});41+ subprocess.kill();42+ const {isCanceled} = await t.throwsAsync(subprocess);43+ t.false(isCanceled);44+});45+46+test('calling abort is considered a signal termination', async t => {47+ const abortController = new AbortController();48+ const subprocess = execa('forever.js', {cancelSignal: abortController.signal});49+ await once(subprocess, 'spawn');50+ abortController.abort();51+ const {isTerminated, signal} = await t.throwsAsync(subprocess);52+ t.true(isTerminated);53+ t.is(signal, 'SIGTERM');54+});55+56+test('calling abort throws an error with message "Command was canceled"', async t => {57+ const abortController = new AbortController();58+ const subprocess = execa('noop.js', {cancelSignal: abortController.signal});59+ abortController.abort();60+ await t.throwsAsync(subprocess, {message: /Command was canceled/});61+});62+63+test('calling abort twice should show the same behaviour as calling it once', async t => {64+ const abortController = new AbortController();65+ const subprocess = execa('noop.js', {cancelSignal: abortController.signal});66+ abortController.abort();67+ abortController.abort();68+ const {isCanceled} = await t.throwsAsync(subprocess);69+ t.true(isCanceled);70+});71+72+test('calling abort on a successfully completed subprocess does not make result.isCanceled true', async t => {73+ const abortController = new AbortController();74+ const subprocess = execa('noop.js', {cancelSignal: abortController.signal});75+ const result = await subprocess;76+ abortController.abort();77+ t.false(result.isCanceled);78+});79+80+test('Throws when using the former "signal" option name', t => {81+ const abortController = new AbortController();82+ t.throws(() => {83+ execa('empty.js', {signal: abortController.signal});84+ }, {message: /renamed to "cancelSignal"/});85+});86+87+test('Cannot use cancelSignal, sync', t => {88+ const abortController = new AbortController();89+ t.throws(() => {90+ execaSync('empty.js', {cancelSignal: abortController.signal});91+ }, {message: /The "cancelSignal" option cannot be used/});92+});added:test/terminate/cleanup.js+102 added
1+import process from 'node:process';2+import {setTimeout} from 'node:timers/promises';3+import test from 'ava';4+import {pEvent} from 'p-event';5+import isRunning from 'is-running';6+import {execa, execaSync} from '../../index.js';7+import {setFixtureDir} from '../helpers/fixtures-dir.js';8+import {nestedExecaAsync, nestedWorker} from '../helpers/nested.js';9+import {foobarString} from '../helpers/input.js';10+11+setFixtureDir();12+13+const isWindows = process.platform === 'win32';14+15+// When subprocess exits before current process16+const spawnAndExit = async (t, execaMethod, cleanup, detached) => {17+ const {stdout} = await execaMethod('noop-fd.js', ['1', foobarString], {cleanup, detached});18+ t.is(stdout, foobarString);19+};20+21+test('spawnAndExit', spawnAndExit, nestedExecaAsync, false, false);22+test('spawnAndExit cleanup', spawnAndExit, nestedExecaAsync, true, false);23+test('spawnAndExit detached', spawnAndExit, nestedExecaAsync, false, true);24+test('spawnAndExit cleanup detached', spawnAndExit, nestedExecaAsync, true, true);25+test('spawnAndExit, worker', spawnAndExit, nestedWorker, false, false);26+test('spawnAndExit cleanup, worker', spawnAndExit, nestedWorker, true, false);27+test('spawnAndExit detached, worker', spawnAndExit, nestedWorker, false, true);28+test('spawnAndExit cleanup detached, worker', spawnAndExit, nestedWorker, true, true);29+30+// When current process exits before subprocess31+const spawnAndKill = async (t, [signal, cleanup, detached, isKilled]) => {32+ const subprocess = execa('subprocess.js', [cleanup, detached], {stdio: 'ignore', ipc: true});33+34+ const pid = await pEvent(subprocess, 'message');35+ t.true(Number.isInteger(pid));36+ t.true(isRunning(pid));37+38+ process.kill(subprocess.pid, signal);39+40+ await t.throwsAsync(subprocess);41+ t.false(isRunning(subprocess.pid));42+43+ if (isKilled) {44+ await Promise.race([45+ setTimeout(1e4, undefined, {ref: false}),46+ pollForSubprocessExit(pid),47+ ]);48+ t.is(isRunning(pid), false);49+ } else {50+ t.is(isRunning(pid), true);51+ process.kill(pid, 'SIGKILL');52+ }53+};54+55+const pollForSubprocessExit = async pid => {56+ while (isRunning(pid)) {57+ // eslint-disable-next-line no-await-in-loop58+ await setTimeout(100);59+ }60+};61+62+// Without `options.cleanup`:63+// - on Windows subprocesses are killed if `options.detached: false`, but not64+// if `options.detached: true`65+// - on Linux subprocesses are never killed regardless of `options.detached`66+// With `options.cleanup`, subprocesses are always killed67+// - `options.cleanup` with SIGKILL is a noop, since it cannot be handled68+test('spawnAndKill SIGTERM', spawnAndKill, ['SIGTERM', false, false, isWindows]);69+test('spawnAndKill SIGKILL', spawnAndKill, ['SIGKILL', false, false, isWindows]);70+test('spawnAndKill cleanup SIGTERM', spawnAndKill, ['SIGTERM', true, false, true]);71+test('spawnAndKill cleanup SIGKILL', spawnAndKill, ['SIGKILL', true, false, isWindows]);72+test('spawnAndKill detached SIGTERM', spawnAndKill, ['SIGTERM', false, true, false]);73+test('spawnAndKill detached SIGKILL', spawnAndKill, ['SIGKILL', false, true, false]);74+test('spawnAndKill cleanup detached SIGTERM', spawnAndKill, ['SIGTERM', true, true, false]);75+test('spawnAndKill cleanup detached SIGKILL', spawnAndKill, ['SIGKILL', true, true, false]);76+77+// See #12878+test('removes exit handler on exit', async t => {79+ // @todo this relies on `signal-exit` internals80+ const exitListeners = globalThis[Symbol.for('signal-exit emitter')].listeners.exit;81+82+ const subprocess = execa('noop.js');83+ const listener = exitListeners.at(-1);84+85+ await subprocess;86+ t.false(exitListeners.includes(listener));87+});88+89+test('detach subprocess', async t => {90+ const {stdout} = await execa('detach.js');91+ const pid = Number(stdout);92+ t.true(Number.isInteger(pid));93+ t.true(isRunning(pid));94+95+ process.kill(pid, 'SIGKILL');96+});97+98+test('Cannot use "detached" option, sync', t => {99+ t.throws(() => {100+ execaSync('empty.js', {detached: true});101+ }, {message: /The "detached: true" option cannot be used/});102+});added:test/terminate/kill-error.js+83 added
1+import {once} from 'node:events';2+import {setImmediate} from 'node:timers/promises';3+import test from 'ava';4+import isRunning from 'is-running';5+import {execa} from '../../index.js';6+import {setFixtureDir} from '../helpers/fixtures-dir.js';7+8+setFixtureDir();9+10+test('.kill(error) propagates error', async t => {11+ const subprocess = execa('forever.js');12+ const originalMessage = 'test';13+ const cause = new Error(originalMessage);14+ t.true(subprocess.kill(cause));15+ const error = await t.throwsAsync(subprocess);16+ t.is(error.cause, cause);17+ t.true(cause.stack.includes(import.meta.url));18+ t.is(error.exitCode, undefined);19+ t.is(error.signal, 'SIGTERM');20+ t.true(error.isTerminated);21+ t.is(error.originalMessage, originalMessage);22+ t.true(error.message.includes(originalMessage));23+ t.true(error.message.includes('was killed with SIGTERM'));24+});25+26+test('.kill(error) uses killSignal', async t => {27+ const subprocess = execa('forever.js', {killSignal: 'SIGINT'});28+ const cause = new Error('test');29+ subprocess.kill(cause);30+ const error = await t.throwsAsync(subprocess);31+ t.is(error.cause, cause);32+ t.is(error.signal, 'SIGINT');33+});34+35+test('.kill(signal, error) uses signal', async t => {36+ const subprocess = execa('forever.js');37+ const cause = new Error('test');38+ subprocess.kill('SIGINT', cause);39+ const error = await t.throwsAsync(subprocess);40+ t.is(error.cause, cause);41+ t.is(error.signal, 'SIGINT');42+});43+44+test('.kill(error) is a noop if subprocess already exited', async t => {45+ const subprocess = execa('empty.js');46+ await subprocess;47+ t.false(isRunning(subprocess.pid));48+ t.false(subprocess.kill(new Error('test')));49+});50+51+test('.kill(error) terminates but does not change the error if the subprocess already errored but did not exit yet', async t => {52+ const subprocess = execa('forever.js');53+ const cause = new Error('first');54+ subprocess.stdout.destroy(cause);55+ await setImmediate();56+ const secondError = new Error('second');57+ t.true(subprocess.kill(secondError));58+ const error = await t.throwsAsync(subprocess);59+ t.is(error.cause, cause);60+ t.is(error.exitCode, undefined);61+ t.is(error.signal, 'SIGTERM');62+ t.true(error.isTerminated);63+ t.false(error.message.includes(secondError.message));64+});65+66+test('.kill(error) twice in a row', async t => {67+ const subprocess = execa('forever.js');68+ const cause = new Error('first');69+ subprocess.kill(cause);70+ const secondCause = new Error('second');71+ subprocess.kill(secondCause);72+ const error = await t.throwsAsync(subprocess);73+ t.is(error.cause, cause);74+ t.false(error.message.includes(secondCause.message));75+});76+77+test('.kill(error) does not emit the "error" event', async t => {78+ const subprocess = execa('forever.js');79+ const cause = new Error('test');80+ subprocess.kill(cause);81+ const error = await Promise.race([t.throwsAsync(subprocess), once(subprocess, 'error')]);82+ t.is(error.cause, cause);83+});added:test/terminate/kill-force.js+140 added
1+import process from 'node:process';2+import {once, defaultMaxListeners} from 'node:events';3+import {constants} from 'node:os';4+import {setTimeout} from 'node:timers/promises';5+import test from 'ava';6+import {pEvent} from 'p-event';7+import isRunning from 'is-running';8+import {execa} from '../../index.js';9+import {setFixtureDir} from '../helpers/fixtures-dir.js';10+import {assertMaxListeners} from '../helpers/listeners.js';11+12+setFixtureDir();13+14+const isWindows = process.platform === 'win32';15+16+const spawnNoKillable = async (forceKillAfterDelay, options) => {17+ const subprocess = execa('no-killable.js', {18+ ipc: true,19+ forceKillAfterDelay,20+ ...options,21+ });22+ await pEvent(subprocess, 'message');23+ return {subprocess};24+};25+26+const spawnNoKillableSimple = options => execa('forever.js', {killSignal: 'SIGWINCH', forceKillAfterDelay: 1, ...options});27+28+test('kill("SIGKILL") should terminate cleanly', async t => {29+ const {subprocess} = await spawnNoKillable();30+31+ subprocess.kill('SIGKILL');32+33+ const {isTerminated, signal} = await t.throwsAsync(subprocess);34+ t.true(isTerminated);35+ t.is(signal, 'SIGKILL');36+});37+38+const testInvalidForceKill = async (t, forceKillAfterDelay) => {39+ t.throws(() => {40+ execa('empty.js', {forceKillAfterDelay});41+ }, {instanceOf: TypeError, message: /non-negative integer/});42+};43+44+test('`forceKillAfterDelay` should not be NaN', testInvalidForceKill, Number.NaN);45+test('`forceKillAfterDelay` should not be negative', testInvalidForceKill, -1);46+47+// `SIGTERM` cannot be caught on Windows, and it always aborts the subprocess (like `SIGKILL` on Unix).48+// Therefore, this feature and those tests must be different on Windows.49+if (isWindows) {50+ test('Can call `.kill()` with `forceKillAfterDelay` on Windows', async t => {51+ const {subprocess} = await spawnNoKillable(1);52+ subprocess.kill();53+54+ const {isTerminated, signal} = await t.throwsAsync(subprocess);55+ t.true(isTerminated);56+ t.is(signal, 'SIGTERM');57+ });58+} else {59+ const testNoForceKill = async (t, forceKillAfterDelay, killArgument, options) => {60+ const {subprocess} = await spawnNoKillable(forceKillAfterDelay, options);61+62+ subprocess.kill(killArgument);63+64+ await setTimeout(6e3);65+ t.true(isRunning(subprocess.pid));66+ subprocess.kill('SIGKILL');67+68+ const {isTerminated, signal} = await t.throwsAsync(subprocess);69+ t.true(isTerminated);70+ t.is(signal, 'SIGKILL');71+ };72+73+ test('`forceKillAfterDelay: false` should not kill after a timeout', testNoForceKill, false);74+ test('`forceKillAfterDelay` should not kill after a timeout with other signals', testNoForceKill, true, 'SIGINT');75+ test('`forceKillAfterDelay` should not kill after a timeout with wrong killSignal string', testNoForceKill, true, 'SIGTERM', {killSignal: 'SIGINT'});76+ test('`forceKillAfterDelay` should not kill after a timeout with wrong killSignal number', testNoForceKill, true, constants.signals.SIGTERM, {killSignal: constants.signals.SIGINT});77+78+ const testForceKill = async (t, forceKillAfterDelay, killArgument, options) => {79+ const {subprocess} = await spawnNoKillable(forceKillAfterDelay, options);80+81+ subprocess.kill(killArgument);82+83+ const {isTerminated, signal} = await t.throwsAsync(subprocess);84+ t.true(isTerminated);85+ t.is(signal, 'SIGKILL');86+ };87+88+ test('`forceKillAfterDelay: number` should kill after a timeout', testForceKill, 50);89+ test('`forceKillAfterDelay: true` should kill after a timeout', testForceKill, true);90+ test('`forceKillAfterDelay: undefined` should kill after a timeout', testForceKill, undefined);91+ test('`forceKillAfterDelay` should kill after a timeout with SIGTERM', testForceKill, 50, 'SIGTERM');92+ test('`forceKillAfterDelay` should kill after a timeout with the killSignal string', testForceKill, 50, 'SIGINT', {killSignal: 'SIGINT'});93+ test('`forceKillAfterDelay` should kill after a timeout with the killSignal number', testForceKill, 50, constants.signals.SIGINT, {killSignal: constants.signals.SIGINT});94+ test('`forceKillAfterDelay` should kill after a timeout with an error', testForceKill, 50, new Error('test'));95+ test('`forceKillAfterDelay` should kill after a timeout with an error and a killSignal', testForceKill, 50, new Error('test'), {killSignal: 'SIGINT'});96+97+ test('`forceKillAfterDelay` works with the "signal" option', async t => {98+ const abortController = new AbortController();99+ const subprocess = spawnNoKillableSimple({cancelSignal: abortController.signal});100+ await once(subprocess, 'spawn');101+ abortController.abort();102+ const {isTerminated, signal, isCanceled} = await t.throwsAsync(subprocess);103+ t.true(isTerminated);104+ t.is(signal, 'SIGKILL');105+ t.true(isCanceled);106+ });107+108+ test('`forceKillAfterDelay` works with the "timeout" option', async t => {109+ const subprocess = spawnNoKillableSimple({timeout: 1});110+ const {isTerminated, signal, timedOut} = await t.throwsAsync(subprocess);111+ t.true(isTerminated);112+ t.is(signal, 'SIGKILL');113+ t.true(timedOut);114+ });115+116+ test.serial('Can call `.kill()` with `forceKillAfterDelay` many times without triggering the maxListeners warning', async t => {117+ const checkMaxListeners = assertMaxListeners(t);118+119+ const subprocess = spawnNoKillableSimple();120+ for (let index = 0; index < defaultMaxListeners + 1; index += 1) {121+ subprocess.kill();122+ }123+124+ const {isTerminated, signal} = await t.throwsAsync(subprocess);125+ t.true(isTerminated);126+ t.is(signal, 'SIGKILL');127+128+ checkMaxListeners();129+ });130+131+ test('Can call `.kill()` with `forceKillAfterDelay` multiple times', async t => {132+ const subprocess = spawnNoKillableSimple();133+ subprocess.kill();134+ subprocess.kill();135+136+ const {isTerminated, signal} = await t.throwsAsync(subprocess);137+ t.true(isTerminated);138+ t.is(signal, 'SIGKILL');139+ });140+}added:test/terminate/kill-signal.js+95 added
1+import {once} from 'node:events';2+import {setImmediate} from 'node:timers/promises';3+import test from 'ava';4+import {execa} from '../../index.js';5+import {setFixtureDir} from '../helpers/fixtures-dir.js';6+7+setFixtureDir();8+9+test('Can call `.kill()` multiple times', async t => {10+ const subprocess = execa('forever.js');11+ subprocess.kill();12+ subprocess.kill();13+14+ const {isTerminated, signal} = await t.throwsAsync(subprocess);15+ t.true(isTerminated);16+ t.is(signal, 'SIGTERM');17+});18+19+test('execa() returns a promise with kill()', async t => {20+ const subprocess = execa('noop.js', ['foo']);21+ t.is(typeof subprocess.kill, 'function');22+ await subprocess;23+});24+25+const testInvalidKillArgument = async (t, killArgument, secondKillArgument) => {26+ const subprocess = execa('empty.js');27+ const message = secondKillArgument instanceof Error || secondKillArgument === undefined28+ ? /error instance or a signal name/29+ : /second argument is optional/;30+ t.throws(() => {31+ subprocess.kill(killArgument, secondKillArgument);32+ }, {message});33+ await subprocess;34+};35+36+test('Cannot call .kill(null)', testInvalidKillArgument, null);37+test('Cannot call .kill(0n)', testInvalidKillArgument, 0n);38+test('Cannot call .kill(true)', testInvalidKillArgument, true);39+test('Cannot call .kill(errorObject)', testInvalidKillArgument, {name: '', message: '', stack: ''});40+test('Cannot call .kill(errorArray)', testInvalidKillArgument, [new Error('test')]);41+test('Cannot call .kill(undefined, true)', testInvalidKillArgument, undefined, true);42+test('Cannot call .kill("SIGTERM", true)', testInvalidKillArgument, 'SIGTERM', true);43+test('Cannot call .kill(true, error)', testInvalidKillArgument, true, new Error('test'));44+45+test('subprocess errors are handled before spawn', async t => {46+ const subprocess = execa('forever.js');47+ const cause = new Error('test');48+ subprocess.emit('error', cause);49+ subprocess.kill();50+ const error = await t.throwsAsync(subprocess);51+ t.is(error.cause, cause);52+ t.is(error.exitCode, undefined);53+ t.is(error.signal, undefined);54+ t.false(error.isTerminated);55+});56+57+test('subprocess errors are handled after spawn', async t => {58+ const subprocess = execa('forever.js');59+ await once(subprocess, 'spawn');60+ const cause = new Error('test');61+ subprocess.emit('error', cause);62+ subprocess.kill();63+ const error = await t.throwsAsync(subprocess);64+ t.is(error.cause, cause);65+ t.is(error.exitCode, undefined);66+ t.is(error.signal, 'SIGTERM');67+ t.true(error.isTerminated);68+});69+70+test('subprocess double errors are handled after spawn', async t => {71+ const abortController = new AbortController();72+ const subprocess = execa('forever.js', {cancelSignal: abortController.signal});73+ await once(subprocess, 'spawn');74+ const cause = new Error('test');75+ subprocess.emit('error', cause);76+ await setImmediate();77+ abortController.abort();78+ const error = await t.throwsAsync(subprocess);79+ t.is(error.cause, cause);80+ t.is(error.exitCode, undefined);81+ t.is(error.signal, 'SIGTERM');82+ t.true(error.isTerminated);83+});84+85+test('subprocess errors use killSignal', async t => {86+ const subprocess = execa('forever.js', {killSignal: 'SIGINT'});87+ await once(subprocess, 'spawn');88+ const cause = new Error('test');89+ subprocess.emit('error', cause);90+ subprocess.kill();91+ const error = await t.throwsAsync(subprocess);92+ t.is(error.cause, cause);93+ t.true(error.isTerminated);94+ t.is(error.signal, 'SIGINT');95+});added:test/terminate/timeout.js+76 added
1+import test from 'ava';2+import {execa, execaSync} from '../../index.js';3+import {setFixtureDir, FIXTURES_DIR} from '../helpers/fixtures-dir.js';4+5+setFixtureDir();6+7+test('timeout kills the subprocess if it times out', async t => {8+ const {isTerminated, signal, timedOut, originalMessage, shortMessage, message} = await t.throwsAsync(execa('forever.js', {timeout: 1}));9+ t.true(isTerminated);10+ t.is(signal, 'SIGTERM');11+ t.true(timedOut);12+ t.is(originalMessage, '');13+ t.is(shortMessage, 'Command timed out after 1 milliseconds: forever.js');14+ t.is(message, shortMessage);15+});16+17+test('timeout kills the subprocess if it times out, in sync mode', async t => {18+ const {isTerminated, signal, timedOut, originalMessage, shortMessage, message} = await t.throws(() => {19+ execaSync('node', ['forever.js'], {timeout: 1, cwd: FIXTURES_DIR});20+ });21+ t.true(isTerminated);22+ t.is(signal, 'SIGTERM');23+ t.true(timedOut);24+ t.is(originalMessage, 'spawnSync node ETIMEDOUT');25+ t.is(shortMessage, `Command timed out after 1 milliseconds: node forever.js\n${originalMessage}`);26+ t.is(message, shortMessage);27+});28+29+test('timeout does not kill the subprocess if it does not time out', async t => {30+ const {timedOut} = await execa('delay.js', ['500'], {timeout: 1e8});31+ t.false(timedOut);32+});33+34+test('timeout uses killSignal', async t => {35+ const {isTerminated, signal, timedOut} = await t.throwsAsync(execa('forever.js', {timeout: 1, killSignal: 'SIGINT'}));36+ t.true(isTerminated);37+ t.is(signal, 'SIGINT');38+ t.true(timedOut);39+});40+41+const INVALID_TIMEOUT_REGEXP = /`timeout` option to be a non-negative integer/;42+43+const testTimeoutValidation = (t, timeout, execaMethod) => {44+ t.throws(() => {45+ execaMethod('empty.js', {timeout});46+ }, {message: INVALID_TIMEOUT_REGEXP});47+};48+49+test('timeout must not be negative', testTimeoutValidation, -1, execa);50+test('timeout must be an integer', testTimeoutValidation, false, execa);51+test('timeout must not be negative - sync', testTimeoutValidation, -1, execaSync);52+test('timeout must be an integer - sync', testTimeoutValidation, false, execaSync);53+54+test('timedOut is false if timeout is undefined', async t => {55+ const {timedOut} = await execa('noop.js');56+ t.false(timedOut);57+});58+59+test('timedOut is false if timeout is 0', async t => {60+ const {timedOut} = await execa('noop.js', {timeout: 0});61+ t.false(timedOut);62+});63+64+test('timedOut is false if timeout is undefined and exit code is 0 in sync mode', t => {65+ const {timedOut} = execaSync('noop.js');66+ t.false(timedOut);67+});68+69+test('timedOut is true if the timeout happened after a different error occurred', async t => {70+ const subprocess = execa('forever.js', {timeout: 1e3});71+ const cause = new Error('test');72+ subprocess.emit('error', cause);73+ const error = await t.throwsAsync(subprocess);74+ t.is(error.cause, cause);75+ t.true(error.timedOut);76+});added:test/transform/encoding-final.js+129 added
1+import {Buffer} from 'node:buffer';2+import {exec} from 'node:child_process';3+import {promisify} from 'node:util';4+import test from 'ava';5+import getStream from 'get-stream';6+import {execa, execaSync} from '../../index.js';7+import {setFixtureDir, FIXTURES_DIR} from '../helpers/fixtures-dir.js';8+import {fullStdio} from '../helpers/stdio.js';9+import {foobarString, foobarUint8Array, foobarHex} from '../helpers/input.js';10+11+const pExec = promisify(exec);12+13+setFixtureDir();14+15+const checkEncoding = async (t, encoding, fdNumber, execaMethod) => {16+ const {stdio} = await execaMethod('noop-fd.js', [`${fdNumber}`, STRING_TO_ENCODE], {...fullStdio, encoding});17+ compareValues(t, stdio[fdNumber], encoding);18+19+ if (execaMethod !== execaSync) {20+ const subprocess = execaMethod('noop-fd.js', [`${fdNumber}`, STRING_TO_ENCODE], {...fullStdio, encoding});21+ const result = await getStream(subprocess.stdio[fdNumber]);22+ compareValues(t, result, 'utf8');23+ await subprocess;24+ }25+26+ if (fdNumber === 3) {27+ return;28+ }29+30+ const {stdout, stderr} = await pExec(`node noop-fd.js ${fdNumber} ${STRING_TO_ENCODE}`, {encoding, cwd: FIXTURES_DIR});31+ compareValues(t, fdNumber === 1 ? stdout : stderr, encoding);32+};33+34+const compareValues = (t, value, encoding) => {35+ if (encoding === 'buffer') {36+ t.true(ArrayBuffer.isView(value));37+ t.true(BUFFER_TO_ENCODE.equals(value));38+ } else {39+ t.is(value, BUFFER_TO_ENCODE.toString(encoding));40+ }41+};42+43+// This string gives different outputs with each encoding type44+const STRING_TO_ENCODE = '\u1000.';45+const BUFFER_TO_ENCODE = Buffer.from(STRING_TO_ENCODE);46+47+test('can pass encoding "buffer" to stdout', checkEncoding, 'buffer', 1, execa);48+test('can pass encoding "utf8" to stdout', checkEncoding, 'utf8', 1, execa);49+test('can pass encoding "utf16le" to stdout', checkEncoding, 'utf16le', 1, execa);50+test('can pass encoding "latin1" to stdout', checkEncoding, 'latin1', 1, execa);51+test('can pass encoding "ascii" to stdout', checkEncoding, 'ascii', 1, execa);52+test('can pass encoding "hex" to stdout', checkEncoding, 'hex', 1, execa);53+test('can pass encoding "base64" to stdout', checkEncoding, 'base64', 1, execa);54+test('can pass encoding "base64url" to stdout', checkEncoding, 'base64url', 1, execa);55+test('can pass encoding "buffer" to stderr', checkEncoding, 'buffer', 2, execa);56+test('can pass encoding "utf8" to stderr', checkEncoding, 'utf8', 2, execa);57+test('can pass encoding "utf16le" to stderr', checkEncoding, 'utf16le', 2, execa);58+test('can pass encoding "latin1" to stderr', checkEncoding, 'latin1', 2, execa);59+test('can pass encoding "ascii" to stderr', checkEncoding, 'ascii', 2, execa);60+test('can pass encoding "hex" to stderr', checkEncoding, 'hex', 2, execa);61+test('can pass encoding "base64" to stderr', checkEncoding, 'base64', 2, execa);62+test('can pass encoding "base64url" to stderr', checkEncoding, 'base64url', 2, execa);63+test('can pass encoding "buffer" to stdio[*]', checkEncoding, 'buffer', 3, execa);64+test('can pass encoding "utf8" to stdio[*]', checkEncoding, 'utf8', 3, execa);65+test('can pass encoding "utf16le" to stdio[*]', checkEncoding, 'utf16le', 3, execa);66+test('can pass encoding "latin1" to stdio[*]', checkEncoding, 'latin1', 3, execa);67+test('can pass encoding "ascii" to stdio[*]', checkEncoding, 'ascii', 3, execa);68+test('can pass encoding "hex" to stdio[*]', checkEncoding, 'hex', 3, execa);69+test('can pass encoding "base64" to stdio[*]', checkEncoding, 'base64', 3, execa);70+test('can pass encoding "base64url" to stdio[*]', checkEncoding, 'base64url', 3, execa);71+test('can pass encoding "buffer" to stdout - sync', checkEncoding, 'buffer', 1, execaSync);72+test('can pass encoding "utf8" to stdout - sync', checkEncoding, 'utf8', 1, execaSync);73+test('can pass encoding "utf16le" to stdout - sync', checkEncoding, 'utf16le', 1, execaSync);74+test('can pass encoding "latin1" to stdout - sync', checkEncoding, 'latin1', 1, execaSync);75+test('can pass encoding "ascii" to stdout - sync', checkEncoding, 'ascii', 1, execaSync);76+test('can pass encoding "hex" to stdout - sync', checkEncoding, 'hex', 1, execaSync);77+test('can pass encoding "base64" to stdout - sync', checkEncoding, 'base64', 1, execaSync);78+test('can pass encoding "base64url" to stdout - sync', checkEncoding, 'base64url', 1, execaSync);79+test('can pass encoding "buffer" to stderr - sync', checkEncoding, 'buffer', 2, execaSync);80+test('can pass encoding "utf8" to stderr - sync', checkEncoding, 'utf8', 2, execaSync);81+test('can pass encoding "utf16le" to stderr - sync', checkEncoding, 'utf16le', 2, execaSync);82+test('can pass encoding "latin1" to stderr - sync', checkEncoding, 'latin1', 2, execaSync);83+test('can pass encoding "ascii" to stderr - sync', checkEncoding, 'ascii', 2, execaSync);84+test('can pass encoding "hex" to stderr - sync', checkEncoding, 'hex', 2, execaSync);85+test('can pass encoding "base64" to stderr - sync', checkEncoding, 'base64', 2, execaSync);86+test('can pass encoding "base64url" to stderr - sync', checkEncoding, 'base64url', 2, execaSync);87+test('can pass encoding "buffer" to stdio[*] - sync', checkEncoding, 'buffer', 3, execaSync);88+test('can pass encoding "utf8" to stdio[*] - sync', checkEncoding, 'utf8', 3, execaSync);89+test('can pass encoding "utf16le" to stdio[*] - sync', checkEncoding, 'utf16le', 3, execaSync);90+test('can pass encoding "latin1" to stdio[*] - sync', checkEncoding, 'latin1', 3, execaSync);91+test('can pass encoding "ascii" to stdio[*] - sync', checkEncoding, 'ascii', 3, execaSync);92+test('can pass encoding "hex" to stdio[*] - sync', checkEncoding, 'hex', 3, execaSync);93+test('can pass encoding "base64" to stdio[*] - sync', checkEncoding, 'base64', 3, execaSync);94+test('can pass encoding "base64url" to stdio[*] - sync', checkEncoding, 'base64url', 3, execaSync);95+96+// eslint-disable-next-line max-params97+const testEncodingInput = async (t, input, expectedStdout, encoding, execaMethod) => {98+ const {stdout} = await execaMethod('stdin.js', {input, encoding});99+ t.deepEqual(stdout, expectedStdout);100+};101+102+test('Can use string input', testEncodingInput, foobarString, foobarString, 'utf8', execa);103+test('Can use Uint8Array input', testEncodingInput, foobarUint8Array, foobarString, 'utf8', execa);104+test('Can use string input, encoding "buffer"', testEncodingInput, foobarString, foobarUint8Array, 'buffer', execa);105+test('Can use Uint8Array input, encoding "buffer"', testEncodingInput, foobarUint8Array, foobarUint8Array, 'buffer', execa);106+test('Can use string input, encoding "hex"', testEncodingInput, foobarString, foobarHex, 'hex', execa);107+test('Can use Uint8Array input, encoding "hex"', testEncodingInput, foobarUint8Array, foobarHex, 'hex', execa);108+test('Can use string input, sync', testEncodingInput, foobarString, foobarString, 'utf8', execaSync);109+test('Can use Uint8Array input, sync', testEncodingInput, foobarUint8Array, foobarString, 'utf8', execaSync);110+test('Can use string input, encoding "buffer", sync', testEncodingInput, foobarString, foobarUint8Array, 'buffer', execaSync);111+test('Can use Uint8Array input, encoding "buffer", sync', testEncodingInput, foobarUint8Array, foobarUint8Array, 'buffer', execaSync);112+test('Can use string input, encoding "hex", sync', testEncodingInput, foobarString, foobarHex, 'hex', execaSync);113+test('Can use Uint8Array input, encoding "hex", sync', testEncodingInput, foobarUint8Array, foobarHex, 'hex', execaSync);114+115+const testSubprocessEncoding = (t, encoding) => {116+ const subprocess = execa('empty.js', {...fullStdio, encoding});117+ t.is(subprocess.stdout.readableEncoding, null);118+ t.is(subprocess.stderr.readableEncoding, null);119+ t.is(subprocess.stdio[3].readableEncoding, null);120+};121+122+test('Does not modify subprocess.std* encoding, "utf8"', testSubprocessEncoding, 'utf8');123+test('Does not modify subprocess.std* encoding, "utf16le"', testSubprocessEncoding, 'utf16le');124+test('Does not modify subprocess.std* encoding, "buffer"', testSubprocessEncoding, 'buffer');125+test('Does not modify subprocess.std* encoding, "hex"', testSubprocessEncoding, 'hex');126+test('Does not modify subprocess.std* encoding, "base64"', testSubprocessEncoding, 'base64');127+test('Does not modify subprocess.std* encoding, "base64url"', testSubprocessEncoding, 'base64url');128+test('Does not modify subprocess.std* encoding, "latin1"', testSubprocessEncoding, 'latin1');129+test('Does not modify subprocess.std* encoding, "ascii"', testSubprocessEncoding, 'ascii');added:test/transform/encoding-ignored.js+92 added
1+import process from 'node:process';2+import test from 'ava';3+import {execa, execaSync} from '../../index.js';4+import {setFixtureDir} from '../helpers/fixtures-dir.js';5+import {outputObjectGenerator, addNoopGenerator} from '../helpers/generator.js';6+import {foobarObject} from '../helpers/input.js';7+8+setFixtureDir();9+10+const testObjectMode = async (t, addNoopTransform, execaMethod) => {11+ const {stdout} = await execaMethod('noop.js', {12+ stdout: addNoopGenerator(outputObjectGenerator(), addNoopTransform, true),13+ encoding: 'base64',14+ });15+ t.deepEqual(stdout, [foobarObject]);16+};17+18+test('Other encodings work with transforms that return objects', testObjectMode, false, execa);19+test('Other encodings work with transforms that return objects, noop transform', testObjectMode, true, execa);20+test('Other encodings work with transforms that return objects, sync', testObjectMode, false, execaSync);21+test('Other encodings work with transforms that return objects, noop transform, sync', testObjectMode, true, execaSync);22+23+// eslint-disable-next-line max-params24+const testIgnoredEncoding = async (t, stdoutOption, isUndefined, options, execaMethod) => {25+ const {stdout} = await execaMethod('empty.js', {stdout: stdoutOption, ...options});26+ t.is(stdout === undefined, isUndefined);27+};28+29+const base64Options = {encoding: 'base64'};30+const linesOptions = {lines: true};31+test('Is ignored with other encodings and "ignore"', testIgnoredEncoding, 'ignore', true, base64Options, execa);32+test('Is ignored with other encodings and ["ignore"]', testIgnoredEncoding, ['ignore'], true, base64Options, execa);33+test('Is ignored with other encodings and "ipc"', testIgnoredEncoding, 'ipc', true, base64Options, execa);34+test('Is ignored with other encodings and ["ipc"]', testIgnoredEncoding, ['ipc'], true, base64Options, execa);35+test('Is ignored with other encodings and "inherit"', testIgnoredEncoding, 'inherit', true, base64Options, execa);36+test('Is ignored with other encodings and ["inherit"]', testIgnoredEncoding, ['inherit'], true, base64Options, execa);37+test('Is ignored with other encodings and 1', testIgnoredEncoding, 1, true, base64Options, execa);38+test('Is ignored with other encodings and [1]', testIgnoredEncoding, [1], true, base64Options, execa);39+test('Is ignored with other encodings and process.stdout', testIgnoredEncoding, process.stdout, true, base64Options, execa);40+test('Is ignored with other encodings and [process.stdout]', testIgnoredEncoding, [process.stdout], true, base64Options, execa);41+test('Is not ignored with other encodings and "pipe"', testIgnoredEncoding, 'pipe', false, base64Options, execa);42+test('Is not ignored with other encodings and ["pipe"]', testIgnoredEncoding, ['pipe'], false, base64Options, execa);43+test('Is not ignored with other encodings and "overlapped"', testIgnoredEncoding, 'overlapped', false, base64Options, execa);44+test('Is not ignored with other encodings and ["overlapped"]', testIgnoredEncoding, ['overlapped'], false, base64Options, execa);45+test('Is not ignored with other encodings and ["inherit", "pipe"]', testIgnoredEncoding, ['inherit', 'pipe'], false, base64Options, execa);46+test('Is not ignored with other encodings and undefined', testIgnoredEncoding, undefined, false, base64Options, execa);47+test('Is not ignored with other encodings and null', testIgnoredEncoding, null, false, base64Options, execa);48+test('Is ignored with "lines: true" and "ignore"', testIgnoredEncoding, 'ignore', true, linesOptions, execa);49+test('Is ignored with "lines: true" and ["ignore"]', testIgnoredEncoding, ['ignore'], true, linesOptions, execa);50+test('Is ignored with "lines: true" and "ipc"', testIgnoredEncoding, 'ipc', true, linesOptions, execa);51+test('Is ignored with "lines: true" and ["ipc"]', testIgnoredEncoding, ['ipc'], true, linesOptions, execa);52+test('Is ignored with "lines: true" and "inherit"', testIgnoredEncoding, 'inherit', true, linesOptions, execa);53+test('Is ignored with "lines: true" and ["inherit"]', testIgnoredEncoding, ['inherit'], true, linesOptions, execa);54+test('Is ignored with "lines: true" and 1', testIgnoredEncoding, 1, true, linesOptions, execa);55+test('Is ignored with "lines: true" and [1]', testIgnoredEncoding, [1], true, linesOptions, execa);56+test('Is ignored with "lines: true" and process.stdout', testIgnoredEncoding, process.stdout, true, linesOptions, execa);57+test('Is ignored with "lines: true" and [process.stdout]', testIgnoredEncoding, [process.stdout], true, linesOptions, execa);58+test('Is not ignored with "lines: true" and "pipe"', testIgnoredEncoding, 'pipe', false, linesOptions, execa);59+test('Is not ignored with "lines: true" and ["pipe"]', testIgnoredEncoding, ['pipe'], false, linesOptions, execa);60+test('Is not ignored with "lines: true" and "overlapped"', testIgnoredEncoding, 'overlapped', false, linesOptions, execa);61+test('Is not ignored with "lines: true" and ["overlapped"]', testIgnoredEncoding, ['overlapped'], false, linesOptions, execa);62+test('Is not ignored with "lines: true" and ["inherit", "pipe"]', testIgnoredEncoding, ['inherit', 'pipe'], false, linesOptions, execa);63+test('Is not ignored with "lines: true" and undefined', testIgnoredEncoding, undefined, false, linesOptions, execa);64+test('Is not ignored with "lines: true" and null', testIgnoredEncoding, null, false, linesOptions, execa);65+test('Is ignored with "lines: true", other encodings and "ignore"', testIgnoredEncoding, 'ignore', true, {...base64Options, ...linesOptions}, execa);66+test('Is not ignored with "lines: true", other encodings and "pipe"', testIgnoredEncoding, 'pipe', false, {...base64Options, ...linesOptions}, execa);67+test('Is ignored with other encodings and "ignore", sync', testIgnoredEncoding, 'ignore', true, base64Options, execaSync);68+test('Is ignored with other encodings and ["ignore"], sync', testIgnoredEncoding, ['ignore'], true, base64Options, execaSync);69+test('Is ignored with other encodings and "inherit", sync', testIgnoredEncoding, 'inherit', true, base64Options, execaSync);70+test('Is ignored with other encodings and ["inherit"], sync', testIgnoredEncoding, ['inherit'], true, base64Options, execaSync);71+test('Is ignored with other encodings and 1, sync', testIgnoredEncoding, 1, true, base64Options, execaSync);72+test('Is ignored with other encodings and [1], sync', testIgnoredEncoding, [1], true, base64Options, execaSync);73+test('Is ignored with other encodings and process.stdout, sync', testIgnoredEncoding, process.stdout, true, base64Options, execaSync);74+test('Is ignored with other encodings and [process.stdout], sync', testIgnoredEncoding, [process.stdout], true, base64Options, execaSync);75+test('Is not ignored with other encodings and "pipe", sync', testIgnoredEncoding, 'pipe', false, base64Options, execaSync);76+test('Is not ignored with other encodings and ["pipe"], sync', testIgnoredEncoding, ['pipe'], false, base64Options, execaSync);77+test('Is not ignored with other encodings and undefined, sync', testIgnoredEncoding, undefined, false, base64Options, execaSync);78+test('Is not ignored with other encodings and null, sync', testIgnoredEncoding, null, false, base64Options, execaSync);79+test('Is ignored with "lines: true" and "ignore", sync', testIgnoredEncoding, 'ignore', true, linesOptions, execaSync);80+test('Is ignored with "lines: true" and ["ignore"], sync', testIgnoredEncoding, ['ignore'], true, linesOptions, execaSync);81+test('Is ignored with "lines: true" and "inherit", sync', testIgnoredEncoding, 'inherit', true, linesOptions, execaSync);82+test('Is ignored with "lines: true" and ["inherit"], sync', testIgnoredEncoding, ['inherit'], true, linesOptions, execaSync);83+test('Is ignored with "lines: true" and 1, sync', testIgnoredEncoding, 1, true, linesOptions, execaSync);84+test('Is ignored with "lines: true" and [1], sync', testIgnoredEncoding, [1], true, linesOptions, execaSync);85+test('Is ignored with "lines: true" and process.stdout, sync', testIgnoredEncoding, process.stdout, true, linesOptions, execaSync);86+test('Is ignored with "lines: true" and [process.stdout], sync', testIgnoredEncoding, [process.stdout], true, linesOptions, execaSync);87+test('Is not ignored with "lines: true" and "pipe", sync', testIgnoredEncoding, 'pipe', false, linesOptions, execaSync);88+test('Is not ignored with "lines: true" and ["pipe"], sync', testIgnoredEncoding, ['pipe'], false, linesOptions, execaSync);89+test('Is not ignored with "lines: true" and undefined, sync', testIgnoredEncoding, undefined, false, linesOptions, execaSync);90+test('Is not ignored with "lines: true" and null, sync', testIgnoredEncoding, null, false, linesOptions, execaSync);91+test('Is ignored with "lines: true", other encodings and "ignore", sync', testIgnoredEncoding, 'ignore', true, {...base64Options, ...linesOptions}, execaSync);92+test('Is not ignored with "lines: true", other encodings and "pipe", sync', testIgnoredEncoding, 'pipe', false, {...base64Options, ...linesOptions}, execaSync);added:test/transform/encoding-multibyte.js+73 added
1+import test from 'ava';2+import {execa, execaSync} from '../../index.js';3+import {setFixtureDir} from '../helpers/fixtures-dir.js';4+import {noopGenerator, getOutputsGenerator, addNoopGenerator} from '../helpers/generator.js';5+import {multibyteChar, multibyteString, multibyteUint8Array, breakingLength, brokenSymbol} from '../helpers/encoding.js';6+7+setFixtureDir();8+9+const foobarArray = ['fo', 'ob', 'ar', '..'];10+11+const testMultibyteCharacters = async (t, objectMode, addNoopTransform, execaMethod) => {12+ const {stdout} = await execaMethod('noop.js', {13+ stdout: addNoopGenerator(getOutputsGenerator(foobarArray)(objectMode, true), addNoopTransform, objectMode),14+ encoding: 'base64',15+ });16+ if (objectMode) {17+ t.deepEqual(stdout, foobarArray);18+ } else {19+ t.is(stdout, btoa(foobarArray.join('')));20+ }21+};22+23+test('Handle multibyte characters', testMultibyteCharacters, false, false, execa);24+test('Handle multibyte characters, noop transform', testMultibyteCharacters, false, true, execa);25+test('Handle multibyte characters, with objectMode', testMultibyteCharacters, true, false, execa);26+test('Handle multibyte characters, with objectMode, noop transform', testMultibyteCharacters, true, true, execa);27+test('Handle multibyte characters, sync', testMultibyteCharacters, false, false, execaSync);28+test('Handle multibyte characters, noop transform, sync', testMultibyteCharacters, false, true, execaSync);29+test('Handle multibyte characters, with objectMode, sync', testMultibyteCharacters, true, false, execaSync);30+test('Handle multibyte characters, with objectMode, noop transform, sync', testMultibyteCharacters, true, true, execaSync);31+32+const testMultibyte = async (t, objectMode, execaMethod) => {33+ const {stdout} = await execaMethod('stdin.js', {34+ stdin: [35+ [multibyteUint8Array.slice(0, breakingLength), multibyteUint8Array.slice(breakingLength)],36+ noopGenerator(objectMode, true),37+ ],38+ });39+ t.is(stdout, multibyteString);40+};41+42+test('Generator handles multibyte characters with Uint8Array', testMultibyte, false, execa);43+test('Generator handles multibyte characters with Uint8Array, objectMode', testMultibyte, true, execa);44+test('Generator handles multibyte characters with Uint8Array, sync', testMultibyte, false, execaSync);45+test('Generator handles multibyte characters with Uint8Array, objectMode, sync', testMultibyte, true, execaSync);46+47+const testMultibytePartial = async (t, objectMode, execaMethod) => {48+ const {stdout} = await execaMethod('stdin.js', {49+ stdin: [50+ [multibyteUint8Array.slice(0, breakingLength)],51+ noopGenerator(objectMode, true),52+ ],53+ });54+ t.is(stdout, `${multibyteChar}${brokenSymbol}`);55+};56+57+test('Generator handles partial multibyte characters with Uint8Array', testMultibytePartial, false, execa);58+test('Generator handles partial multibyte characters with Uint8Array, objectMode', testMultibytePartial, true, execa);59+test('Generator handles partial multibyte characters with Uint8Array, sync', testMultibytePartial, false, execaSync);60+test('Generator handles partial multibyte characters with Uint8Array, objectMode, sync', testMultibytePartial, true, execaSync);61+62+const testMultibytePartialOutput = async (t, execaMethod) => {63+ const {stdout} = await execaMethod('noop.js', {64+ stdout: getOutputsGenerator([65+ multibyteUint8Array.slice(0, breakingLength),66+ multibyteUint8Array.slice(breakingLength),67+ ])(false, true),68+ });69+ t.is(stdout, multibyteString);70+};71+72+test('Generator handles output multibyte characters with Uint8Array', testMultibytePartialOutput, execa);73+test('Generator handles output multibyte characters with Uint8Array, sync', testMultibytePartialOutput, execaSync);added:test/transform/encoding-transform.js+172 added
1+import {Buffer} from 'node:buffer';2+import test from 'ava';3+import {execa, execaSync} from '../../index.js';4+import {setFixtureDir} from '../helpers/fixtures-dir.js';5+import {getStdio} from '../helpers/stdio.js';6+import {foobarString, foobarUint8Array, foobarBuffer, foobarObject} from '../helpers/input.js';7+import {noopGenerator, getOutputGenerator} from '../helpers/generator.js';8+9+setFixtureDir();10+11+const getTypeofGenerator = lines => (objectMode, binary) => ({12+ * transform(line) {13+ lines.push(Object.prototype.toString.call(line));14+ yield '';15+ },16+ objectMode,17+ binary,18+});19+20+const assertTypeofChunk = (t, lines, expectedType) => {21+ t.deepEqual(lines, [`[object ${expectedType}]`]);22+};23+24+// eslint-disable-next-line max-params25+const testGeneratorFirstEncoding = async (t, input, encoding, expectedType, objectMode, binary) => {26+ const lines = [];27+ const subprocess = execa('stdin.js', {stdin: getTypeofGenerator(lines)(objectMode, binary), encoding});28+ subprocess.stdin.end(input);29+ await subprocess;30+ assertTypeofChunk(t, lines, expectedType);31+};32+33+test('First generator argument is string with default encoding, with string writes', testGeneratorFirstEncoding, foobarString, 'utf8', 'String', false, undefined);34+test('First generator argument is string with default encoding, with Buffer writes', testGeneratorFirstEncoding, foobarBuffer, 'utf8', 'String', false, undefined);35+test('First generator argument is string with default encoding, with Uint8Array writes', testGeneratorFirstEncoding, foobarUint8Array, 'utf8', 'String', false, undefined);36+test('First generator argument is string with default encoding, with string writes, "binary: false"', testGeneratorFirstEncoding, foobarString, 'utf8', 'String', false, false);37+test('First generator argument is Uint8Array with default encoding, with string writes, "binary: true"', testGeneratorFirstEncoding, foobarString, 'utf8', 'Uint8Array', false, true);38+test('First generator argument is string with encoding "utf16le", with string writes', testGeneratorFirstEncoding, foobarString, 'utf16le', 'String', false, undefined);39+test('First generator argument is string with encoding "utf16le", with Buffer writes', testGeneratorFirstEncoding, foobarBuffer, 'utf16le', 'String', false, undefined);40+test('First generator argument is string with encoding "utf16le", with Uint8Array writes', testGeneratorFirstEncoding, foobarUint8Array, 'utf16le', 'String', false, undefined);41+test('First generator argument is string with encoding "utf16le", with string writes, "binary: false"', testGeneratorFirstEncoding, foobarString, 'utf16le', 'String', false, false);42+test('First generator argument is Uint8Array with encoding "utf16le", with string writes, "binary: true"', testGeneratorFirstEncoding, foobarString, 'utf16le', 'Uint8Array', false, true);43+test('First generator argument is Uint8Array with encoding "buffer", with string writes', testGeneratorFirstEncoding, foobarString, 'buffer', 'Uint8Array', false, undefined);44+test('First generator argument is Uint8Array with encoding "buffer", with Buffer writes', testGeneratorFirstEncoding, foobarBuffer, 'buffer', 'Uint8Array', false, undefined);45+test('First generator argument is Uint8Array with encoding "buffer", with Uint8Array writes', testGeneratorFirstEncoding, foobarUint8Array, 'buffer', 'Uint8Array', false, undefined);46+test('First generator argument is Uint8Array with encoding "buffer", with string writes, "binary: false"', testGeneratorFirstEncoding, foobarString, 'buffer', 'Uint8Array', false, false);47+test('First generator argument is Uint8Array with encoding "buffer", with string writes, "binary: true"', testGeneratorFirstEncoding, foobarString, 'buffer', 'Uint8Array', false, true);48+test('First generator argument is Uint8Array with encoding "hex", with string writes', testGeneratorFirstEncoding, foobarString, 'hex', 'Uint8Array', false, undefined);49+test('First generator argument is Uint8Array with encoding "hex", with Buffer writes', testGeneratorFirstEncoding, foobarBuffer, 'hex', 'Uint8Array', false, undefined);50+test('First generator argument is Uint8Array with encoding "hex", with Uint8Array writes', testGeneratorFirstEncoding, foobarUint8Array, 'hex', 'Uint8Array', false, undefined);51+test('First generator argument is Uint8Array with encoding "hex", with string writes, "binary: false"', testGeneratorFirstEncoding, foobarString, 'hex', 'Uint8Array', false, false);52+test('First generator argument is Uint8Array with encoding "hex", with string writes, "binary: true"', testGeneratorFirstEncoding, foobarString, 'hex', 'Uint8Array', false, true);53+test('First generator argument can be string with objectMode', testGeneratorFirstEncoding, foobarString, 'utf8', 'String', true, undefined);54+test('First generator argument can be string with objectMode, "binary: false"', testGeneratorFirstEncoding, foobarString, 'utf8', 'String', true, false);55+test('First generator argument can be string with objectMode, "binary: true"', testGeneratorFirstEncoding, foobarString, 'utf8', 'String', true, true);56+test('First generator argument can be objects with objectMode', testGeneratorFirstEncoding, foobarObject, 'utf8', 'Object', true, undefined);57+test('First generator argument can be objects with objectMode, "binary: false"', testGeneratorFirstEncoding, foobarObject, 'utf8', 'Object', true, false);58+test('First generator argument can be objects with objectMode, "binary: true"', testGeneratorFirstEncoding, foobarObject, 'utf8', 'Object', true, true);59+60+// eslint-disable-next-line max-params61+const testGeneratorFirstEncodingSync = (t, input, encoding, expectedType, objectMode, binary) => {62+ const lines = [];63+ execaSync('stdin.js', {stdin: [[input], getTypeofGenerator(lines)(objectMode, binary)], encoding});64+ assertTypeofChunk(t, lines, expectedType);65+};66+67+test('First generator argument is string with default encoding, with string writes, sync', testGeneratorFirstEncodingSync, foobarString, 'utf8', 'String', false, undefined);68+test('First generator argument is string with default encoding, with Uint8Array writes, sync', testGeneratorFirstEncodingSync, foobarUint8Array, 'utf8', 'String', false, undefined);69+test('First generator argument is string with default encoding, with string writes, "binary: false", sync', testGeneratorFirstEncodingSync, foobarString, 'utf8', 'String', false, false);70+test('First generator argument is Uint8Array with default encoding, with string writes, "binary: true", sync', testGeneratorFirstEncodingSync, foobarString, 'utf8', 'Uint8Array', false, true);71+test('First generator argument is string with encoding "utf16le", with string writes, sync', testGeneratorFirstEncodingSync, foobarString, 'utf16le', 'String', false, undefined);72+test('First generator argument is string with encoding "utf16le", with Uint8Array writes, sync', testGeneratorFirstEncodingSync, foobarUint8Array, 'utf16le', 'String', false, undefined);73+test('First generator argument is string with encoding "utf16le", with string writes, "binary: false", sync', testGeneratorFirstEncodingSync, foobarString, 'utf16le', 'String', false, false);74+test('First generator argument is Uint8Array with encoding "utf16le", with string writes, "binary: true", sync', testGeneratorFirstEncodingSync, foobarString, 'utf16le', 'Uint8Array', false, true);75+test('First generator argument is Uint8Array with encoding "buffer", with string writes, sync', testGeneratorFirstEncodingSync, foobarString, 'buffer', 'Uint8Array', false, undefined);76+test('First generator argument is Uint8Array with encoding "buffer", with Uint8Array writes, sync', testGeneratorFirstEncodingSync, foobarUint8Array, 'buffer', 'Uint8Array', false, undefined);77+test('First generator argument is Uint8Array with encoding "buffer", with string writes, "binary: false", sync', testGeneratorFirstEncodingSync, foobarString, 'buffer', 'Uint8Array', false, false);78+test('First generator argument is Uint8Array with encoding "buffer", with string writes, "binary: true", sync', testGeneratorFirstEncodingSync, foobarString, 'buffer', 'Uint8Array', false, true);79+test('First generator argument is Uint8Array with encoding "hex", with string writes, sync', testGeneratorFirstEncodingSync, foobarString, 'hex', 'Uint8Array', false, undefined);80+test('First generator argument is Uint8Array with encoding "hex", with Uint8Array writes, sync', testGeneratorFirstEncodingSync, foobarUint8Array, 'hex', 'Uint8Array', false, undefined);81+test('First generator argument is Uint8Array with encoding "hex", with string writes, "binary: false", sync', testGeneratorFirstEncodingSync, foobarString, 'hex', 'Uint8Array', false, false);82+test('First generator argument is Uint8Array with encoding "hex", with string writes, "binary: true", sync', testGeneratorFirstEncodingSync, foobarString, 'hex', 'Uint8Array', false, true);83+test('First generator argument can be string with objectMode, sync', testGeneratorFirstEncodingSync, foobarString, 'utf8', 'String', true, undefined);84+test('First generator argument can be string with objectMode, "binary: false", sync', testGeneratorFirstEncodingSync, foobarString, 'utf8', 'String', true, false);85+test('First generator argument can be string with objectMode, "binary: true", sync', testGeneratorFirstEncodingSync, foobarString, 'utf8', 'String', true, true);86+test('First generator argument can be objects with objectMode, sync', testGeneratorFirstEncodingSync, foobarObject, 'utf8', 'Object', true, undefined);87+test('First generator argument can be objects with objectMode, "binary: false", sync', testGeneratorFirstEncodingSync, foobarObject, 'utf8', 'Object', true, false);88+test('First generator argument can be objects with objectMode, "binary: true", sync', testGeneratorFirstEncodingSync, foobarObject, 'utf8', 'Object', true, true);89+90+const testEncodingIgnored = async (t, encoding) => {91+ const input = Buffer.from(foobarString).toString(encoding);92+ const subprocess = execa('stdin.js', {stdin: noopGenerator(true)});93+ subprocess.stdin.end(input, encoding);94+ const {stdout} = await subprocess;95+ t.is(stdout, input);96+};97+98+test('Write call encoding "utf8" is ignored with objectMode', testEncodingIgnored, 'utf8');99+test('Write call encoding "utf16le" is ignored with objectMode', testEncodingIgnored, 'utf16le');100+test('Write call encoding "hex" is ignored with objectMode', testEncodingIgnored, 'hex');101+test('Write call encoding "base64" is ignored with objectMode', testEncodingIgnored, 'base64');102+103+// eslint-disable-next-line max-params104+const testGeneratorNextEncoding = async (t, input, encoding, firstObjectMode, secondObjectMode, expectedType, execaMethod) => {105+ const lines = [];106+ await execaMethod('noop.js', ['other'], {107+ stdout: [108+ getOutputGenerator(input)(firstObjectMode),109+ getTypeofGenerator(lines)(secondObjectMode),110+ ],111+ encoding,112+ });113+ assertTypeofChunk(t, lines, expectedType);114+};115+116+test('Next generator argument is string with default encoding, with string writes', testGeneratorNextEncoding, foobarString, 'utf8', false, false, 'String', execa);117+test('Next generator argument is string with default encoding, with string writes, objectMode first', testGeneratorNextEncoding, foobarString, 'utf8', true, false, 'String', execa);118+test('Next generator argument is string with default encoding, with string writes, objectMode both', testGeneratorNextEncoding, foobarString, 'utf8', true, true, 'String', execa);119+test('Next generator argument is string with default encoding, with Uint8Array writes', testGeneratorNextEncoding, foobarUint8Array, 'utf8', false, false, 'String', execa);120+test('Next generator argument is Uint8Array with default encoding, with Uint8Array writes, objectMode first', testGeneratorNextEncoding, foobarUint8Array, 'utf8', true, false, 'Uint8Array', execa);121+test('Next generator argument is string with default encoding, with Uint8Array writes, objectMode both', testGeneratorNextEncoding, foobarUint8Array, 'utf8', true, true, 'Uint8Array', execa);122+test('Next generator argument is string with encoding "utf16le", with string writes', testGeneratorNextEncoding, foobarString, 'utf16le', false, false, 'String', execa);123+test('Next generator argument is string with encoding "utf16le",, with string writes, objectMode first', testGeneratorNextEncoding, foobarString, 'utf16le', true, false, 'String', execa);124+test('Next generator argument is string with encoding "utf16le",, with string writes, objectMode both', testGeneratorNextEncoding, foobarString, 'utf16le', true, true, 'String', execa);125+test('Next generator argument is string with encoding "utf16le",, with Uint8Array writes', testGeneratorNextEncoding, foobarUint8Array, 'utf16le', false, false, 'String', execa);126+test('Next generator argument is Uint8Array with encoding "utf16le",, with Uint8Array writes, objectMode first', testGeneratorNextEncoding, foobarUint8Array, 'utf16le', true, false, 'Uint8Array', execa);127+test('Next generator argument is string with encoding "utf16le",, with Uint8Array writes, objectMode both', testGeneratorNextEncoding, foobarUint8Array, 'utf16le', true, true, 'Uint8Array', execa);128+test('Next generator argument is Uint8Array with encoding "buffer", with string writes', testGeneratorNextEncoding, foobarString, 'buffer', false, false, 'Uint8Array', execa);129+test('Next generator argument is string with encoding "buffer", with string writes, objectMode first', testGeneratorNextEncoding, foobarString, 'buffer', true, false, 'String', execa);130+test('Next generator argument is string with encoding "buffer", with string writes, objectMode both', testGeneratorNextEncoding, foobarString, 'buffer', true, true, 'String', execa);131+test('Next generator argument is Uint8Array with encoding "buffer", with Uint8Array writes', testGeneratorNextEncoding, foobarUint8Array, 'buffer', false, false, 'Uint8Array', execa);132+test('Next generator argument is Uint8Array with encoding "buffer", with Uint8Array writes, objectMode first', testGeneratorNextEncoding, foobarUint8Array, 'buffer', true, false, 'Uint8Array', execa);133+test('Next generator argument is Uint8Array with encoding "buffer", with Uint8Array writes, objectMode both', testGeneratorNextEncoding, foobarUint8Array, 'buffer', true, true, 'Uint8Array', execa);134+test('Next generator argument is Uint8Array with encoding "hex", with string writes', testGeneratorNextEncoding, foobarString, 'hex', false, false, 'Uint8Array', execa);135+test('Next generator argument is Uint8Array with encoding "hex", with Uint8Array writes', testGeneratorNextEncoding, foobarUint8Array, 'hex', false, false, 'Uint8Array', execa);136+test('Next generator argument is object with default encoding, with object writes, objectMode first', testGeneratorNextEncoding, foobarObject, 'utf8', true, false, 'Object', execa);137+test('Next generator argument is object with default encoding, with object writes, objectMode both', testGeneratorNextEncoding, foobarObject, 'utf8', true, true, 'Object', execa);138+test('Next generator argument is string with default encoding, with string writes, sync', testGeneratorNextEncoding, foobarString, 'utf8', false, false, 'String', execaSync);139+test('Next generator argument is string with default encoding, with string writes, objectMode first, sync', testGeneratorNextEncoding, foobarString, 'utf8', true, false, 'String', execaSync);140+test('Next generator argument is string with default encoding, with string writes, objectMode both, sync', testGeneratorNextEncoding, foobarString, 'utf8', true, true, 'String', execaSync);141+test('Next generator argument is string with default encoding, with Uint8Array writes, sync', testGeneratorNextEncoding, foobarUint8Array, 'utf8', false, false, 'String', execaSync);142+test('Next generator argument is Uint8Array with default encoding, with Uint8Array writes, objectMode first, sync', testGeneratorNextEncoding, foobarUint8Array, 'utf8', true, false, 'Uint8Array', execaSync);143+test('Next generator argument is string with default encoding, with Uint8Array writes, objectMode both, sync', testGeneratorNextEncoding, foobarUint8Array, 'utf8', true, true, 'Uint8Array', execaSync);144+test('Next generator argument is string with encoding "utf16le", with string writes, sync', testGeneratorNextEncoding, foobarString, 'utf16le', false, false, 'String', execaSync);145+test('Next generator argument is string with encoding "utf16le",, with string writes, objectMode first, sync', testGeneratorNextEncoding, foobarString, 'utf16le', true, false, 'String', execaSync);146+test('Next generator argument is string with encoding "utf16le",, with string writes, objectMode both, sync', testGeneratorNextEncoding, foobarString, 'utf16le', true, true, 'String', execaSync);147+test('Next generator argument is string with encoding "utf16le",, with Uint8Array writes, sync', testGeneratorNextEncoding, foobarUint8Array, 'utf16le', false, false, 'String', execaSync);148+test('Next generator argument is Uint8Array with encoding "utf16le",, with Uint8Array writes, objectMode first, sync', testGeneratorNextEncoding, foobarUint8Array, 'utf16le', true, false, 'Uint8Array', execaSync);149+test('Next generator argument is string with encoding "utf16le",, with Uint8Array writes, objectMode both, sync', testGeneratorNextEncoding, foobarUint8Array, 'utf16le', true, true, 'Uint8Array', execaSync);150+test('Next generator argument is Uint8Array with encoding "buffer", with string writes, sync', testGeneratorNextEncoding, foobarString, 'buffer', false, false, 'Uint8Array', execaSync);151+test('Next generator argument is string with encoding "buffer", with string writes, objectMode first, sync', testGeneratorNextEncoding, foobarString, 'buffer', true, false, 'String', execaSync);152+test('Next generator argument is string with encoding "buffer", with string writes, objectMode both, sync', testGeneratorNextEncoding, foobarString, 'buffer', true, true, 'String', execaSync);153+test('Next generator argument is Uint8Array with encoding "buffer", with Uint8Array writes, sync', testGeneratorNextEncoding, foobarUint8Array, 'buffer', false, false, 'Uint8Array', execaSync);154+test('Next generator argument is Uint8Array with encoding "buffer", with Uint8Array writes, objectMode first, sync', testGeneratorNextEncoding, foobarUint8Array, 'buffer', true, false, 'Uint8Array', execaSync);155+test('Next generator argument is Uint8Array with encoding "buffer", with Uint8Array writes, objectMode both, sync', testGeneratorNextEncoding, foobarUint8Array, 'buffer', true, true, 'Uint8Array', execaSync);156+test('Next generator argument is Uint8Array with encoding "hex", with string writes, sync', testGeneratorNextEncoding, foobarString, 'hex', false, false, 'Uint8Array', execaSync);157+test('Next generator argument is Uint8Array with encoding "hex", with Uint8Array writes, sync', testGeneratorNextEncoding, foobarUint8Array, 'hex', false, false, 'Uint8Array', execaSync);158+test('Next generator argument is object with default encoding, with object writes, objectMode first, sync', testGeneratorNextEncoding, foobarObject, 'utf8', true, false, 'Object', execaSync);159+test('Next generator argument is object with default encoding, with object writes, objectMode both, sync', testGeneratorNextEncoding, foobarObject, 'utf8', true, true, 'Object', execaSync);160+161+const testFirstOutputGeneratorArgument = async (t, fdNumber, execaMethod) => {162+ const lines = [];163+ await execaMethod('noop-fd.js', [`${fdNumber}`], getStdio(fdNumber, getTypeofGenerator(lines)(true)));164+ assertTypeofChunk(t, lines, 'String');165+};166+167+test('The first generator with result.stdout does not receive an object argument even in objectMode', testFirstOutputGeneratorArgument, 1, execa);168+test('The first generator with result.stderr does not receive an object argument even in objectMode', testFirstOutputGeneratorArgument, 2, execa);169+test('The first generator with result.stdio[*] does not receive an object argument even in objectMode', testFirstOutputGeneratorArgument, 3, execa);170+test('The first generator with result.stdout does not receive an object argument even in objectMode, sync', testFirstOutputGeneratorArgument, 1, execaSync);171+test('The first generator with result.stderr does not receive an object argument even in objectMode, sync', testFirstOutputGeneratorArgument, 2, execaSync);172+test('The first generator with result.stdio[*] does not receive an object argument even in objectMode, sync', testFirstOutputGeneratorArgument, 3, execaSync);added:test/transform/generator-all.js+224 added
1+import {Buffer} from 'node:buffer';2+import test from 'ava';3+import {execa, execaSync} from '../../index.js';4+import {setFixtureDir} from '../helpers/fixtures-dir.js';5+import {foobarObject} from '../helpers/input.js';6+import {7+ outputObjectGenerator,8+ uppercaseGenerator,9+ uppercaseBufferGenerator,10+} from '../helpers/generator.js';11+12+setFixtureDir();13+14+const textEncoder = new TextEncoder();15+16+const getAllStdioOption = (stdioOption, encoding, objectMode) => {17+ if (stdioOption) {18+ return 'pipe';19+ }20+21+ if (objectMode) {22+ return outputObjectGenerator();23+ }24+25+ return encoding === 'utf8' ? uppercaseGenerator() : uppercaseBufferGenerator();26+};27+28+const getStdoutStderrOutput = ({output, stdioOption, encoding, objectMode, lines}) => {29+ if (objectMode && !stdioOption) {30+ return encoding === 'utf8' ? [foobarObject, foobarObject] : [foobarObject];31+ }32+33+ const stdioOutput = stdioOption ? output : output.toUpperCase();34+35+ if (encoding === 'hex') {36+ return Buffer.from(stdioOutput).toString('hex');37+ }38+39+ if (encoding === 'buffer') {40+ return textEncoder.encode(stdioOutput);41+ }42+43+ return lines ? stdioOutput.trim().split('\n').map(string => `${string}\n`) : stdioOutput;44+};45+46+const getAllOutput = ({stdoutOutput, stderrOutput, encoding, objectMode, lines}) => {47+ if (objectMode || (lines && encoding === 'utf8')) {48+ return [stdoutOutput, stderrOutput].flat();49+ }50+51+ return encoding === 'buffer'52+ ? new Uint8Array([...stdoutOutput, ...stderrOutput])53+ : `${stdoutOutput}${stderrOutput}`;54+};55+56+// eslint-disable-next-line max-params57+const testGeneratorAll = async (t, reject, encoding, objectMode, stdoutOption, stderrOption, lines, execaMethod) => {58+ const fixtureName = reject ? 'all.js' : 'all-fail.js';59+ const {stdout, stderr, all} = await execaMethod(fixtureName, {60+ all: true,61+ reject,62+ stdout: getAllStdioOption(stdoutOption, encoding, objectMode),63+ stderr: getAllStdioOption(stderrOption, encoding, objectMode),64+ encoding,65+ lines,66+ stripFinalNewline: false,67+ });68+69+ const stdoutOutput = getStdoutStderrOutput({output: 'std\nout\n', stdioOption: stdoutOption, encoding, objectMode, lines});70+ t.deepEqual(stdout, stdoutOutput);71+ const stderrOutput = getStdoutStderrOutput({output: 'std\nerr\n', stdioOption: stderrOption, encoding, objectMode, lines});72+ t.deepEqual(stderr, stderrOutput);73+ const allOutput = getAllOutput({stdoutOutput, stderrOutput, encoding, objectMode, lines});74+ if (Array.isArray(all) && Array.isArray(allOutput)) {75+ t.deepEqual([...all].sort(), [...allOutput].sort());76+ } else {77+ t.deepEqual(all, allOutput);78+ }79+};80+81+test('Can use generators with result.all = transform + transform', testGeneratorAll, true, 'utf8', false, false, false, false, execa);82+test('Can use generators with error.all = transform + transform', testGeneratorAll, false, 'utf8', false, false, false, false, execa);83+test('Can use generators with result.all = transform + transform, encoding "buffer"', testGeneratorAll, true, 'buffer', false, false, false, false, execa);84+test('Can use generators with error.all = transform + transform, encoding "buffer"', testGeneratorAll, false, 'buffer', false, false, false, false, execa);85+test('Can use generators with result.all = transform + transform, encoding "hex"', testGeneratorAll, true, 'hex', false, false, false, false, execa);86+test('Can use generators with error.all = transform + transform, encoding "hex"', testGeneratorAll, false, 'hex', false, false, false, false, execa);87+test('Can use generators with result.all = transform + pipe', testGeneratorAll, true, 'utf8', false, false, true, false, execa);88+test('Can use generators with error.all = transform + pipe', testGeneratorAll, false, 'utf8', false, false, true, false, execa);89+test('Can use generators with result.all = transform + pipe, encoding "buffer"', testGeneratorAll, true, 'buffer', false, false, true, false, execa);90+test('Can use generators with error.all = transform + pipe, encoding "buffer"', testGeneratorAll, false, 'buffer', false, false, true, false, execa);91+test('Can use generators with result.all = transform + pipe, encoding "hex"', testGeneratorAll, true, 'hex', false, false, true, false, execa);92+test('Can use generators with error.all = transform + pipe, encoding "hex"', testGeneratorAll, false, 'hex', false, false, true, false, execa);93+test('Can use generators with result.all = pipe + transform', testGeneratorAll, true, 'utf8', false, true, false, false, execa);94+test('Can use generators with error.all = pipe + transform', testGeneratorAll, false, 'utf8', false, true, false, false, execa);95+test('Can use generators with result.all = pipe + transform, encoding "buffer"', testGeneratorAll, true, 'buffer', false, true, false, false, execa);96+test('Can use generators with error.all = pipe + transform, encoding "buffer"', testGeneratorAll, false, 'buffer', false, true, false, false, execa);97+test('Can use generators with result.all = pipe + transform, encoding "hex"', testGeneratorAll, true, 'hex', false, true, false, false, execa);98+test('Can use generators with error.all = pipe + transform, encoding "hex"', testGeneratorAll, false, 'hex', false, true, false, false, execa);99+test('Can use generators with result.all = transform + transform, objectMode', testGeneratorAll, true, 'utf8', true, false, false, false, execa);100+test('Can use generators with error.all = transform + transform, objectMode', testGeneratorAll, false, 'utf8', true, false, false, false, execa);101+test('Can use generators with result.all = transform + transform, objectMode, encoding "buffer"', testGeneratorAll, true, 'buffer', true, false, false, false, execa);102+test('Can use generators with error.all = transform + transform, objectMode, encoding "buffer"', testGeneratorAll, false, 'buffer', true, false, false, false, execa);103+test('Can use generators with result.all = transform + transform, objectMode, encoding "hex"', testGeneratorAll, true, 'hex', true, false, false, false, execa);104+test('Can use generators with error.all = transform + transform, objectMode, encoding "hex"', testGeneratorAll, false, 'hex', true, false, false, false, execa);105+test('Can use generators with result.all = transform + pipe, objectMode', testGeneratorAll, true, 'utf8', true, false, true, false, execa);106+test('Can use generators with error.all = transform + pipe, objectMode', testGeneratorAll, false, 'utf8', true, false, true, false, execa);107+test('Can use generators with result.all = transform + pipe, objectMode, encoding "buffer"', testGeneratorAll, true, 'buffer', true, false, true, false, execa);108+test('Can use generators with error.all = transform + pipe, objectMode, encoding "buffer"', testGeneratorAll, false, 'buffer', true, false, true, false, execa);109+test('Can use generators with result.all = transform + pipe, objectMode, encoding "hex"', testGeneratorAll, true, 'hex', true, false, true, false, execa);110+test('Can use generators with error.all = transform + pipe, objectMode, encoding "hex"', testGeneratorAll, false, 'hex', true, false, true, false, execa);111+test('Can use generators with result.all = pipe + transform, objectMode', testGeneratorAll, true, 'utf8', true, true, false, false, execa);112+test('Can use generators with error.all = pipe + transform, objectMode', testGeneratorAll, false, 'utf8', true, true, false, false, execa);113+test('Can use generators with result.all = pipe + transform, objectMode, encoding "buffer"', testGeneratorAll, true, 'buffer', true, true, false, false, execa);114+test('Can use generators with error.all = pipe + transform, objectMode, encoding "buffer"', testGeneratorAll, false, 'buffer', true, true, false, false, execa);115+test('Can use generators with result.all = pipe + transform, objectMode, encoding "hex"', testGeneratorAll, true, 'hex', true, true, false, false, execa);116+test('Can use generators with error.all = pipe + transform, objectMode, encoding "hex"', testGeneratorAll, false, 'hex', true, true, false, false, execa);117+test('Can use generators with result.all = transform + transform, sync', testGeneratorAll, true, 'utf8', false, false, false, false, execaSync);118+test('Can use generators with error.all = transform + transform, sync', testGeneratorAll, false, 'utf8', false, false, false, false, execaSync);119+test('Can use generators with result.all = transform + transform, encoding "buffer", sync', testGeneratorAll, true, 'buffer', false, false, false, false, execaSync);120+test('Can use generators with error.all = transform + transform, encoding "buffer", sync', testGeneratorAll, false, 'buffer', false, false, false, false, execaSync);121+test('Can use generators with result.all = transform + transform, encoding "hex", sync', testGeneratorAll, true, 'hex', false, false, false, false, execaSync);122+test('Can use generators with error.all = transform + transform, encoding "hex", sync', testGeneratorAll, false, 'hex', false, false, false, false, execaSync);123+test('Can use generators with result.all = transform + pipe, sync', testGeneratorAll, true, 'utf8', false, false, true, false, execaSync);124+test('Can use generators with error.all = transform + pipe, sync', testGeneratorAll, false, 'utf8', false, false, true, false, execaSync);125+test('Can use generators with result.all = transform + pipe, encoding "buffer", sync', testGeneratorAll, true, 'buffer', false, false, true, false, execaSync);126+test('Can use generators with error.all = transform + pipe, encoding "buffer", sync', testGeneratorAll, false, 'buffer', false, false, true, false, execaSync);127+test('Can use generators with result.all = transform + pipe, encoding "hex", sync', testGeneratorAll, true, 'hex', false, false, true, false, execaSync);128+test('Can use generators with error.all = transform + pipe, encoding "hex", sync', testGeneratorAll, false, 'hex', false, false, true, false, execaSync);129+test('Can use generators with result.all = pipe + transform, sync', testGeneratorAll, true, 'utf8', false, true, false, false, execaSync);130+test('Can use generators with error.all = pipe + transform, sync', testGeneratorAll, false, 'utf8', false, true, false, false, execaSync);131+test('Can use generators with result.all = pipe + transform, encoding "buffer", sync', testGeneratorAll, true, 'buffer', false, true, false, false, execaSync);132+test('Can use generators with error.all = pipe + transform, encoding "buffer", sync', testGeneratorAll, false, 'buffer', false, true, false, false, execaSync);133+test('Can use generators with result.all = pipe + transform, encoding "hex", sync', testGeneratorAll, true, 'hex', false, true, false, false, execaSync);134+test('Can use generators with error.all = pipe + transform, encoding "hex", sync', testGeneratorAll, false, 'hex', false, true, false, false, execaSync);135+test('Can use generators with result.all = transform + transform, objectMode, sync', testGeneratorAll, true, 'utf8', true, false, false, false, execaSync);136+test('Can use generators with error.all = transform + transform, objectMode, sync', testGeneratorAll, false, 'utf8', true, false, false, false, execaSync);137+test('Can use generators with result.all = transform + transform, objectMode, encoding "buffer", sync', testGeneratorAll, true, 'buffer', true, false, false, false, execaSync);138+test('Can use generators with error.all = transform + transform, objectMode, encoding "buffer", sync', testGeneratorAll, false, 'buffer', true, false, false, false, execaSync);139+test('Can use generators with result.all = transform + transform, objectMode, encoding "hex", sync', testGeneratorAll, true, 'hex', true, false, false, false, execaSync);140+test('Can use generators with error.all = transform + transform, objectMode, encoding "hex", sync', testGeneratorAll, false, 'hex', true, false, false, false, execaSync);141+test('Can use generators with result.all = transform + pipe, objectMode, sync', testGeneratorAll, true, 'utf8', true, false, true, false, execaSync);142+test('Can use generators with error.all = transform + pipe, objectMode, sync', testGeneratorAll, false, 'utf8', true, false, true, false, execaSync);143+test('Can use generators with result.all = transform + pipe, objectMode, encoding "buffer", sync', testGeneratorAll, true, 'buffer', true, false, true, false, execaSync);144+test('Can use generators with error.all = transform + pipe, objectMode, encoding "buffer", sync', testGeneratorAll, false, 'buffer', true, false, true, false, execaSync);145+test('Can use generators with result.all = transform + pipe, objectMode, encoding "hex", sync', testGeneratorAll, true, 'hex', true, false, true, false, execaSync);146+test('Can use generators with error.all = transform + pipe, objectMode, encoding "hex", sync', testGeneratorAll, false, 'hex', true, false, true, false, execaSync);147+test('Can use generators with result.all = pipe + transform, objectMode, sync', testGeneratorAll, true, 'utf8', true, true, false, false, execaSync);148+test('Can use generators with error.all = pipe + transform, objectMode, sync', testGeneratorAll, false, 'utf8', true, true, false, false, execaSync);149+test('Can use generators with result.all = pipe + transform, objectMode, encoding "buffer", sync', testGeneratorAll, true, 'buffer', true, true, false, false, execaSync);150+test('Can use generators with error.all = pipe + transform, objectMode, encoding "buffer", sync', testGeneratorAll, false, 'buffer', true, true, false, false, execaSync);151+test('Can use generators with result.all = pipe + transform, objectMode, encoding "hex", sync', testGeneratorAll, true, 'hex', true, true, false, false, execaSync);152+test('Can use generators with error.all = pipe + transform, objectMode, encoding "hex", sync', testGeneratorAll, false, 'hex', true, true, false, false, execaSync);153+test('Can use generators with result.all = transform + transform, lines', testGeneratorAll, true, 'utf8', false, false, false, true, execa);154+test('Can use generators with error.all = transform + transform, lines', testGeneratorAll, false, 'utf8', false, false, false, true, execa);155+test('Can use generators with result.all = transform + transform, encoding "buffer", lines', testGeneratorAll, true, 'buffer', false, false, false, true, execa);156+test('Can use generators with error.all = transform + transform, encoding "buffer", lines', testGeneratorAll, false, 'buffer', false, false, false, true, execa);157+test('Can use generators with result.all = transform + transform, encoding "hex", lines', testGeneratorAll, true, 'hex', false, false, false, true, execa);158+test('Can use generators with error.all = transform + transform, encoding "hex", lines', testGeneratorAll, false, 'hex', false, false, false, true, execa);159+test('Can use generators with result.all = transform + pipe, lines', testGeneratorAll, true, 'utf8', false, false, true, true, execa);160+test('Can use generators with error.all = transform + pipe, lines', testGeneratorAll, false, 'utf8', false, false, true, true, execa);161+test('Can use generators with result.all = transform + pipe, encoding "buffer", lines', testGeneratorAll, true, 'buffer', false, false, true, true, execa);162+test('Can use generators with error.all = transform + pipe, encoding "buffer", lines', testGeneratorAll, false, 'buffer', false, false, true, true, execa);163+test('Can use generators with result.all = transform + pipe, encoding "hex", lines', testGeneratorAll, true, 'hex', false, false, true, true, execa);164+test('Can use generators with error.all = transform + pipe, encoding "hex", lines', testGeneratorAll, false, 'hex', false, false, true, true, execa);165+test('Can use generators with result.all = pipe + transform, lines', testGeneratorAll, true, 'utf8', false, true, false, true, execa);166+test('Can use generators with error.all = pipe + transform, lines', testGeneratorAll, false, 'utf8', false, true, false, true, execa);167+test('Can use generators with result.all = pipe + transform, encoding "buffer", lines', testGeneratorAll, true, 'buffer', false, true, false, true, execa);168+test('Can use generators with error.all = pipe + transform, encoding "buffer", lines', testGeneratorAll, false, 'buffer', false, true, false, true, execa);169+test('Can use generators with result.all = pipe + transform, encoding "hex", lines', testGeneratorAll, true, 'hex', false, true, false, true, execa);170+test('Can use generators with error.all = pipe + transform, encoding "hex", lines', testGeneratorAll, false, 'hex', false, true, false, true, execa);171+test('Can use generators with result.all = transform + transform, objectMode, lines', testGeneratorAll, true, 'utf8', true, false, false, true, execa);172+test('Can use generators with error.all = transform + transform, objectMode, lines', testGeneratorAll, false, 'utf8', true, false, false, true, execa);173+test('Can use generators with result.all = transform + transform, objectMode, encoding "buffer", lines', testGeneratorAll, true, 'buffer', true, false, false, true, execa);174+test('Can use generators with error.all = transform + transform, objectMode, encoding "buffer", lines', testGeneratorAll, false, 'buffer', true, false, false, true, execa);175+test('Can use generators with result.all = transform + transform, objectMode, encoding "hex", lines', testGeneratorAll, true, 'hex', true, false, false, true, execa);176+test('Can use generators with error.all = transform + transform, objectMode, encoding "hex", lines', testGeneratorAll, false, 'hex', true, false, false, true, execa);177+test('Can use generators with result.all = transform + pipe, objectMode, lines', testGeneratorAll, true, 'utf8', true, false, true, true, execa);178+test('Can use generators with error.all = transform + pipe, objectMode, lines', testGeneratorAll, false, 'utf8', true, false, true, true, execa);179+test('Can use generators with result.all = transform + pipe, objectMode, encoding "buffer", lines', testGeneratorAll, true, 'buffer', true, false, true, true, execa);180+test('Can use generators with error.all = transform + pipe, objectMode, encoding "buffer", lines', testGeneratorAll, false, 'buffer', true, false, true, true, execa);181+test('Can use generators with result.all = transform + pipe, objectMode, encoding "hex", lines', testGeneratorAll, true, 'hex', true, false, true, true, execa);182+test('Can use generators with error.all = transform + pipe, objectMode, encoding "hex", lines', testGeneratorAll, false, 'hex', true, false, true, true, execa);183+test('Can use generators with result.all = pipe + transform, objectMode, lines', testGeneratorAll, true, 'utf8', true, true, false, true, execa);184+test('Can use generators with error.all = pipe + transform, objectMode, lines', testGeneratorAll, false, 'utf8', true, true, false, true, execa);185+test('Can use generators with result.all = pipe + transform, objectMode, encoding "buffer", lines', testGeneratorAll, true, 'buffer', true, true, false, true, execa);186+test('Can use generators with error.all = pipe + transform, objectMode, encoding "buffer", lines', testGeneratorAll, false, 'buffer', true, true, false, true, execa);187+test('Can use generators with result.all = pipe + transform, objectMode, encoding "hex", lines', testGeneratorAll, true, 'hex', true, true, false, true, execa);188+test('Can use generators with error.all = pipe + transform, objectMode, encoding "hex", lines', testGeneratorAll, false, 'hex', true, true, false, true, execa);189+test('Can use generators with result.all = transform + transform, sync, lines', testGeneratorAll, true, 'utf8', false, false, false, true, execaSync);190+test('Can use generators with error.all = transform + transform, sync, lines', testGeneratorAll, false, 'utf8', false, false, false, true, execaSync);191+test('Can use generators with result.all = transform + transform, encoding "buffer", sync, lines', testGeneratorAll, true, 'buffer', false, false, false, true, execaSync);192+test('Can use generators with error.all = transform + transform, encoding "buffer", sync, lines', testGeneratorAll, false, 'buffer', false, false, false, true, execaSync);193+test('Can use generators with result.all = transform + transform, encoding "hex", sync, lines', testGeneratorAll, true, 'hex', false, false, false, true, execaSync);194+test('Can use generators with error.all = transform + transform, encoding "hex", sync, lines', testGeneratorAll, false, 'hex', false, false, false, true, execaSync);195+test('Can use generators with result.all = transform + pipe, sync, lines', testGeneratorAll, true, 'utf8', false, false, true, true, execaSync);196+test('Can use generators with error.all = transform + pipe, sync, lines', testGeneratorAll, false, 'utf8', false, false, true, true, execaSync);197+test('Can use generators with result.all = transform + pipe, encoding "buffer", sync, lines', testGeneratorAll, true, 'buffer', false, false, true, true, execaSync);198+test('Can use generators with error.all = transform + pipe, encoding "buffer", sync, lines', testGeneratorAll, false, 'buffer', false, false, true, true, execaSync);199+test('Can use generators with result.all = transform + pipe, encoding "hex", sync, lines', testGeneratorAll, true, 'hex', false, false, true, true, execaSync);200+test('Can use generators with error.all = transform + pipe, encoding "hex", sync, lines', testGeneratorAll, false, 'hex', false, false, true, true, execaSync);201+test('Can use generators with result.all = pipe + transform, sync, lines', testGeneratorAll, true, 'utf8', false, true, false, true, execaSync);202+test('Can use generators with error.all = pipe + transform, sync, lines', testGeneratorAll, false, 'utf8', false, true, false, true, execaSync);203+test('Can use generators with result.all = pipe + transform, encoding "buffer", sync, lines', testGeneratorAll, true, 'buffer', false, true, false, true, execaSync);204+test('Can use generators with error.all = pipe + transform, encoding "buffer", sync, lines', testGeneratorAll, false, 'buffer', false, true, false, true, execaSync);205+test('Can use generators with result.all = pipe + transform, encoding "hex", sync, lines', testGeneratorAll, true, 'hex', false, true, false, true, execaSync);206+test('Can use generators with error.all = pipe + transform, encoding "hex", sync, lines', testGeneratorAll, false, 'hex', false, true, false, true, execaSync);207+test('Can use generators with result.all = transform + transform, objectMode, sync, lines', testGeneratorAll, true, 'utf8', true, false, false, true, execaSync);208+test('Can use generators with error.all = transform + transform, objectMode, sync, lines', testGeneratorAll, false, 'utf8', true, false, false, true, execaSync);209+test('Can use generators with result.all = transform + transform, objectMode, encoding "buffer", sync, lines', testGeneratorAll, true, 'buffer', true, false, false, true, execaSync);210+test('Can use generators with error.all = transform + transform, objectMode, encoding "buffer", sync, lines', testGeneratorAll, false, 'buffer', true, false, false, true, execaSync);211+test('Can use generators with result.all = transform + transform, objectMode, encoding "hex", sync, lines', testGeneratorAll, true, 'hex', true, false, false, true, execaSync);212+test('Can use generators with error.all = transform + transform, objectMode, encoding "hex", sync, lines', testGeneratorAll, false, 'hex', true, false, false, true, execaSync);213+test('Can use generators with result.all = transform + pipe, objectMode, sync, lines', testGeneratorAll, true, 'utf8', true, false, true, true, execaSync);214+test('Can use generators with error.all = transform + pipe, objectMode, sync, lines', testGeneratorAll, false, 'utf8', true, false, true, true, execaSync);215+test('Can use generators with result.all = transform + pipe, objectMode, encoding "buffer", sync, lines', testGeneratorAll, true, 'buffer', true, false, true, true, execaSync);216+test('Can use generators with error.all = transform + pipe, objectMode, encoding "buffer", sync, lines', testGeneratorAll, false, 'buffer', true, false, true, true, execaSync);217+test('Can use generators with result.all = transform + pipe, objectMode, encoding "hex", sync, lines', testGeneratorAll, true, 'hex', true, false, true, true, execaSync);218+test('Can use generators with error.all = transform + pipe, objectMode, encoding "hex", sync, lines', testGeneratorAll, false, 'hex', true, false, true, true, execaSync);219+test('Can use generators with result.all = pipe + transform, objectMode, sync, lines', testGeneratorAll, true, 'utf8', true, true, false, true, execaSync);220+test('Can use generators with error.all = pipe + transform, objectMode, sync, lines', testGeneratorAll, false, 'utf8', true, true, false, true, execaSync);221+test('Can use generators with result.all = pipe + transform, objectMode, encoding "buffer", sync, lines', testGeneratorAll, true, 'buffer', true, true, false, true, execaSync);222+test('Can use generators with error.all = pipe + transform, objectMode, encoding "buffer", sync, lines', testGeneratorAll, false, 'buffer', true, true, false, true, execaSync);223+test('Can use generators with result.all = pipe + transform, objectMode, encoding "hex", sync, lines', testGeneratorAll, true, 'hex', true, true, false, true, execaSync);224+test('Can use generators with error.all = pipe + transform, objectMode, encoding "hex", sync, lines', testGeneratorAll, false, 'hex', true, true, false, true, execaSync);added:test/transform/generator-error.js+89 added
1+import {once} from 'node:events';2+import test from 'ava';3+import {execa, execaSync} from '../../index.js';4+import {foobarString} from '../helpers/input.js';5+import {noopGenerator, infiniteGenerator, convertTransformToFinal} from '../helpers/generator.js';6+import {generatorsMap} from '../helpers/map.js';7+import {setFixtureDir} from '../helpers/fixtures-dir.js';8+9+setFixtureDir();10+11+const assertProcessError = async (t, type, execaMethod, getSubprocess) => {12+ const cause = new Error(foobarString);13+ const transform = generatorsMap[type].throwing(cause)();14+ const error = execaMethod === execa15+ ? await t.throwsAsync(getSubprocess(transform))16+ : t.throws(() => {17+ getSubprocess(transform);18+ });19+ t.is(error.cause, cause);20+};21+22+const testThrowingGenerator = async (t, type, final, execaMethod) => {23+ await assertProcessError(t, type, execaMethod, transform => execaMethod('noop.js', {24+ stdout: convertTransformToFinal(transform, final),25+ }));26+};27+28+test('Generators "transform" errors make subprocess fail', testThrowingGenerator, 'generator', false, execa);29+test('Generators "final" errors make subprocess fail', testThrowingGenerator, 'generator', true, execa);30+test('Generators "transform" errors make subprocess fail, sync', testThrowingGenerator, 'generator', false, execaSync);31+test('Generators "final" errors make subprocess fail, sync', testThrowingGenerator, 'generator', true, execaSync);32+test('Duplexes "transform" errors make subprocess fail', testThrowingGenerator, 'duplex', false, execa);33+test('WebTransform "transform" errors make subprocess fail', testThrowingGenerator, 'webTransform', false, execa);34+35+const testSingleErrorOutput = async (t, type, execaMethod) => {36+ await assertProcessError(t, type, execaMethod, transform => execaMethod('noop.js', {37+ stdout: [38+ generatorsMap[type].noop(false),39+ transform,40+ generatorsMap[type].noop(false),41+ ],42+ }));43+};44+45+test('Generators errors make subprocess fail even when other output generators do not throw', testSingleErrorOutput, 'generator', execa);46+test('Generators errors make subprocess fail even when other output generators do not throw, sync', testSingleErrorOutput, 'generator', execaSync);47+test('Duplexes errors make subprocess fail even when other output generators do not throw', testSingleErrorOutput, 'duplex', execa);48+test('WebTransform errors make subprocess fail even when other output generators do not throw', testSingleErrorOutput, 'webTransform', execa);49+50+const testSingleErrorInput = async (t, type, execaMethod) => {51+ await assertProcessError(t, type, execaMethod, transform => execaMethod('stdin.js', {52+ stdin: [53+ ['foobar\n'],54+ generatorsMap[type].noop(false),55+ transform,56+ generatorsMap[type].noop(false),57+ ],58+ }));59+};60+61+test('Generators errors make subprocess fail even when other input generators do not throw', testSingleErrorInput, 'generator', execa);62+test('Generators errors make subprocess fail even when other input generators do not throw, sync', testSingleErrorInput, 'generator', execaSync);63+test('Duplexes errors make subprocess fail even when other input generators do not throw', testSingleErrorInput, 'duplex', execa);64+test('WebTransform errors make subprocess fail even when other input generators do not throw', testSingleErrorInput, 'webTransform', execa);65+66+const testGeneratorCancel = async (t, error) => {67+ const subprocess = execa('noop.js', {stdout: infiniteGenerator()});68+ await once(subprocess.stdout, 'data');69+ subprocess.stdout.destroy(error);70+ await (error === undefined ? t.notThrowsAsync(subprocess) : t.throwsAsync(subprocess));71+};72+73+test('Running generators are canceled on subprocess abort', testGeneratorCancel, undefined);74+test('Running generators are canceled on subprocess error', testGeneratorCancel, new Error('test'));75+76+const testGeneratorDestroy = async (t, transform) => {77+ const subprocess = execa('forever.js', {stdout: transform});78+ const cause = new Error('test');79+ subprocess.stdout.destroy(cause);80+ subprocess.kill();81+ t.like(await t.throwsAsync(subprocess), {cause});82+};83+84+test('Generators are destroyed on subprocess error, sync', testGeneratorDestroy, noopGenerator(false));85+test('Generators are destroyed on subprocess error, async', testGeneratorDestroy, infiniteGenerator());86+87+test('Generators are destroyed on early subprocess exit', async t => {88+ await t.throwsAsync(execa('noop.js', {stdout: infiniteGenerator(), uid: -1}));89+});added:test/transform/generator-final.js+35 added
1+import test from 'ava';2+import {execa, execaSync} from '../../index.js';3+import {foobarString} from '../helpers/input.js';4+import {getOutputAsyncGenerator, getOutputGenerator, convertTransformToFinal} from '../helpers/generator.js';5+import {setFixtureDir} from '../helpers/fixtures-dir.js';6+7+setFixtureDir();8+9+const testGeneratorFinal = async (t, fixtureName, execaMethod) => {10+ const {stdout} = await execaMethod(fixtureName, {stdout: convertTransformToFinal(getOutputGenerator(foobarString)(), true)});11+ t.is(stdout, foobarString);12+};13+14+test('Generators "final" can be used', testGeneratorFinal, 'noop.js', execa);15+test('Generators "final" is used even on empty streams', testGeneratorFinal, 'empty.js', execa);16+test('Generators "final" can be used, sync', testGeneratorFinal, 'noop.js', execaSync);17+test('Generators "final" is used even on empty streams, sync', testGeneratorFinal, 'empty.js', execaSync);18+19+const testFinalAlone = async (t, final, execaMethod) => {20+ const {stdout} = await execaMethod('noop-fd.js', ['1', '.'], {stdout: {final: final(foobarString)().transform, binary: true}});21+ t.is(stdout, `.${foobarString}`);22+};23+24+test('Generators "final" can be used without "transform"', testFinalAlone, getOutputGenerator, execa);25+test('Generators "final" can be used without "transform", sync', testFinalAlone, getOutputGenerator, execaSync);26+test('Generators "final" can be used without "transform", async', testFinalAlone, getOutputAsyncGenerator, execa);27+28+const testFinalNoOutput = async (t, final, execaMethod) => {29+ const {stdout} = await execaMethod('empty.js', {stdout: {final: final(foobarString)().transform}});30+ t.is(stdout, foobarString);31+};32+33+test('Generators "final" can be used without "transform" nor output', testFinalNoOutput, getOutputGenerator, execa);34+test('Generators "final" can be used without "transform" nor output, sync', testFinalNoOutput, getOutputGenerator, execaSync);35+test('Generators "final" can be used without "transform" nor output, async', testFinalNoOutput, getOutputAsyncGenerator, execa);added:test/transform/generator-input.js+158 added
1+import {Buffer} from 'node:buffer';2+import test from 'ava';3+import {execa, execaSync} from '../../index.js';4+import {setFixtureDir} from '../helpers/fixtures-dir.js';5+import {getStdio} from '../helpers/stdio.js';6+import {7+ foobarString,8+ foobarUppercase,9+ foobarHex,10+ foobarUint8Array,11+ foobarBuffer,12+ foobarObject,13+ foobarObjectString,14+} from '../helpers/input.js';15+import {generatorsMap} from '../helpers/map.js';16+17+setFixtureDir();18+19+const getInputObjectMode = (objectMode, addNoopTransform, type) => objectMode20+ ? {21+ input: [foobarObject],22+ generators: generatorsMap[type].addNoop(generatorsMap[type].serialize(objectMode), addNoopTransform, objectMode),23+ output: foobarObjectString,24+ }25+ : {26+ input: foobarUint8Array,27+ generators: generatorsMap[type].addNoop(generatorsMap[type].uppercase(objectMode), addNoopTransform, objectMode),28+ output: foobarUppercase,29+ };30+31+// eslint-disable-next-line max-params32+const testGeneratorInput = async (t, fdNumber, objectMode, addNoopTransform, type, execaMethod) => {33+ const {input, generators, output} = getInputObjectMode(objectMode, addNoopTransform, type);34+ const {stdout} = await execaMethod('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, [input, ...generators]));35+ t.is(stdout, output);36+};37+38+test('Can use generators with result.stdin', testGeneratorInput, 0, false, false, 'generator', execa);39+test('Can use generators with result.stdio[*] as input', testGeneratorInput, 3, false, false, 'generator', execa);40+test('Can use generators with result.stdin, objectMode', testGeneratorInput, 0, true, false, 'generator', execa);41+test('Can use generators with result.stdio[*] as input, objectMode', testGeneratorInput, 3, true, false, 'generator', execa);42+test('Can use generators with result.stdin, noop transform', testGeneratorInput, 0, false, true, 'generator', execa);43+test('Can use generators with result.stdio[*] as input, noop transform', testGeneratorInput, 3, false, true, 'generator', execa);44+test('Can use generators with result.stdin, objectMode, noop transform', testGeneratorInput, 0, true, true, 'generator', execa);45+test('Can use generators with result.stdio[*] as input, objectMode, noop transform', testGeneratorInput, 3, true, true, 'generator', execa);46+test('Can use generators with result.stdin, sync', testGeneratorInput, 0, false, false, 'generator', execaSync);47+test('Can use generators with result.stdin, objectMode, sync', testGeneratorInput, 0, true, false, 'generator', execaSync);48+test('Can use generators with result.stdin, noop transform, sync', testGeneratorInput, 0, false, true, 'generator', execaSync);49+test('Can use generators with result.stdin, objectMode, noop transform, sync', testGeneratorInput, 0, true, true, 'generator', execaSync);50+test('Can use duplexes with result.stdin', testGeneratorInput, 0, false, false, 'duplex', execa);51+test('Can use duplexes with result.stdio[*] as input', testGeneratorInput, 3, false, false, 'duplex', execa);52+test('Can use duplexes with result.stdin, objectMode', testGeneratorInput, 0, true, false, 'duplex', execa);53+test('Can use duplexes with result.stdio[*] as input, objectMode', testGeneratorInput, 3, true, false, 'duplex', execa);54+test('Can use duplexes with result.stdin, noop transform', testGeneratorInput, 0, false, true, 'duplex', execa);55+test('Can use duplexes with result.stdio[*] as input, noop transform', testGeneratorInput, 3, false, true, 'duplex', execa);56+test('Can use duplexes with result.stdin, objectMode, noop transform', testGeneratorInput, 0, true, true, 'duplex', execa);57+test('Can use duplexes with result.stdio[*] as input, objectMode, noop transform', testGeneratorInput, 3, true, true, 'duplex', execa);58+test('Can use webTransforms with result.stdin', testGeneratorInput, 0, false, false, 'webTransform', execa);59+test('Can use webTransforms with result.stdio[*] as input', testGeneratorInput, 3, false, false, 'webTransform', execa);60+test('Can use webTransforms with result.stdin, objectMode', testGeneratorInput, 0, true, false, 'webTransform', execa);61+test('Can use webTransforms with result.stdio[*] as input, objectMode', testGeneratorInput, 3, true, false, 'webTransform', execa);62+test('Can use webTransforms with result.stdin, noop transform', testGeneratorInput, 0, false, true, 'webTransform', execa);63+test('Can use webTransforms with result.stdio[*] as input, noop transform', testGeneratorInput, 3, false, true, 'webTransform', execa);64+test('Can use webTransforms with result.stdin, objectMode, noop transform', testGeneratorInput, 0, true, true, 'webTransform', execa);65+test('Can use webTransforms with result.stdio[*] as input, objectMode, noop transform', testGeneratorInput, 3, true, true, 'webTransform', execa);66+67+// eslint-disable-next-line max-params68+const testGeneratorInputPipe = async (t, useShortcutProperty, objectMode, addNoopTransform, type, input) => {69+ const {generators, output} = getInputObjectMode(objectMode, addNoopTransform, type);70+ const subprocess = execa('stdin-fd.js', ['0'], getStdio(0, generators));71+ const stream = useShortcutProperty ? subprocess.stdin : subprocess.stdio[0];72+ stream.end(...input);73+ const {stdout} = await subprocess;74+ const expectedOutput = input[1] === 'utf16le' ? Buffer.from(output, input[1]).toString() : output;75+ t.is(stdout, expectedOutput);76+};77+78+test('Can use generators with subprocess.stdio[0] and default encoding', testGeneratorInputPipe, false, false, false, 'generator', [foobarString, 'utf8']);79+test('Can use generators with subprocess.stdin and default encoding', testGeneratorInputPipe, true, false, false, 'generator', [foobarString, 'utf8']);80+test('Can use generators with subprocess.stdio[0] and encoding "utf16le"', testGeneratorInputPipe, false, false, false, 'generator', [foobarString, 'utf16le']);81+test('Can use generators with subprocess.stdin and encoding "utf16le"', testGeneratorInputPipe, true, false, false, 'generator', [foobarString, 'utf16le']);82+test('Can use generators with subprocess.stdio[0] and encoding "buffer"', testGeneratorInputPipe, false, false, false, 'generator', [foobarBuffer, 'buffer']);83+test('Can use generators with subprocess.stdin and encoding "buffer"', testGeneratorInputPipe, true, false, false, 'generator', [foobarBuffer, 'buffer']);84+test('Can use generators with subprocess.stdio[0] and encoding "hex"', testGeneratorInputPipe, false, false, false, 'generator', [foobarHex, 'hex']);85+test('Can use generators with subprocess.stdin and encoding "hex"', testGeneratorInputPipe, true, false, false, 'generator', [foobarHex, 'hex']);86+test('Can use generators with subprocess.stdio[0], objectMode', testGeneratorInputPipe, false, true, false, 'generator', [foobarObject]);87+test('Can use generators with subprocess.stdin, objectMode', testGeneratorInputPipe, true, true, false, 'generator', [foobarObject]);88+test('Can use generators with subprocess.stdio[0] and default encoding, noop transform', testGeneratorInputPipe, false, false, true, 'generator', [foobarString, 'utf8']);89+test('Can use generators with subprocess.stdin and default encoding, noop transform', testGeneratorInputPipe, true, false, true, 'generator', [foobarString, 'utf8']);90+test('Can use generators with subprocess.stdio[0] and encoding "utf16le", noop transform', testGeneratorInputPipe, false, false, true, 'generator', [foobarString, 'utf16le']);91+test('Can use generators with subprocess.stdin and encoding "utf16le", noop transform', testGeneratorInputPipe, true, false, true, 'generator', [foobarString, 'utf16le']);92+test('Can use generators with subprocess.stdio[0] and encoding "buffer", noop transform', testGeneratorInputPipe, false, false, true, 'generator', [foobarBuffer, 'buffer']);93+test('Can use generators with subprocess.stdin and encoding "buffer", noop transform', testGeneratorInputPipe, true, false, true, 'generator', [foobarBuffer, 'buffer']);94+test('Can use generators with subprocess.stdio[0] and encoding "hex", noop transform', testGeneratorInputPipe, false, false, true, 'generator', [foobarHex, 'hex']);95+test('Can use generators with subprocess.stdin and encoding "hex", noop transform', testGeneratorInputPipe, true, false, true, 'generator', [foobarHex, 'hex']);96+test('Can use generators with subprocess.stdio[0], objectMode, noop transform', testGeneratorInputPipe, false, true, true, 'generator', [foobarObject]);97+test('Can use generators with subprocess.stdin, objectMode, noop transform', testGeneratorInputPipe, true, true, true, 'generator', [foobarObject]);98+test('Can use duplexes with subprocess.stdio[0] and default encoding', testGeneratorInputPipe, false, false, false, 'duplex', [foobarString, 'utf8']);99+test('Can use duplexes with subprocess.stdin and default encoding', testGeneratorInputPipe, true, false, false, 'duplex', [foobarString, 'utf8']);100+test('Can use duplexes with subprocess.stdio[0] and encoding "utf16le"', testGeneratorInputPipe, false, false, false, 'duplex', [foobarString, 'utf16le']);101+test('Can use duplexes with subprocess.stdin and encoding "utf16le"', testGeneratorInputPipe, true, false, false, 'duplex', [foobarString, 'utf16le']);102+test('Can use duplexes with subprocess.stdio[0] and encoding "buffer"', testGeneratorInputPipe, false, false, false, 'duplex', [foobarBuffer, 'buffer']);103+test('Can use duplexes with subprocess.stdin and encoding "buffer"', testGeneratorInputPipe, true, false, false, 'duplex', [foobarBuffer, 'buffer']);104+test('Can use duplexes with subprocess.stdio[0] and encoding "hex"', testGeneratorInputPipe, false, false, false, 'duplex', [foobarHex, 'hex']);105+test('Can use duplexes with subprocess.stdin and encoding "hex"', testGeneratorInputPipe, true, false, false, 'duplex', [foobarHex, 'hex']);106+test('Can use duplexes with subprocess.stdio[0], objectMode', testGeneratorInputPipe, false, true, false, 'duplex', [foobarObject]);107+test('Can use duplexes with subprocess.stdin, objectMode', testGeneratorInputPipe, true, true, false, 'duplex', [foobarObject]);108+test('Can use duplexes with subprocess.stdio[0] and default encoding, noop transform', testGeneratorInputPipe, false, false, true, 'duplex', [foobarString, 'utf8']);109+test('Can use duplexes with subprocess.stdin and default encoding, noop transform', testGeneratorInputPipe, true, false, true, 'duplex', [foobarString, 'utf8']);110+test('Can use duplexes with subprocess.stdio[0] and encoding "utf16le", noop transform', testGeneratorInputPipe, false, false, true, 'duplex', [foobarString, 'utf16le']);111+test('Can use duplexes with subprocess.stdin and encoding "utf16le", noop transform', testGeneratorInputPipe, true, false, true, 'duplex', [foobarString, 'utf16le']);112+test('Can use duplexes with subprocess.stdio[0] and encoding "buffer", noop transform', testGeneratorInputPipe, false, false, true, 'duplex', [foobarBuffer, 'buffer']);113+test('Can use duplexes with subprocess.stdin and encoding "buffer", noop transform', testGeneratorInputPipe, true, false, true, 'duplex', [foobarBuffer, 'buffer']);114+test('Can use duplexes with subprocess.stdio[0] and encoding "hex", noop transform', testGeneratorInputPipe, false, false, true, 'duplex', [foobarHex, 'hex']);115+test('Can use duplexes with subprocess.stdin and encoding "hex", noop transform', testGeneratorInputPipe, true, false, true, 'duplex', [foobarHex, 'hex']);116+test('Can use duplexes with subprocess.stdio[0], objectMode, noop transform', testGeneratorInputPipe, false, true, true, 'duplex', [foobarObject]);117+test('Can use duplexes with subprocess.stdin, objectMode, noop transform', testGeneratorInputPipe, true, true, true, 'duplex', [foobarObject]);118+test('Can use webTransforms with subprocess.stdio[0] and default encoding', testGeneratorInputPipe, false, false, false, 'webTransform', [foobarString, 'utf8']);119+test('Can use webTransforms with subprocess.stdin and default encoding', testGeneratorInputPipe, true, false, false, 'webTransform', [foobarString, 'utf8']);120+test('Can use webTransforms with subprocess.stdio[0] and encoding "utf16le"', testGeneratorInputPipe, false, false, false, 'webTransform', [foobarString, 'utf16le']);121+test('Can use webTransforms with subprocess.stdin and encoding "utf16le"', testGeneratorInputPipe, true, false, false, 'webTransform', [foobarString, 'utf16le']);122+test('Can use webTransforms with subprocess.stdio[0] and encoding "buffer"', testGeneratorInputPipe, false, false, false, 'webTransform', [foobarBuffer, 'buffer']);123+test('Can use webTransforms with subprocess.stdin and encoding "buffer"', testGeneratorInputPipe, true, false, false, 'webTransform', [foobarBuffer, 'buffer']);124+test('Can use webTransforms with subprocess.stdio[0] and encoding "hex"', testGeneratorInputPipe, false, false, false, 'webTransform', [foobarHex, 'hex']);125+test('Can use webTransforms with subprocess.stdin and encoding "hex"', testGeneratorInputPipe, true, false, false, 'webTransform', [foobarHex, 'hex']);126+test('Can use webTransforms with subprocess.stdio[0], objectMode', testGeneratorInputPipe, false, true, false, 'webTransform', [foobarObject]);127+test('Can use webTransforms with subprocess.stdin, objectMode', testGeneratorInputPipe, true, true, false, 'webTransform', [foobarObject]);128+test('Can use webTransforms with subprocess.stdio[0] and default encoding, noop transform', testGeneratorInputPipe, false, false, true, 'webTransform', [foobarString, 'utf8']);129+test('Can use webTransforms with subprocess.stdin and default encoding, noop transform', testGeneratorInputPipe, true, false, true, 'webTransform', [foobarString, 'utf8']);130+test('Can use webTransforms with subprocess.stdio[0] and encoding "utf16le", noop transform', testGeneratorInputPipe, false, false, true, 'webTransform', [foobarString, 'utf16le']);131+test('Can use webTransforms with subprocess.stdin and encoding "utf16le", noop transform', testGeneratorInputPipe, true, false, true, 'webTransform', [foobarString, 'utf16le']);132+test('Can use webTransforms with subprocess.stdio[0] and encoding "buffer", noop transform', testGeneratorInputPipe, false, false, true, 'webTransform', [foobarBuffer, 'buffer']);133+test('Can use webTransforms with subprocess.stdin and encoding "buffer", noop transform', testGeneratorInputPipe, true, false, true, 'webTransform', [foobarBuffer, 'buffer']);134+test('Can use webTransforms with subprocess.stdio[0] and encoding "hex", noop transform', testGeneratorInputPipe, false, false, true, 'webTransform', [foobarHex, 'hex']);135+test('Can use webTransforms with subprocess.stdin and encoding "hex", noop transform', testGeneratorInputPipe, true, false, true, 'webTransform', [foobarHex, 'hex']);136+test('Can use webTransforms with subprocess.stdio[0], objectMode, noop transform', testGeneratorInputPipe, false, true, true, 'webTransform', [foobarObject]);137+test('Can use webTransforms with subprocess.stdin, objectMode, noop transform', testGeneratorInputPipe, true, true, true, 'webTransform', [foobarObject]);138+139+const testGeneratorStdioInputPipe = async (t, objectMode, addNoopTransform, type) => {140+ const {input, generators, output} = getInputObjectMode(objectMode, addNoopTransform, type);141+ const subprocess = execa('stdin-fd.js', ['3'], getStdio(3, [[], ...generators]));142+ subprocess.stdio[3].write(Array.isArray(input) ? input[0] : input);143+ const {stdout} = await subprocess;144+ t.is(stdout, output);145+};146+147+test('Can use generators with subprocess.stdio[*] as input', testGeneratorStdioInputPipe, false, false, 'generator');148+test('Can use generators with subprocess.stdio[*] as input, objectMode', testGeneratorStdioInputPipe, true, false, 'generator');149+test('Can use generators with subprocess.stdio[*] as input, noop transform', testGeneratorStdioInputPipe, false, true, 'generator');150+test('Can use generators with subprocess.stdio[*] as input, objectMode, noop transform', testGeneratorStdioInputPipe, true, true, 'generator');151+test('Can use duplexes with subprocess.stdio[*] as input', testGeneratorStdioInputPipe, false, false, 'duplex');152+test('Can use duplexes with subprocess.stdio[*] as input, objectMode', testGeneratorStdioInputPipe, true, false, 'duplex');153+test('Can use duplexes with subprocess.stdio[*] as input, noop transform', testGeneratorStdioInputPipe, false, true, 'duplex');154+test('Can use duplexes with subprocess.stdio[*] as input, objectMode, noop transform', testGeneratorStdioInputPipe, true, true, 'duplex');155+test('Can use webTransforms with subprocess.stdio[*] as input', testGeneratorStdioInputPipe, false, false, 'webTransform');156+test('Can use webTransforms with subprocess.stdio[*] as input, objectMode', testGeneratorStdioInputPipe, true, false, 'webTransform');157+test('Can use webTransforms with subprocess.stdio[*] as input, noop transform', testGeneratorStdioInputPipe, false, true, 'webTransform');158+test('Can use webTransforms with subprocess.stdio[*] as input, objectMode, noop transform', testGeneratorStdioInputPipe, true, true, 'webTransform');added:test/transform/generator-main.js+185 added
1+import {Buffer} from 'node:buffer';2+import {scheduler} from 'node:timers/promises';3+import test from 'ava';4+import {getStreamAsArray} from 'get-stream';5+import {execa, execaSync} from '../../index.js';6+import {foobarString} from '../helpers/input.js';7+import {8+ noopGenerator,9+ outputObjectGenerator,10+ convertTransformToFinal,11+ prefix,12+ suffix,13+} from '../helpers/generator.js';14+import {generatorsMap} from '../helpers/map.js';15+import {defaultHighWaterMark} from '../helpers/stream.js';16+import {setFixtureDir} from '../helpers/fixtures-dir.js';17+import {maxBuffer, assertErrorMessage} from '../helpers/max-buffer.js';18+19+setFixtureDir();20+21+const repeatCount = defaultHighWaterMark * 3;22+23+const writerGenerator = function * () {24+ for (let index = 0; index < repeatCount; index += 1) {25+ yield '\n';26+ }27+};28+29+const getLengthGenerator = function * (t, chunk) {30+ t.is(chunk.length, 1);31+ yield chunk;32+};33+34+// eslint-disable-next-line max-params35+const testHighWaterMark = async (t, passThrough, binary, objectMode, execaMethod) => {36+ const {stdout} = await execaMethod('noop.js', {37+ stdout: [38+ ...(objectMode ? [outputObjectGenerator()] : []),39+ writerGenerator,40+ ...(passThrough ? [noopGenerator(false, binary)] : []),41+ {transform: getLengthGenerator.bind(undefined, t), preserveNewlines: true, objectMode: true},42+ ],43+ });44+ t.is(stdout.length, repeatCount);45+ t.true(stdout.every(chunk => chunk === '\n'));46+};47+48+test('Synchronous yields are not buffered, no passThrough', testHighWaterMark, false, false, false, execa);49+test('Synchronous yields are not buffered, line-wise passThrough', testHighWaterMark, true, false, false, execa);50+test('Synchronous yields are not buffered, binary passThrough', testHighWaterMark, true, true, false, execa);51+test('Synchronous yields are not buffered, objectMode as input but not output', testHighWaterMark, false, false, true, execa);52+test('Synchronous yields are not buffered, no passThrough, sync', testHighWaterMark, false, false, false, execaSync);53+test('Synchronous yields are not buffered, line-wise passThrough, sync', testHighWaterMark, true, false, false, execaSync);54+test('Synchronous yields are not buffered, binary passThrough, sync', testHighWaterMark, true, true, false, execaSync);55+test('Synchronous yields are not buffered, objectMode as input but not output, sync', testHighWaterMark, false, false, true, execaSync);56+57+// eslint-disable-next-line max-params58+const testNoYield = async (t, type, objectMode, final, output, execaMethod) => {59+ const {stdout} = await execaMethod('noop.js', {stdout: convertTransformToFinal(generatorsMap[type].noYield(objectMode), final)});60+ t.deepEqual(stdout, output);61+};62+63+test('Generator can filter "transform" by not calling yield', testNoYield, 'generator', false, false, '', execa);64+test('Generator can filter "transform" by not calling yield, objectMode', testNoYield, 'generator', true, false, [], execa);65+test('Generator can filter "final" by not calling yield', testNoYield, 'generator', false, true, '', execa);66+test('Generator can filter "final" by not calling yield, objectMode', testNoYield, 'generator', true, true, [], execa);67+test('Generator can filter "transform" by not calling yield, sync', testNoYield, 'generator', false, false, '', execaSync);68+test('Generator can filter "transform" by not calling yield, objectMode, sync', testNoYield, 'generator', true, false, [], execaSync);69+test('Generator can filter "final" by not calling yield, sync', testNoYield, 'generator', false, true, '', execaSync);70+test('Generator can filter "final" by not calling yield, objectMode, sync', testNoYield, 'generator', true, true, [], execaSync);71+test('Duplex can filter by not calling push', testNoYield, 'duplex', false, false, '', execa);72+test('Duplex can filter by not calling push, objectMode', testNoYield, 'duplex', true, false, [], execa);73+test('WebTransform can filter by not calling push', testNoYield, 'webTransform', false, false, '', execa);74+test('WebTransform can filter by not calling push, objectMode', testNoYield, 'webTransform', true, false, [], execa);75+76+const testMultipleYields = async (t, type, final, binary) => {77+ const {stdout} = await execa('noop-fd.js', ['1', foobarString], {stdout: convertTransformToFinal(generatorsMap[type].multipleYield(), final)});78+ const newline = binary ? '' : '\n';79+ t.is(stdout, `${prefix}${newline}${foobarString}${newline}${suffix}`);80+};81+82+test('Generator can yield "transform" multiple times at different moments', testMultipleYields, 'generator', false, false);83+test('Generator can yield "final" multiple times at different moments', testMultipleYields, 'generator', true, false);84+test('Duplex can push multiple times at different moments', testMultipleYields, 'duplex', false, true);85+test('WebTransform can push multiple times at different moments', testMultipleYields, 'webTransform', false, true);86+87+const partsPerChunk = 4;88+const chunksPerCall = 10;89+const callCount = 5;90+const fullString = '\n'.repeat(defaultHighWaterMark / partsPerChunk);91+92+const yieldFullStrings = function * () {93+ yield * Array.from({length: partsPerChunk * chunksPerCall}).fill(fullString);94+};95+96+const manyYieldGenerator = async function * () {97+ for (let index = 0; index < callCount; index += 1) {98+ yield * yieldFullStrings();99+ // eslint-disable-next-line no-await-in-loop100+ await scheduler.yield();101+ }102+};103+104+const testManyYields = async (t, final) => {105+ const subprocess = execa('noop.js', {stdout: convertTransformToFinal(manyYieldGenerator, final), stripFinalNewline: false});106+ const [chunks, {stdout}] = await Promise.all([getStreamAsArray(subprocess.stdout), subprocess]);107+ const expectedChunk = Buffer.from(fullString);108+ t.deepEqual(chunks, Array.from({length: callCount * partsPerChunk * chunksPerCall}).fill(expectedChunk));109+ t.is(chunks.join(''), stdout);110+};111+112+test('Generator "transform" yields are sent right away', testManyYields, false);113+test('Generator "final" yields are sent right away', testManyYields, true);114+115+const testMaxBuffer = async (t, type) => {116+ const bigString = '.'.repeat(maxBuffer);117+ const {stdout} = await execa('noop.js', {118+ maxBuffer,119+ stdout: generatorsMap[type].getOutput(bigString)(false, true),120+ });121+ t.is(stdout, bigString);122+123+ const {isMaxBuffer, shortMessage} = await t.throwsAsync(execa('noop.js', {124+ maxBuffer,125+ stdout: generatorsMap[type].getOutput(`${bigString}.`)(false, true),126+ }));127+ t.true(isMaxBuffer);128+ assertErrorMessage(t, shortMessage);129+};130+131+test('Generators take "maxBuffer" into account', testMaxBuffer, 'generator');132+test('Duplexes take "maxBuffer" into account', testMaxBuffer, 'duplex');133+test('WebTransforms take "maxBuffer" into account', testMaxBuffer, 'webTransform');134+135+test('Generators does not take "maxBuffer" into account, sync', t => {136+ const bigString = '.'.repeat(maxBuffer);137+ const {isMaxBuffer, stdout} = execaSync('noop.js', {138+ maxBuffer,139+ stdout: generatorsMap.generator.getOutput(`${bigString}.`)(false, true),140+ });141+ t.false(isMaxBuffer);142+ t.is(stdout.length, maxBuffer + 1);143+});144+145+const testMaxBufferObject = async (t, type) => {146+ const bigArray = Array.from({length: maxBuffer}).fill('..');147+ const {stdout} = await execa('noop.js', {148+ maxBuffer,149+ stdout: generatorsMap[type].getOutputs(bigArray)(true, true),150+ });151+ t.is(stdout.length, maxBuffer);152+153+ const {isMaxBuffer, shortMessage} = await t.throwsAsync(execa('noop.js', {154+ maxBuffer,155+ stdout: generatorsMap[type].getOutputs([...bigArray, ''])(true, true),156+ }));157+ t.true(isMaxBuffer);158+ assertErrorMessage(t, shortMessage, {unit: 'objects'});159+};160+161+test('Generators take "maxBuffer" into account, objectMode', testMaxBufferObject, 'generator');162+test('Duplexes take "maxBuffer" into account, objectMode', testMaxBufferObject, 'duplex');163+test('WebTransforms take "maxBuffer" into account, objectMode', testMaxBufferObject, 'webTransform');164+165+test('Generators does not take "maxBuffer" into account, objectMode, sync', t => {166+ const bigArray = Array.from({length: maxBuffer}).fill('..');167+ const {isMaxBuffer, stdout} = execaSync('noop.js', {168+ maxBuffer,169+ stdout: generatorsMap.generator.getOutputs([...bigArray, ''])(true, true),170+ });171+ t.false(isMaxBuffer);172+ t.is(stdout.length, maxBuffer + 1);173+});174+175+const testAsyncGenerators = async (t, type, final) => {176+ const {stdout} = await execa('noop.js', {177+ stdout: convertTransformToFinal(generatorsMap[type].timeout(1e2)(), final),178+ });179+ t.is(stdout, foobarString);180+};181+182+test('Generators "transform" is awaited on success', testAsyncGenerators, 'generator', false);183+test('Generators "final" is awaited on success', testAsyncGenerators, 'generator', true);184+test('Duplex is awaited on success', testAsyncGenerators, 'duplex', false);185+test('WebTransform is awaited on success', testAsyncGenerators, 'webTransform', false);added:test/transform/generator-mixed.js+104 added
1+import {readFile, writeFile, rm} from 'node:fs/promises';2+import {PassThrough} from 'node:stream';3+import test from 'ava';4+import getStream from 'get-stream';5+import tempfile from 'tempfile';6+import {execa, execaSync} from '../../index.js';7+import {setFixtureDir} from '../helpers/fixtures-dir.js';8+import {foobarString, foobarUppercase, foobarUint8Array} from '../helpers/input.js';9+import {uppercaseGenerator} from '../helpers/generator.js';10+import {uppercaseBufferDuplex} from '../helpers/duplex.js';11+import {uppercaseBufferWebTransform} from '../helpers/web-transform.js';12+import {generatorsMap} from '../helpers/map.js';13+14+setFixtureDir();15+16+const testInputOption = async (t, type, execaMethod) => {17+ const {stdout} = await execaMethod('stdin-fd.js', ['0'], {stdin: generatorsMap[type].uppercase(), input: foobarUint8Array});18+ t.is(stdout, foobarUppercase);19+};20+21+test('Can use generators with input option', testInputOption, 'generator', execa);22+test('Can use generators with input option, sync', testInputOption, 'generator', execaSync);23+test('Can use duplexes with input option', testInputOption, 'duplex', execa);24+test('Can use webTransforms with input option', testInputOption, 'webTransform', execa);25+26+// eslint-disable-next-line max-params27+const testInputFile = async (t, stdinOption, useInputFile, reversed, execaMethod) => {28+ const filePath = tempfile();29+ await writeFile(filePath, foobarString);30+ const options = useInputFile31+ ? {inputFile: filePath, stdin: stdinOption}32+ : {stdin: [{file: filePath}, stdinOption]};33+ options.stdin = reversed ? options.stdin.reverse() : options.stdin;34+ const {stdout} = await execaMethod('stdin-fd.js', ['0'], options);35+ t.is(stdout, foobarUppercase);36+ await rm(filePath);37+};38+39+test('Can use generators with a file as input', testInputFile, uppercaseGenerator(), false, false, execa);40+test('Can use generators with a file as input, reversed', testInputFile, uppercaseGenerator(), false, true, execa);41+test('Can use generators with inputFile option', testInputFile, uppercaseGenerator(), true, false, execa);42+test('Can use generators with a file as input, sync', testInputFile, uppercaseGenerator(), false, false, execaSync);43+test('Can use generators with a file as input, reversed, sync', testInputFile, uppercaseGenerator(), false, true, execaSync);44+test('Can use generators with inputFile option, sync', testInputFile, uppercaseGenerator(), true, false, execaSync);45+test('Can use duplexes with a file as input', testInputFile, uppercaseBufferDuplex(), false, false, execa);46+test('Can use duplexes with a file as input, reversed', testInputFile, uppercaseBufferDuplex(), false, true, execa);47+test('Can use duplexes with inputFile option', testInputFile, uppercaseBufferDuplex(), true, false, execa);48+test('Can use webTransforms with a file as input', testInputFile, uppercaseBufferWebTransform(), false, false, execa);49+test('Can use webTransforms with a file as input, reversed', testInputFile, uppercaseBufferWebTransform(), false, true, execa);50+test('Can use webTransforms with inputFile option', testInputFile, uppercaseBufferWebTransform(), true, false, execa);51+52+const testOutputFile = async (t, reversed, type, execaMethod) => {53+ const filePath = tempfile();54+ const stdoutOption = [generatorsMap[type].uppercaseBuffer(false, true), {file: filePath}];55+ const reversedStdoutOption = reversed ? stdoutOption.reverse() : stdoutOption;56+ const {stdout} = await execaMethod('noop-fd.js', ['1'], {stdout: reversedStdoutOption});57+ t.is(stdout, foobarUppercase);58+ t.is(await readFile(filePath, 'utf8'), foobarUppercase);59+ await rm(filePath);60+};61+62+test('Can use generators with a file as output', testOutputFile, false, 'generator', execa);63+test('Can use generators with a file as output, reversed', testOutputFile, true, 'generator', execa);64+test('Can use generators with a file as output, sync', testOutputFile, false, 'generator', execaSync);65+test('Can use generators with a file as output, reversed, sync', testOutputFile, true, 'generator', execaSync);66+test('Can use duplexes with a file as output', testOutputFile, false, 'duplex', execa);67+test('Can use duplexes with a file as output, reversed', testOutputFile, true, 'duplex', execa);68+test('Can use webTransforms with a file as output', testOutputFile, false, 'webTransform', execa);69+test('Can use webTransforms with a file as output, reversed', testOutputFile, true, 'webTransform', execa);70+71+const testWritableDestination = async (t, type) => {72+ const passThrough = new PassThrough();73+ const [{stdout}, streamOutput] = await Promise.all([74+ execa('noop-fd.js', ['1', foobarString], {stdout: [generatorsMap[type].uppercaseBuffer(false, true), passThrough]}),75+ getStream(passThrough),76+ ]);77+ t.is(stdout, foobarUppercase);78+ t.is(streamOutput, foobarUppercase);79+};80+81+test('Can use generators to a Writable stream', testWritableDestination, 'generator');82+test('Can use duplexes to a Writable stream', testWritableDestination, 'duplex');83+test('Can use webTransforms to a Writable stream', testWritableDestination, 'webTransform');84+85+const testReadableSource = async (t, type) => {86+ const passThrough = new PassThrough();87+ const subprocess = execa('stdin-fd.js', ['0'], {stdin: [passThrough, generatorsMap[type].uppercase()]});88+ passThrough.end(foobarString);89+ const {stdout} = await subprocess;90+ t.is(stdout, foobarUppercase);91+};92+93+test('Can use generators from a Readable stream', testReadableSource, 'generator');94+test('Can use duplexes from a Readable stream', testReadableSource, 'duplex');95+test('Can use webTransforms from a Readable stream', testReadableSource, 'webTransform');96+97+const testInherit = async (t, type) => {98+ const {stdout} = await execa('nested-inherit.js', [type]);99+ t.is(stdout, foobarUppercase);100+};101+102+test('Can use generators with "inherit"', testInherit, 'generator');103+test('Can use duplexes with "inherit"', testInherit, 'duplex');104+test('Can use webTransforms with "inherit"', testInherit, 'webTransform');added:test/transform/generator-output.js+261 added
1+import test from 'ava';2+import getStream, {getStreamAsArray} from 'get-stream';3+import {execa, execaSync} from '../../index.js';4+import {setFixtureDir} from '../helpers/fixtures-dir.js';5+import {getStdio} from '../helpers/stdio.js';6+import {foobarString, foobarUppercase, foobarObject} from '../helpers/input.js';7+import {generatorsMap} from '../helpers/map.js';8+9+setFixtureDir();10+11+const getOutputObjectMode = (objectMode, addNoopTransform, type, binary) => objectMode12+ ? {13+ generators: generatorsMap[type].addNoop(generatorsMap[type].outputObject(), addNoopTransform, objectMode, binary),14+ output: [foobarObject],15+ getStreamMethod: getStreamAsArray,16+ }17+ : {18+ generators: generatorsMap[type].addNoop(generatorsMap[type].uppercaseBuffer(objectMode, true), addNoopTransform, objectMode, binary),19+ output: foobarUppercase,20+ getStreamMethod: getStream,21+ };22+23+// eslint-disable-next-line max-params24+const testGeneratorOutput = async (t, fdNumber, reject, useShortcutProperty, objectMode, addNoopTransform, type, execaMethod) => {25+ const {generators, output} = getOutputObjectMode(objectMode, addNoopTransform, type);26+ const fixtureName = reject ? 'noop-fd.js' : 'noop-fail.js';27+ const {stdout, stderr, stdio} = await execaMethod(fixtureName, [`${fdNumber}`, foobarString], {...getStdio(fdNumber, generators), reject});28+ const result = useShortcutProperty ? [stdout, stderr][fdNumber - 1] : stdio[fdNumber];29+ t.deepEqual(result, output);30+};31+32+test('Can use generators with result.stdio[1]', testGeneratorOutput, 1, true, false, false, false, 'generator', execa);33+test('Can use generators with result.stdout', testGeneratorOutput, 1, true, true, false, false, 'generator', execa);34+test('Can use generators with result.stdio[2]', testGeneratorOutput, 2, true, false, false, false, 'generator', execa);35+test('Can use generators with result.stderr', testGeneratorOutput, 2, true, true, false, false, 'generator', execa);36+test('Can use generators with result.stdio[*] as output', testGeneratorOutput, 3, true, false, false, false, 'generator', execa);37+test('Can use generators with error.stdio[1]', testGeneratorOutput, 1, false, false, false, false, 'generator', execa);38+test('Can use generators with error.stdout', testGeneratorOutput, 1, false, true, false, false, 'generator', execa);39+test('Can use generators with error.stdio[2]', testGeneratorOutput, 2, false, false, false, false, 'generator', execa);40+test('Can use generators with error.stderr', testGeneratorOutput, 2, false, true, false, false, 'generator', execa);41+test('Can use generators with error.stdio[*] as output', testGeneratorOutput, 3, false, false, false, false, 'generator', execa);42+test('Can use generators with result.stdio[1], objectMode', testGeneratorOutput, 1, true, false, true, false, 'generator', execa);43+test('Can use generators with result.stdout, objectMode', testGeneratorOutput, 1, true, true, true, false, 'generator', execa);44+test('Can use generators with result.stdio[2], objectMode', testGeneratorOutput, 2, true, false, true, false, 'generator', execa);45+test('Can use generators with result.stderr, objectMode', testGeneratorOutput, 2, true, true, true, false, 'generator', execa);46+test('Can use generators with result.stdio[*] as output, objectMode', testGeneratorOutput, 3, true, false, true, false, 'generator', execa);47+test('Can use generators with error.stdio[1], objectMode', testGeneratorOutput, 1, false, false, true, false, 'generator', execa);48+test('Can use generators with error.stdout, objectMode', testGeneratorOutput, 1, false, true, true, false, 'generator', execa);49+test('Can use generators with error.stdio[2], objectMode', testGeneratorOutput, 2, false, false, true, false, 'generator', execa);50+test('Can use generators with error.stderr, objectMode', testGeneratorOutput, 2, false, true, true, false, 'generator', execa);51+test('Can use generators with error.stdio[*] as output, objectMode', testGeneratorOutput, 3, false, false, true, false, 'generator', execa);52+test('Can use generators with result.stdio[1], noop transform', testGeneratorOutput, 1, true, false, false, true, 'generator', execa);53+test('Can use generators with result.stdout, noop transform', testGeneratorOutput, 1, true, true, false, true, 'generator', execa);54+test('Can use generators with result.stdio[2], noop transform', testGeneratorOutput, 2, true, false, false, true, 'generator', execa);55+test('Can use generators with result.stderr, noop transform', testGeneratorOutput, 2, true, true, false, true, 'generator', execa);56+test('Can use generators with result.stdio[*] as output, noop transform', testGeneratorOutput, 3, true, false, false, true, 'generator', execa);57+test('Can use generators with error.stdio[1], noop transform', testGeneratorOutput, 1, false, false, false, true, 'generator', execa);58+test('Can use generators with error.stdout, noop transform', testGeneratorOutput, 1, false, true, false, true, 'generator', execa);59+test('Can use generators with error.stdio[2], noop transform', testGeneratorOutput, 2, false, false, false, true, 'generator', execa);60+test('Can use generators with error.stderr, noop transform', testGeneratorOutput, 2, false, true, false, true, 'generator', execa);61+test('Can use generators with error.stdio[*] as output, noop transform', testGeneratorOutput, 3, false, false, false, true, 'generator', execa);62+test('Can use generators with result.stdio[1], objectMode, noop transform', testGeneratorOutput, 1, true, false, true, true, 'generator', execa);63+test('Can use generators with result.stdout, objectMode, noop transform', testGeneratorOutput, 1, true, true, true, true, 'generator', execa);64+test('Can use generators with result.stdio[2], objectMode, noop transform', testGeneratorOutput, 2, true, false, true, true, 'generator', execa);65+test('Can use generators with result.stderr, objectMode, noop transform', testGeneratorOutput, 2, true, true, true, true, 'generator', execa);66+test('Can use generators with result.stdio[*] as output, objectMode, noop transform', testGeneratorOutput, 3, true, false, true, true, 'generator', execa);67+test('Can use generators with error.stdio[1], objectMode, noop transform', testGeneratorOutput, 1, false, false, true, true, 'generator', execa);68+test('Can use generators with error.stdout, objectMode, noop transform', testGeneratorOutput, 1, false, true, true, true, 'generator', execa);69+test('Can use generators with error.stdio[2], objectMode, noop transform', testGeneratorOutput, 2, false, false, true, true, 'generator', execa);70+test('Can use generators with error.stderr, objectMode, noop transform', testGeneratorOutput, 2, false, true, true, true, 'generator', execa);71+test('Can use generators with error.stdio[*] as output, objectMode, noop transform', testGeneratorOutput, 3, false, false, true, true, 'generator', execa);72+test('Can use generators with result.stdio[1], sync', testGeneratorOutput, 1, true, false, false, false, 'generator', execaSync);73+test('Can use generators with result.stdout, sync', testGeneratorOutput, 1, true, true, false, false, 'generator', execaSync);74+test('Can use generators with result.stdio[2], sync', testGeneratorOutput, 2, true, false, false, false, 'generator', execaSync);75+test('Can use generators with result.stderr, sync', testGeneratorOutput, 2, true, true, false, false, 'generator', execaSync);76+test('Can use generators with result.stdio[*] as output, sync', testGeneratorOutput, 3, true, false, false, false, 'generator', execaSync);77+test('Can use generators with error.stdio[1], sync', testGeneratorOutput, 1, false, false, false, false, 'generator', execaSync);78+test('Can use generators with error.stdout, sync', testGeneratorOutput, 1, false, true, false, false, 'generator', execaSync);79+test('Can use generators with error.stdio[2], sync', testGeneratorOutput, 2, false, false, false, false, 'generator', execaSync);80+test('Can use generators with error.stderr, sync', testGeneratorOutput, 2, false, true, false, false, 'generator', execaSync);81+test('Can use generators with error.stdio[*] as output, sync', testGeneratorOutput, 3, false, false, false, false, 'generator', execaSync);82+test('Can use generators with result.stdio[1], objectMode, sync', testGeneratorOutput, 1, true, false, true, false, 'generator', execaSync);83+test('Can use generators with result.stdout, objectMode, sync', testGeneratorOutput, 1, true, true, true, false, 'generator', execaSync);84+test('Can use generators with result.stdio[2], objectMode, sync', testGeneratorOutput, 2, true, false, true, false, 'generator', execaSync);85+test('Can use generators with result.stderr, objectMode, sync', testGeneratorOutput, 2, true, true, true, false, 'generator', execaSync);86+test('Can use generators with result.stdio[*] as output, objectMode, sync', testGeneratorOutput, 3, true, false, true, false, 'generator', execaSync);87+test('Can use generators with error.stdio[1], objectMode, sync', testGeneratorOutput, 1, false, false, true, false, 'generator', execaSync);88+test('Can use generators with error.stdout, objectMode, sync', testGeneratorOutput, 1, false, true, true, false, 'generator', execaSync);89+test('Can use generators with error.stdio[2], objectMode, sync', testGeneratorOutput, 2, false, false, true, false, 'generator', execaSync);90+test('Can use generators with error.stderr, objectMode, sync', testGeneratorOutput, 2, false, true, true, false, 'generator', execaSync);91+test('Can use generators with error.stdio[*] as output, objectMode, sync', testGeneratorOutput, 3, false, false, true, false, 'generator', execaSync);92+test('Can use generators with result.stdio[1], noop transform, sync', testGeneratorOutput, 1, true, false, false, true, 'generator', execaSync);93+test('Can use generators with result.stdout, noop transform, sync', testGeneratorOutput, 1, true, true, false, true, 'generator', execaSync);94+test('Can use generators with result.stdio[2], noop transform, sync', testGeneratorOutput, 2, true, false, false, true, 'generator', execaSync);95+test('Can use generators with result.stderr, noop transform, sync', testGeneratorOutput, 2, true, true, false, true, 'generator', execaSync);96+test('Can use generators with result.stdio[*] as output, noop transform, sync', testGeneratorOutput, 3, true, false, false, true, 'generator', execaSync);97+test('Can use generators with error.stdio[1], noop transform, sync', testGeneratorOutput, 1, false, false, false, true, 'generator', execaSync);98+test('Can use generators with error.stdout, noop transform, sync', testGeneratorOutput, 1, false, true, false, true, 'generator', execaSync);99+test('Can use generators with error.stdio[2], noop transform, sync', testGeneratorOutput, 2, false, false, false, true, 'generator', execaSync);100+test('Can use generators with error.stderr, noop transform, sync', testGeneratorOutput, 2, false, true, false, true, 'generator', execaSync);101+test('Can use generators with error.stdio[*] as output, noop transform, sync', testGeneratorOutput, 3, false, false, false, true, 'generator', execaSync);102+test('Can use generators with result.stdio[1], objectMode, noop transform, sync', testGeneratorOutput, 1, true, false, true, true, 'generator', execaSync);103+test('Can use generators with result.stdout, objectMode, noop transform, sync', testGeneratorOutput, 1, true, true, true, true, 'generator', execaSync);104+test('Can use generators with result.stdio[2], objectMode, noop transform, sync', testGeneratorOutput, 2, true, false, true, true, 'generator', execaSync);105+test('Can use generators with result.stderr, objectMode, noop transform, sync', testGeneratorOutput, 2, true, true, true, true, 'generator', execaSync);106+test('Can use generators with result.stdio[*] as output, objectMode, noop transform, sync', testGeneratorOutput, 3, true, false, true, true, 'generator', execaSync);107+test('Can use generators with error.stdio[1], objectMode, noop transform, sync', testGeneratorOutput, 1, false, false, true, true, 'generator', execaSync);108+test('Can use generators with error.stdout, objectMode, noop transform, sync', testGeneratorOutput, 1, false, true, true, true, 'generator', execaSync);109+test('Can use generators with error.stdio[2], objectMode, noop transform, sync', testGeneratorOutput, 2, false, false, true, true, 'generator', execaSync);110+test('Can use generators with error.stderr, objectMode, noop transform, sync', testGeneratorOutput, 2, false, true, true, true, 'generator', execaSync);111+test('Can use generators with error.stdio[*] as output, objectMode, noop transform, sync', testGeneratorOutput, 3, false, false, true, true, 'generator', execaSync);112+test('Can use duplexes with result.stdio[1]', testGeneratorOutput, 1, true, false, false, false, 'duplex', execa);113+test('Can use duplexes with result.stdout', testGeneratorOutput, 1, true, true, false, false, 'duplex', execa);114+test('Can use duplexes with result.stdio[2]', testGeneratorOutput, 2, true, false, false, false, 'duplex', execa);115+test('Can use duplexes with result.stderr', testGeneratorOutput, 2, true, true, false, false, 'duplex', execa);116+test('Can use duplexes with result.stdio[*] as output', testGeneratorOutput, 3, true, false, false, false, 'duplex', execa);117+test('Can use duplexes with error.stdio[1]', testGeneratorOutput, 1, false, false, false, false, 'duplex', execa);118+test('Can use duplexes with error.stdout', testGeneratorOutput, 1, false, true, false, false, 'duplex', execa);119+test('Can use duplexes with error.stdio[2]', testGeneratorOutput, 2, false, false, false, false, 'duplex', execa);120+test('Can use duplexes with error.stderr', testGeneratorOutput, 2, false, true, false, false, 'duplex', execa);121+test('Can use duplexes with error.stdio[*] as output', testGeneratorOutput, 3, false, false, false, false, 'duplex', execa);122+test('Can use duplexes with result.stdio[1], objectMode', testGeneratorOutput, 1, true, false, true, false, 'duplex', execa);123+test('Can use duplexes with result.stdout, objectMode', testGeneratorOutput, 1, true, true, true, false, 'duplex', execa);124+test('Can use duplexes with result.stdio[2], objectMode', testGeneratorOutput, 2, true, false, true, false, 'duplex', execa);125+test('Can use duplexes with result.stderr, objectMode', testGeneratorOutput, 2, true, true, true, false, 'duplex', execa);126+test('Can use duplexes with result.stdio[*] as output, objectMode', testGeneratorOutput, 3, true, false, true, false, 'duplex', execa);127+test('Can use duplexes with error.stdio[1], objectMode', testGeneratorOutput, 1, false, false, true, false, 'duplex', execa);128+test('Can use duplexes with error.stdout, objectMode', testGeneratorOutput, 1, false, true, true, false, 'duplex', execa);129+test('Can use duplexes with error.stdio[2], objectMode', testGeneratorOutput, 2, false, false, true, false, 'duplex', execa);130+test('Can use duplexes with error.stderr, objectMode', testGeneratorOutput, 2, false, true, true, false, 'duplex', execa);131+test('Can use duplexes with error.stdio[*] as output, objectMode', testGeneratorOutput, 3, false, false, true, false, 'duplex', execa);132+test('Can use duplexes with result.stdio[1], noop transform', testGeneratorOutput, 1, true, false, false, true, 'duplex', execa);133+test('Can use duplexes with result.stdout, noop transform', testGeneratorOutput, 1, true, true, false, true, 'duplex', execa);134+test('Can use duplexes with result.stdio[2], noop transform', testGeneratorOutput, 2, true, false, false, true, 'duplex', execa);135+test('Can use duplexes with result.stderr, noop transform', testGeneratorOutput, 2, true, true, false, true, 'duplex', execa);136+test('Can use duplexes with result.stdio[*] as output, noop transform', testGeneratorOutput, 3, true, false, false, true, 'duplex', execa);137+test('Can use duplexes with error.stdio[1], noop transform', testGeneratorOutput, 1, false, false, false, true, 'duplex', execa);138+test('Can use duplexes with error.stdout, noop transform', testGeneratorOutput, 1, false, true, false, true, 'duplex', execa);139+test('Can use duplexes with error.stdio[2], noop transform', testGeneratorOutput, 2, false, false, false, true, 'duplex', execa);140+test('Can use duplexes with error.stderr, noop transform', testGeneratorOutput, 2, false, true, false, true, 'duplex', execa);141+test('Can use duplexes with error.stdio[*] as output, noop transform', testGeneratorOutput, 3, false, false, false, true, 'duplex', execa);142+test('Can use duplexes with result.stdio[1], objectMode, noop transform', testGeneratorOutput, 1, true, false, true, true, 'duplex', execa);143+test('Can use duplexes with result.stdout, objectMode, noop transform', testGeneratorOutput, 1, true, true, true, true, 'duplex', execa);144+test('Can use duplexes with result.stdio[2], objectMode, noop transform', testGeneratorOutput, 2, true, false, true, true, 'duplex', execa);145+test('Can use duplexes with result.stderr, objectMode, noop transform', testGeneratorOutput, 2, true, true, true, true, 'duplex', execa);146+test('Can use duplexes with result.stdio[*] as output, objectMode, noop transform', testGeneratorOutput, 3, true, false, true, true, 'duplex', execa);147+test('Can use duplexes with error.stdio[1], objectMode, noop transform', testGeneratorOutput, 1, false, false, true, true, 'duplex', execa);148+test('Can use duplexes with error.stdout, objectMode, noop transform', testGeneratorOutput, 1, false, true, true, true, 'duplex', execa);149+test('Can use duplexes with error.stdio[2], objectMode, noop transform', testGeneratorOutput, 2, false, false, true, true, 'duplex', execa);150+test('Can use duplexes with error.stderr, objectMode, noop transform', testGeneratorOutput, 2, false, true, true, true, 'duplex', execa);151+test('Can use duplexes with error.stdio[*] as output, objectMode, noop transform', testGeneratorOutput, 3, false, false, true, true, 'duplex', execa);152+test('Can use webTransforms with result.stdio[1]', testGeneratorOutput, 1, true, false, false, false, 'webTransform', execa);153+test('Can use webTransforms with result.stdout', testGeneratorOutput, 1, true, true, false, false, 'webTransform', execa);154+test('Can use webTransforms with result.stdio[2]', testGeneratorOutput, 2, true, false, false, false, 'webTransform', execa);155+test('Can use webTransforms with result.stderr', testGeneratorOutput, 2, true, true, false, false, 'webTransform', execa);156+test('Can use webTransforms with result.stdio[*] as output', testGeneratorOutput, 3, true, false, false, false, 'webTransform', execa);157+test('Can use webTransforms with error.stdio[1]', testGeneratorOutput, 1, false, false, false, false, 'webTransform', execa);158+test('Can use webTransforms with error.stdout', testGeneratorOutput, 1, false, true, false, false, 'webTransform', execa);159+test('Can use webTransforms with error.stdio[2]', testGeneratorOutput, 2, false, false, false, false, 'webTransform', execa);160+test('Can use webTransforms with error.stderr', testGeneratorOutput, 2, false, true, false, false, 'webTransform', execa);161+test('Can use webTransforms with error.stdio[*] as output', testGeneratorOutput, 3, false, false, false, false, 'webTransform', execa);162+test('Can use webTransforms with result.stdio[1], objectMode', testGeneratorOutput, 1, true, false, true, false, 'webTransform', execa);163+test('Can use webTransforms with result.stdout, objectMode', testGeneratorOutput, 1, true, true, true, false, 'webTransform', execa);164+test('Can use webTransforms with result.stdio[2], objectMode', testGeneratorOutput, 2, true, false, true, false, 'webTransform', execa);165+test('Can use webTransforms with result.stderr, objectMode', testGeneratorOutput, 2, true, true, true, false, 'webTransform', execa);166+test('Can use webTransforms with result.stdio[*] as output, objectMode', testGeneratorOutput, 3, true, false, true, false, 'webTransform', execa);167+test('Can use webTransforms with error.stdio[1], objectMode', testGeneratorOutput, 1, false, false, true, false, 'webTransform', execa);168+test('Can use webTransforms with error.stdout, objectMode', testGeneratorOutput, 1, false, true, true, false, 'webTransform', execa);169+test('Can use webTransforms with error.stdio[2], objectMode', testGeneratorOutput, 2, false, false, true, false, 'webTransform', execa);170+test('Can use webTransforms with error.stderr, objectMode', testGeneratorOutput, 2, false, true, true, false, 'webTransform', execa);171+test('Can use webTransforms with error.stdio[*] as output, objectMode', testGeneratorOutput, 3, false, false, true, false, 'webTransform', execa);172+test('Can use webTransforms with result.stdio[1], noop transform', testGeneratorOutput, 1, true, false, false, true, 'webTransform', execa);173+test('Can use webTransforms with result.stdout, noop transform', testGeneratorOutput, 1, true, true, false, true, 'webTransform', execa);174+test('Can use webTransforms with result.stdio[2], noop transform', testGeneratorOutput, 2, true, false, false, true, 'webTransform', execa);175+test('Can use webTransforms with result.stderr, noop transform', testGeneratorOutput, 2, true, true, false, true, 'webTransform', execa);176+test('Can use webTransforms with result.stdio[*] as output, noop transform', testGeneratorOutput, 3, true, false, false, true, 'webTransform', execa);177+test('Can use webTransforms with error.stdio[1], noop transform', testGeneratorOutput, 1, false, false, false, true, 'webTransform', execa);178+test('Can use webTransforms with error.stdout, noop transform', testGeneratorOutput, 1, false, true, false, true, 'webTransform', execa);179+test('Can use webTransforms with error.stdio[2], noop transform', testGeneratorOutput, 2, false, false, false, true, 'webTransform', execa);180+test('Can use webTransforms with error.stderr, noop transform', testGeneratorOutput, 2, false, true, false, true, 'webTransform', execa);181+test('Can use webTransforms with error.stdio[*] as output, noop transform', testGeneratorOutput, 3, false, false, false, true, 'webTransform', execa);182+test('Can use webTransforms with result.stdio[1], objectMode, noop transform', testGeneratorOutput, 1, true, false, true, true, 'webTransform', execa);183+test('Can use webTransforms with result.stdout, objectMode, noop transform', testGeneratorOutput, 1, true, true, true, true, 'webTransform', execa);184+test('Can use webTransforms with result.stdio[2], objectMode, noop transform', testGeneratorOutput, 2, true, false, true, true, 'webTransform', execa);185+test('Can use webTransforms with result.stderr, objectMode, noop transform', testGeneratorOutput, 2, true, true, true, true, 'webTransform', execa);186+test('Can use webTransforms with result.stdio[*] as output, objectMode, noop transform', testGeneratorOutput, 3, true, false, true, true, 'webTransform', execa);187+test('Can use webTransforms with error.stdio[1], objectMode, noop transform', testGeneratorOutput, 1, false, false, true, true, 'webTransform', execa);188+test('Can use webTransforms with error.stdout, objectMode, noop transform', testGeneratorOutput, 1, false, true, true, true, 'webTransform', execa);189+test('Can use webTransforms with error.stdio[2], objectMode, noop transform', testGeneratorOutput, 2, false, false, true, true, 'webTransform', execa);190+test('Can use webTransforms with error.stderr, objectMode, noop transform', testGeneratorOutput, 2, false, true, true, true, 'webTransform', execa);191+test('Can use webTransforms with error.stdio[*] as output, objectMode, noop transform', testGeneratorOutput, 3, false, false, true, true, 'webTransform', execa);192+193+// eslint-disable-next-line max-params194+const testGeneratorOutputPipe = async (t, fdNumber, useShortcutProperty, objectMode, addNoopTransform, type) => {195+ const {generators, output, getStreamMethod} = getOutputObjectMode(objectMode, addNoopTransform, type, true);196+ const subprocess = execa('noop-fd.js', [`${fdNumber}`, foobarString], getStdio(fdNumber, generators));197+ const stream = useShortcutProperty ? [subprocess.stdout, subprocess.stderr][fdNumber - 1] : subprocess.stdio[fdNumber];198+ const [result] = await Promise.all([getStreamMethod(stream), subprocess]);199+ t.deepEqual(result, output);200+};201+202+test('Can use generators with subprocess.stdio[1]', testGeneratorOutputPipe, 1, false, false, false, 'generator');203+test('Can use generators with subprocess.stdout', testGeneratorOutputPipe, 1, true, false, false, 'generator');204+test('Can use generators with subprocess.stdio[2]', testGeneratorOutputPipe, 2, false, false, false, 'generator');205+test('Can use generators with subprocess.stderr', testGeneratorOutputPipe, 2, true, false, false, 'generator');206+test('Can use generators with subprocess.stdio[*] as output', testGeneratorOutputPipe, 3, false, false, false, 'generator');207+test('Can use generators with subprocess.stdio[1], objectMode', testGeneratorOutputPipe, 1, false, true, false, 'generator');208+test('Can use generators with subprocess.stdout, objectMode', testGeneratorOutputPipe, 1, true, true, false, 'generator');209+test('Can use generators with subprocess.stdio[2], objectMode', testGeneratorOutputPipe, 2, false, true, false, 'generator');210+test('Can use generators with subprocess.stderr, objectMode', testGeneratorOutputPipe, 2, true, true, false, 'generator');211+test('Can use generators with subprocess.stdio[*] as output, objectMode', testGeneratorOutputPipe, 3, false, true, false, 'generator');212+test('Can use generators with subprocess.stdio[1], noop transform', testGeneratorOutputPipe, 1, false, false, true, 'generator');213+test('Can use generators with subprocess.stdout, noop transform', testGeneratorOutputPipe, 1, true, false, true, 'generator');214+test('Can use generators with subprocess.stdio[2], noop transform', testGeneratorOutputPipe, 2, false, false, true, 'generator');215+test('Can use generators with subprocess.stderr, noop transform', testGeneratorOutputPipe, 2, true, false, true, 'generator');216+test('Can use generators with subprocess.stdio[*] as output, noop transform', testGeneratorOutputPipe, 3, false, false, true, 'generator');217+test('Can use generators with subprocess.stdio[1], objectMode, noop transform', testGeneratorOutputPipe, 1, false, true, true, 'generator');218+test('Can use generators with subprocess.stdout, objectMode, noop transform', testGeneratorOutputPipe, 1, true, true, true, 'generator');219+test('Can use generators with subprocess.stdio[2], objectMode, noop transform', testGeneratorOutputPipe, 2, false, true, true, 'generator');220+test('Can use generators with subprocess.stderr, objectMode, noop transform', testGeneratorOutputPipe, 2, true, true, true, 'generator');221+test('Can use generators with subprocess.stdio[*] as output, objectMode, noop transform', testGeneratorOutputPipe, 3, false, true, true, 'generator');222+test('Can use duplexes with subprocess.stdio[1]', testGeneratorOutputPipe, 1, false, false, false, 'duplex');223+test('Can use duplexes with subprocess.stdout', testGeneratorOutputPipe, 1, true, false, false, 'duplex');224+test('Can use duplexes with subprocess.stdio[2]', testGeneratorOutputPipe, 2, false, false, false, 'duplex');225+test('Can use duplexes with subprocess.stderr', testGeneratorOutputPipe, 2, true, false, false, 'duplex');226+test('Can use duplexes with subprocess.stdio[*] as output', testGeneratorOutputPipe, 3, false, false, false, 'duplex');227+test('Can use duplexes with subprocess.stdio[1], objectMode', testGeneratorOutputPipe, 1, false, true, false, 'duplex');228+test('Can use duplexes with subprocess.stdout, objectMode', testGeneratorOutputPipe, 1, true, true, false, 'duplex');229+test('Can use duplexes with subprocess.stdio[2], objectMode', testGeneratorOutputPipe, 2, false, true, false, 'duplex');230+test('Can use duplexes with subprocess.stderr, objectMode', testGeneratorOutputPipe, 2, true, true, false, 'duplex');231+test('Can use duplexes with subprocess.stdio[*] as output, objectMode', testGeneratorOutputPipe, 3, false, true, false, 'duplex');232+test('Can use duplexes with subprocess.stdio[1], noop transform', testGeneratorOutputPipe, 1, false, false, true, 'duplex');233+test('Can use duplexes with subprocess.stdout, noop transform', testGeneratorOutputPipe, 1, true, false, true, 'duplex');234+test('Can use duplexes with subprocess.stdio[2], noop transform', testGeneratorOutputPipe, 2, false, false, true, 'duplex');235+test('Can use duplexes with subprocess.stderr, noop transform', testGeneratorOutputPipe, 2, true, false, true, 'duplex');236+test('Can use duplexes with subprocess.stdio[*] as output, noop transform', testGeneratorOutputPipe, 3, false, false, true, 'duplex');237+test('Can use duplexes with subprocess.stdio[1], objectMode, noop transform', testGeneratorOutputPipe, 1, false, true, true, 'duplex');238+test('Can use duplexes with subprocess.stdout, objectMode, noop transform', testGeneratorOutputPipe, 1, true, true, true, 'duplex');239+test('Can use duplexes with subprocess.stdio[2], objectMode, noop transform', testGeneratorOutputPipe, 2, false, true, true, 'duplex');240+test('Can use duplexes with subprocess.stderr, objectMode, noop transform', testGeneratorOutputPipe, 2, true, true, true, 'duplex');241+test('Can use duplexes with subprocess.stdio[*] as output, objectMode, noop transform', testGeneratorOutputPipe, 3, false, true, true, 'duplex');242+test('Can use webTransforms with subprocess.stdio[1]', testGeneratorOutputPipe, 1, false, false, false, 'webTransform');243+test('Can use webTransforms with subprocess.stdout', testGeneratorOutputPipe, 1, true, false, false, 'webTransform');244+test('Can use webTransforms with subprocess.stdio[2]', testGeneratorOutputPipe, 2, false, false, false, 'webTransform');245+test('Can use webTransforms with subprocess.stderr', testGeneratorOutputPipe, 2, true, false, false, 'webTransform');246+test('Can use webTransforms with subprocess.stdio[*] as output', testGeneratorOutputPipe, 3, false, false, false, 'webTransform');247+test('Can use webTransforms with subprocess.stdio[1], objectMode', testGeneratorOutputPipe, 1, false, true, false, 'webTransform');248+test('Can use webTransforms with subprocess.stdout, objectMode', testGeneratorOutputPipe, 1, true, true, false, 'webTransform');249+test('Can use webTransforms with subprocess.stdio[2], objectMode', testGeneratorOutputPipe, 2, false, true, false, 'webTransform');250+test('Can use webTransforms with subprocess.stderr, objectMode', testGeneratorOutputPipe, 2, true, true, false, 'webTransform');251+test('Can use webTransforms with subprocess.stdio[*] as output, objectMode', testGeneratorOutputPipe, 3, false, true, false, 'webTransform');252+test('Can use webTransforms with subprocess.stdio[1], noop transform', testGeneratorOutputPipe, 1, false, false, true, 'webTransform');253+test('Can use webTransforms with subprocess.stdout, noop transform', testGeneratorOutputPipe, 1, true, false, true, 'webTransform');254+test('Can use webTransforms with subprocess.stdio[2], noop transform', testGeneratorOutputPipe, 2, false, false, true, 'webTransform');255+test('Can use webTransforms with subprocess.stderr, noop transform', testGeneratorOutputPipe, 2, true, false, true, 'webTransform');256+test('Can use webTransforms with subprocess.stdio[*] as output, noop transform', testGeneratorOutputPipe, 3, false, false, true, 'webTransform');257+test('Can use webTransforms with subprocess.stdio[1], objectMode, noop transform', testGeneratorOutputPipe, 1, false, true, true, 'webTransform');258+test('Can use webTransforms with subprocess.stdout, objectMode, noop transform', testGeneratorOutputPipe, 1, true, true, true, 'webTransform');259+test('Can use webTransforms with subprocess.stdio[2], objectMode, noop transform', testGeneratorOutputPipe, 2, false, true, true, 'webTransform');260+test('Can use webTransforms with subprocess.stderr, objectMode, noop transform', testGeneratorOutputPipe, 2, true, true, true, 'webTransform');261+test('Can use webTransforms with subprocess.stdio[*] as output, objectMode, noop transform', testGeneratorOutputPipe, 3, false, true, true, 'webTransform');added:test/transform/generator-return.js+150 added
1+import {Buffer} from 'node:buffer';2+import test from 'ava';3+import {execa, execaSync} from '../../index.js';4+import {setFixtureDir} from '../helpers/fixtures-dir.js';5+import {foobarString, foobarUint8Array} from '../helpers/input.js';6+import {getOutputGenerator, convertTransformToFinal} from '../helpers/generator.js';7+8+setFixtureDir();9+10+// eslint-disable-next-line max-params11+const testGeneratorReturnType = async (t, input, encoding, reject, objectMode, final, execaMethod) => {12+ const fixtureName = reject ? 'noop-fd.js' : 'noop-fail.js';13+ const {stdout} = await execaMethod(fixtureName, ['1', foobarString], {14+ stdout: convertTransformToFinal(getOutputGenerator(input)(objectMode, true), final),15+ encoding,16+ reject,17+ });18+ const typeofChunk = Array.isArray(stdout) ? stdout[0] : stdout;19+ const output = Buffer.from(typeofChunk, encoding === 'buffer' || objectMode ? undefined : encoding).toString();20+ t.is(output, foobarString);21+};22+23+test('Generator can return string with default encoding', testGeneratorReturnType, foobarString, 'utf8', true, false, false, execa);24+test('Generator can return Uint8Array with default encoding', testGeneratorReturnType, foobarUint8Array, 'utf8', true, false, false, execa);25+test('Generator can return string with encoding "utf16le"', testGeneratorReturnType, foobarString, 'utf16le', true, false, false, execa);26+test('Generator can return Uint8Array with encoding "utf16le"', testGeneratorReturnType, foobarUint8Array, 'utf16le', true, false, false, execa);27+test('Generator can return string with encoding "buffer"', testGeneratorReturnType, foobarString, 'buffer', true, false, false, execa);28+test('Generator can return Uint8Array with encoding "buffer"', testGeneratorReturnType, foobarUint8Array, 'buffer', true, false, false, execa);29+test('Generator can return string with encoding "hex"', testGeneratorReturnType, foobarString, 'hex', true, false, false, execa);30+test('Generator can return Uint8Array with encoding "hex"', testGeneratorReturnType, foobarUint8Array, 'hex', true, false, false, execa);31+test('Generator can return string with default encoding, failure', testGeneratorReturnType, foobarString, 'utf8', false, false, false, execa);32+test('Generator can return Uint8Array with default encoding, failure', testGeneratorReturnType, foobarUint8Array, 'utf8', false, false, false, execa);33+test('Generator can return string with encoding "utf16le", failure', testGeneratorReturnType, foobarString, 'utf16le', false, false, false, execa);34+test('Generator can return Uint8Array with encoding "utf16le", failure', testGeneratorReturnType, foobarUint8Array, 'utf16le', false, false, false, execa);35+test('Generator can return string with encoding "buffer", failure', testGeneratorReturnType, foobarString, 'buffer', false, false, false, execa);36+test('Generator can return Uint8Array with encoding "buffer", failure', testGeneratorReturnType, foobarUint8Array, 'buffer', false, false, false, execa);37+test('Generator can return string with encoding "hex", failure', testGeneratorReturnType, foobarString, 'hex', false, false, false, execa);38+test('Generator can return Uint8Array with encoding "hex", failure', testGeneratorReturnType, foobarUint8Array, 'hex', false, false, false, execa);39+test('Generator can return string with default encoding, objectMode', testGeneratorReturnType, foobarString, 'utf8', true, true, false, execa);40+test('Generator can return Uint8Array with default encoding, objectMode', testGeneratorReturnType, foobarUint8Array, 'utf8', true, true, false, execa);41+test('Generator can return string with encoding "utf16le", objectMode', testGeneratorReturnType, foobarString, 'utf16le', true, true, false, execa);42+test('Generator can return Uint8Array with encoding "utf16le", objectMode', testGeneratorReturnType, foobarUint8Array, 'utf16le', true, true, false, execa);43+test('Generator can return string with encoding "buffer", objectMode', testGeneratorReturnType, foobarString, 'buffer', true, true, false, execa);44+test('Generator can return Uint8Array with encoding "buffer", objectMode', testGeneratorReturnType, foobarUint8Array, 'buffer', true, true, false, execa);45+test('Generator can return string with encoding "hex", objectMode', testGeneratorReturnType, foobarString, 'hex', true, true, false, execa);46+test('Generator can return Uint8Array with encoding "hex", objectMode', testGeneratorReturnType, foobarUint8Array, 'hex', true, true, false, execa);47+test('Generator can return string with default encoding, objectMode, failure', testGeneratorReturnType, foobarString, 'utf8', false, true, false, execa);48+test('Generator can return Uint8Array with default encoding, objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'utf8', false, true, false, execa);49+test('Generator can return string with encoding "utf16le", objectMode, failure', testGeneratorReturnType, foobarString, 'utf16le', false, true, false, execa);50+test('Generator can return Uint8Array with encoding "utf16le", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'utf16le', false, true, false, execa);51+test('Generator can return string with encoding "buffer", objectMode, failure', testGeneratorReturnType, foobarString, 'buffer', false, true, false, execa);52+test('Generator can return Uint8Array with encoding "buffer", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'buffer', false, true, false, execa);53+test('Generator can return string with encoding "hex", objectMode, failure', testGeneratorReturnType, foobarString, 'hex', false, true, false, execa);54+test('Generator can return Uint8Array with encoding "hex", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'hex', false, true, false, execa);55+test('Generator can return final string with default encoding', testGeneratorReturnType, foobarString, 'utf8', true, false, true, execa);56+test('Generator can return final Uint8Array with default encoding', testGeneratorReturnType, foobarUint8Array, 'utf8', true, false, true, execa);57+test('Generator can return final string with encoding "utf16le"', testGeneratorReturnType, foobarString, 'utf16le', true, false, true, execa);58+test('Generator can return final Uint8Array with encoding "utf16le"', testGeneratorReturnType, foobarUint8Array, 'utf16le', true, false, true, execa);59+test('Generator can return final string with encoding "buffer"', testGeneratorReturnType, foobarString, 'buffer', true, false, true, execa);60+test('Generator can return final Uint8Array with encoding "buffer"', testGeneratorReturnType, foobarUint8Array, 'buffer', true, false, true, execa);61+test('Generator can return final string with encoding "hex"', testGeneratorReturnType, foobarString, 'hex', true, false, true, execa);62+test('Generator can return final Uint8Array with encoding "hex"', testGeneratorReturnType, foobarUint8Array, 'hex', true, false, true, execa);63+test('Generator can return final string with default encoding, failure', testGeneratorReturnType, foobarString, 'utf8', false, false, true, execa);64+test('Generator can return final Uint8Array with default encoding, failure', testGeneratorReturnType, foobarUint8Array, 'utf8', false, false, true, execa);65+test('Generator can return final string with encoding "utf16le", failure', testGeneratorReturnType, foobarString, 'utf16le', false, false, true, execa);66+test('Generator can return final Uint8Array with encoding "utf16le", failure', testGeneratorReturnType, foobarUint8Array, 'utf16le', false, false, true, execa);67+test('Generator can return final string with encoding "buffer", failure', testGeneratorReturnType, foobarString, 'buffer', false, false, true, execa);68+test('Generator can return final Uint8Array with encoding "buffer", failure', testGeneratorReturnType, foobarUint8Array, 'buffer', false, false, true, execa);69+test('Generator can return final string with encoding "hex", failure', testGeneratorReturnType, foobarString, 'hex', false, false, true, execa);70+test('Generator can return final Uint8Array with encoding "hex", failure', testGeneratorReturnType, foobarUint8Array, 'hex', false, false, true, execa);71+test('Generator can return final string with default encoding, objectMode', testGeneratorReturnType, foobarString, 'utf8', true, true, true, execa);72+test('Generator can return final Uint8Array with default encoding, objectMode', testGeneratorReturnType, foobarUint8Array, 'utf8', true, true, true, execa);73+test('Generator can return final string with encoding "utf16le", objectMode', testGeneratorReturnType, foobarString, 'utf16le', true, true, true, execa);74+test('Generator can return final Uint8Array with encoding "utf16le", objectMode', testGeneratorReturnType, foobarUint8Array, 'utf16le', true, true, true, execa);75+test('Generator can return final string with encoding "buffer", objectMode', testGeneratorReturnType, foobarString, 'buffer', true, true, true, execa);76+test('Generator can return final Uint8Array with encoding "buffer", objectMode', testGeneratorReturnType, foobarUint8Array, 'buffer', true, true, true, execa);77+test('Generator can return final string with encoding "hex", objectMode', testGeneratorReturnType, foobarString, 'hex', true, true, true, execa);78+test('Generator can return final Uint8Array with encoding "hex", objectMode', testGeneratorReturnType, foobarUint8Array, 'hex', true, true, true, execa);79+test('Generator can return final string with default encoding, objectMode, failure', testGeneratorReturnType, foobarString, 'utf8', false, true, true, execa);80+test('Generator can return final Uint8Array with default encoding, objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'utf8', false, true, true, execa);81+test('Generator can return final string with encoding "utf16le", objectMode, failure', testGeneratorReturnType, foobarString, 'utf16le', false, true, true, execa);82+test('Generator can return final Uint8Array with encoding "utf16le", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'utf16le', false, true, true, execa);83+test('Generator can return final string with encoding "buffer", objectMode, failure', testGeneratorReturnType, foobarString, 'buffer', false, true, true, execa);84+test('Generator can return final Uint8Array with encoding "buffer", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'buffer', false, true, true, execa);85+test('Generator can return final string with encoding "hex", objectMode, failure', testGeneratorReturnType, foobarString, 'hex', false, true, true, execa);86+test('Generator can return final Uint8Array with encoding "hex", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'hex', false, true, true, execa);87+test('Generator can return string with default encoding, sync', testGeneratorReturnType, foobarString, 'utf8', true, false, false, execaSync);88+test('Generator can return Uint8Array with default encoding, sync', testGeneratorReturnType, foobarUint8Array, 'utf8', true, false, false, execaSync);89+test('Generator can return string with encoding "utf16le", sync', testGeneratorReturnType, foobarString, 'utf16le', true, false, false, execaSync);90+test('Generator can return Uint8Array with encoding "utf16le", sync', testGeneratorReturnType, foobarUint8Array, 'utf16le', true, false, false, execaSync);91+test('Generator can return string with encoding "buffer", sync', testGeneratorReturnType, foobarString, 'buffer', true, false, false, execaSync);92+test('Generator can return Uint8Array with encoding "buffer", sync', testGeneratorReturnType, foobarUint8Array, 'buffer', true, false, false, execaSync);93+test('Generator can return string with encoding "hex", sync', testGeneratorReturnType, foobarString, 'hex', true, false, false, execaSync);94+test('Generator can return Uint8Array with encoding "hex", sync', testGeneratorReturnType, foobarUint8Array, 'hex', true, false, false, execaSync);95+test('Generator can return string with default encoding, failure, sync', testGeneratorReturnType, foobarString, 'utf8', false, false, false, execaSync);96+test('Generator can return Uint8Array with default encoding, failure, sync', testGeneratorReturnType, foobarUint8Array, 'utf8', false, false, false, execaSync);97+test('Generator can return string with encoding "utf16le", failure, sync', testGeneratorReturnType, foobarString, 'utf16le', false, false, false, execaSync);98+test('Generator can return Uint8Array with encoding "utf16le", failure, sync', testGeneratorReturnType, foobarUint8Array, 'utf16le', false, false, false, execaSync);99+test('Generator can return string with encoding "buffer", failure, sync', testGeneratorReturnType, foobarString, 'buffer', false, false, false, execaSync);100+test('Generator can return Uint8Array with encoding "buffer", failure, sync', testGeneratorReturnType, foobarUint8Array, 'buffer', false, false, false, execaSync);101+test('Generator can return string with encoding "hex", failure, sync', testGeneratorReturnType, foobarString, 'hex', false, false, false, execaSync);102+test('Generator can return Uint8Array with encoding "hex", failure, sync', testGeneratorReturnType, foobarUint8Array, 'hex', false, false, false, execaSync);103+test('Generator can return string with default encoding, objectMode, sync', testGeneratorReturnType, foobarString, 'utf8', true, true, false, execaSync);104+test('Generator can return Uint8Array with default encoding, objectMode, sync', testGeneratorReturnType, foobarUint8Array, 'utf8', true, true, false, execaSync);105+test('Generator can return string with encoding "utf16le", objectMode, sync', testGeneratorReturnType, foobarString, 'utf16le', true, true, false, execaSync);106+test('Generator can return Uint8Array with encoding "utf16le", objectMode, sync', testGeneratorReturnType, foobarUint8Array, 'utf16le', true, true, false, execaSync);107+test('Generator can return string with encoding "buffer", objectMode, sync', testGeneratorReturnType, foobarString, 'buffer', true, true, false, execaSync);108+test('Generator can return Uint8Array with encoding "buffer", objectMode, sync', testGeneratorReturnType, foobarUint8Array, 'buffer', true, true, false, execaSync);109+test('Generator can return string with encoding "hex", objectMode, sync', testGeneratorReturnType, foobarString, 'hex', true, true, false, execaSync);110+test('Generator can return Uint8Array with encoding "hex", objectMode, sync', testGeneratorReturnType, foobarUint8Array, 'hex', true, true, false, execaSync);111+test('Generator can return string with default encoding, objectMode, failure, sync', testGeneratorReturnType, foobarString, 'utf8', false, true, false, execaSync);112+test('Generator can return Uint8Array with default encoding, objectMode, failure, sync', testGeneratorReturnType, foobarUint8Array, 'utf8', false, true, false, execaSync);113+test('Generator can return string with encoding "utf16le", objectMode, failure, sync', testGeneratorReturnType, foobarString, 'utf16le', false, true, false, execaSync);114+test('Generator can return Uint8Array with encoding "utf16le", objectMode, failure, sync', testGeneratorReturnType, foobarUint8Array, 'utf16le', false, true, false, execaSync);115+test('Generator can return string with encoding "buffer", objectMode, failure, sync', testGeneratorReturnType, foobarString, 'buffer', false, true, false, execaSync);116+test('Generator can return Uint8Array with encoding "buffer", objectMode, failure, sync', testGeneratorReturnType, foobarUint8Array, 'buffer', false, true, false, execaSync);117+test('Generator can return string with encoding "hex", objectMode, failure, sync', testGeneratorReturnType, foobarString, 'hex', false, true, false, execaSync);118+test('Generator can return Uint8Array with encoding "hex", objectMode, failure, sync', testGeneratorReturnType, foobarUint8Array, 'hex', false, true, false, execaSync);119+test('Generator can return final string with default encoding, sync', testGeneratorReturnType, foobarString, 'utf8', true, false, true, execaSync);120+test('Generator can return final Uint8Array with default encoding, sync', testGeneratorReturnType, foobarUint8Array, 'utf8', true, false, true, execaSync);121+test('Generator can return final string with encoding "utf16le", sync', testGeneratorReturnType, foobarString, 'utf16le', true, false, true, execaSync);122+test('Generator can return final Uint8Array with encoding "utf16le", sync', testGeneratorReturnType, foobarUint8Array, 'utf16le', true, false, true, execaSync);123+test('Generator can return final string with encoding "buffer", sync', testGeneratorReturnType, foobarString, 'buffer', true, false, true, execaSync);124+test('Generator can return final Uint8Array with encoding "buffer", sync', testGeneratorReturnType, foobarUint8Array, 'buffer', true, false, true, execaSync);125+test('Generator can return final string with encoding "hex", sync', testGeneratorReturnType, foobarString, 'hex', true, false, true, execaSync);126+test('Generator can return final Uint8Array with encoding "hex", sync', testGeneratorReturnType, foobarUint8Array, 'hex', true, false, true, execaSync);127+test('Generator can return final string with default encoding, failure, sync', testGeneratorReturnType, foobarString, 'utf8', false, false, true, execaSync);128+test('Generator can return final Uint8Array with default encoding, failure, sync', testGeneratorReturnType, foobarUint8Array, 'utf8', false, false, true, execaSync);129+test('Generator can return final string with encoding "utf16le", failure, sync', testGeneratorReturnType, foobarString, 'utf16le', false, false, true, execaSync);130+test('Generator can return final Uint8Array with encoding "utf16le", failure, sync', testGeneratorReturnType, foobarUint8Array, 'utf16le', false, false, true, execaSync);131+test('Generator can return final string with encoding "buffer", failure, sync', testGeneratorReturnType, foobarString, 'buffer', false, false, true, execaSync);132+test('Generator can return final Uint8Array with encoding "buffer", failure, sync', testGeneratorReturnType, foobarUint8Array, 'buffer', false, false, true, execaSync);133+test('Generator can return final string with encoding "hex", failure, sync', testGeneratorReturnType, foobarString, 'hex', false, false, true, execaSync);134+test('Generator can return final Uint8Array with encoding "hex", failure, sync', testGeneratorReturnType, foobarUint8Array, 'hex', false, false, true, execaSync);135+test('Generator can return final string with default encoding, objectMode, sync', testGeneratorReturnType, foobarString, 'utf8', true, true, true, execaSync);136+test('Generator can return final Uint8Array with default encoding, objectMode, sync', testGeneratorReturnType, foobarUint8Array, 'utf8', true, true, true, execaSync);137+test('Generator can return final string with encoding "utf16le", objectMode, sync', testGeneratorReturnType, foobarString, 'utf16le', true, true, true, execaSync);138+test('Generator can return final Uint8Array with encoding "utf16le", objectMode, sync', testGeneratorReturnType, foobarUint8Array, 'utf16le', true, true, true, execaSync);139+test('Generator can return final string with encoding "buffer", objectMode, sync', testGeneratorReturnType, foobarString, 'buffer', true, true, true, execaSync);140+test('Generator can return final Uint8Array with encoding "buffer", objectMode, sync', testGeneratorReturnType, foobarUint8Array, 'buffer', true, true, true, execaSync);141+test('Generator can return final string with encoding "hex", objectMode, sync', testGeneratorReturnType, foobarString, 'hex', true, true, true, execaSync);142+test('Generator can return final Uint8Array with encoding "hex", objectMode, sync', testGeneratorReturnType, foobarUint8Array, 'hex', true, true, true, execaSync);143+test('Generator can return final string with default encoding, objectMode, failure, sync', testGeneratorReturnType, foobarString, 'utf8', false, true, true, execaSync);144+test('Generator can return final Uint8Array with default encoding, objectMode, failure, sync', testGeneratorReturnType, foobarUint8Array, 'utf8', false, true, true, execaSync);145+test('Generator can return final string with encoding "utf16le", objectMode, failure, sync', testGeneratorReturnType, foobarString, 'utf16le', false, true, true, execaSync);146+test('Generator can return final Uint8Array with encoding "utf16le", objectMode, failure, sync', testGeneratorReturnType, foobarUint8Array, 'utf16le', false, true, true, execaSync);147+test('Generator can return final string with encoding "buffer", objectMode, failure, sync', testGeneratorReturnType, foobarString, 'buffer', false, true, true, execaSync);148+test('Generator can return final Uint8Array with encoding "buffer", objectMode, failure, sync', testGeneratorReturnType, foobarUint8Array, 'buffer', false, true, true, execaSync);149+test('Generator can return final string with encoding "hex", objectMode, failure, sync', testGeneratorReturnType, foobarString, 'hex', false, true, true, execaSync);150+test('Generator can return final Uint8Array with encoding "hex", objectMode, failure, sync', testGeneratorReturnType, foobarUint8Array, 'hex', false, true, true, execaSync);added:test/transform/normalize-transform.js+55 added
1+import test from 'ava';2+import {execa, execaSync} from '../../index.js';3+import {setFixtureDir} from '../helpers/fixtures-dir.js';4+import {foobarString, foobarUppercase, foobarUint8Array} from '../helpers/input.js';5+import {casedSuffix} from '../helpers/generator.js';6+import {generatorsMap} from '../helpers/map.js';7+8+setFixtureDir();9+10+const testAppendInput = async (t, reversed, type, execaMethod) => {11+ const stdin = [foobarUint8Array, generatorsMap[type].uppercase(), generatorsMap[type].append()];12+ const reversedStdin = reversed ? stdin.reverse() : stdin;13+ const {stdout} = await execaMethod('stdin-fd.js', ['0'], {stdin: reversedStdin});14+ const reversedSuffix = reversed ? casedSuffix.toUpperCase() : casedSuffix;15+ t.is(stdout, `${foobarUppercase}${reversedSuffix}`);16+};17+18+test('Can use multiple generators as input', testAppendInput, false, 'generator', execa);19+test('Can use multiple generators as input, reversed', testAppendInput, true, 'generator', execa);20+test('Can use multiple generators as input, sync', testAppendInput, false, 'generator', execaSync);21+test('Can use multiple generators as input, reversed, sync', testAppendInput, true, 'generator', execaSync);22+test('Can use multiple duplexes as input', testAppendInput, false, 'duplex', execa);23+test('Can use multiple duplexes as input, reversed', testAppendInput, true, 'duplex', execa);24+test('Can use multiple webTransforms as input', testAppendInput, false, 'webTransform', execa);25+test('Can use multiple webTransforms as input, reversed', testAppendInput, true, 'webTransform', execa);26+27+const testAppendOutput = async (t, reversed, type, execaMethod) => {28+ const stdoutOption = [generatorsMap[type].uppercase(), generatorsMap[type].append()];29+ const reversedStdoutOption = reversed ? stdoutOption.reverse() : stdoutOption;30+ const {stdout} = await execaMethod('noop-fd.js', ['1', foobarString], {stdout: reversedStdoutOption});31+ const reversedSuffix = reversed ? casedSuffix.toUpperCase() : casedSuffix;32+ t.is(stdout, `${foobarUppercase}${reversedSuffix}`);33+};34+35+test('Can use multiple generators as output', testAppendOutput, false, 'generator', execa);36+test('Can use multiple generators as output, reversed', testAppendOutput, true, 'generator', execa);37+test('Can use multiple generators as output, sync', testAppendOutput, false, 'generator', execaSync);38+test('Can use multiple generators as output, reversed, sync', testAppendOutput, true, 'generator', execaSync);39+test('Can use multiple duplexes as output', testAppendOutput, false, 'duplex', execa);40+test('Can use multiple duplexes as output, reversed', testAppendOutput, true, 'duplex', execa);41+test('Can use multiple webTransforms as output', testAppendOutput, false, 'webTransform', execa);42+test('Can use multiple webTransforms as output, reversed', testAppendOutput, true, 'webTransform', execa);43+44+const testGeneratorSyntax = async (t, type, usePlainObject, execaMethod) => {45+ const transform = generatorsMap[type].uppercase();46+ const {stdout} = await execaMethod('noop-fd.js', ['1', foobarString], {stdout: usePlainObject ? transform : transform.transform});47+ t.is(stdout, foobarUppercase);48+};49+50+test('Can pass generators with an options plain object', testGeneratorSyntax, 'generator', false, execa);51+test('Can pass generators without an options plain object', testGeneratorSyntax, 'generator', true, execa);52+test('Can pass generators with an options plain object, sync', testGeneratorSyntax, 'generator', false, execaSync);53+test('Can pass generators without an options plain object, sync', testGeneratorSyntax, 'generator', true, execaSync);54+test('Can pass webTransforms with an options plain object', testGeneratorSyntax, 'webTransform', true, execa);55+test('Can pass webTransforms without an options plain object', testGeneratorSyntax, 'webTransform', false, execa);added:test/transform/split-binary.js+95 added
1+import test from 'ava';2+import {execa, execaSync} from '../../index.js';3+import {setFixtureDir} from '../helpers/fixtures-dir.js';4+import {getOutputsGenerator, resultGenerator} from '../helpers/generator.js';5+import {6+ simpleFull,7+ simpleChunks,8+ simpleFullUint8Array,9+ simpleFullUtf16Inverted,10+ simpleFullUtf16Uint8Array,11+ simpleChunksUint8Array,12+ simpleFullEnd,13+ simpleFullEndUtf16Inverted,14+ simpleFullHex,15+ simpleLines,16+ noNewlinesChunks,17+} from '../helpers/lines.js';18+19+setFixtureDir();20+21+// eslint-disable-next-line max-params22+const testBinaryOption = async (t, binary, input, expectedLines, expectedOutput, objectMode, preserveNewlines, encoding, execaMethod) => {23+ const lines = [];24+ const {stdout} = await execaMethod('noop.js', {25+ stdout: [26+ getOutputsGenerator(input)(false, true),27+ resultGenerator(lines)(objectMode, binary, preserveNewlines),28+ ],29+ stripFinalNewline: false,30+ encoding,31+ });32+ t.deepEqual(lines, expectedLines);33+ t.deepEqual(stdout, expectedOutput);34+};35+36+test('Does not split lines when "binary" is true', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFull, false, true, 'utf8', execa);37+test('Splits lines when "binary" is false', testBinaryOption, false, simpleChunks, simpleLines, simpleFull, false, true, 'utf8', execa);38+test('Splits lines when "binary" is undefined', testBinaryOption, undefined, simpleChunks, simpleLines, simpleFull, false, true, 'utf8', execa);39+test('Does not split lines when "binary" is true, encoding "utf16le"', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUtf16Inverted, false, true, 'utf16le', execa);40+test('Splits lines when "binary" is false, encoding "utf16le"', testBinaryOption, false, [simpleFullUtf16Uint8Array], simpleLines, simpleFullUtf16Inverted, false, true, 'utf16le', execa);41+test('Splits lines when "binary" is undefined, encoding "utf16le"', testBinaryOption, undefined, [simpleFullUtf16Uint8Array], simpleLines, simpleFullUtf16Inverted, false, true, 'utf16le', execa);42+test('Does not split lines when "binary" is true, encoding "buffer"', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, true, 'buffer', execa);43+test('Does not split lines when "binary" is undefined, encoding "buffer"', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, true, 'buffer', execa);44+test('Does not split lines when "binary" is false, encoding "buffer"', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, true, 'buffer', execa);45+test('Does not split lines when "binary" is true, encoding "hex"', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, true, 'hex', execa);46+test('Does not split lines when "binary" is undefined, encoding "hex"', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, true, 'hex', execa);47+test('Does not split lines when "binary" is false, encoding "hex"', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, true, 'hex', execa);48+test('Does not split lines when "binary" is true, objectMode', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleChunksUint8Array, true, true, 'utf8', execa);49+test('Splits lines when "binary" is false, objectMode', testBinaryOption, false, simpleChunks, simpleLines, simpleLines, true, true, 'utf8', execa);50+test('Splits lines when "binary" is undefined, objectMode', testBinaryOption, undefined, simpleChunks, simpleLines, simpleLines, true, true, 'utf8', execa);51+test('Does not split lines when "binary" is true, preserveNewlines', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFull, false, false, 'utf8', execa);52+test('Splits lines when "binary" is false, preserveNewlines', testBinaryOption, false, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, 'utf8', execa);53+test('Splits lines when "binary" is undefined, preserveNewlines', testBinaryOption, undefined, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, 'utf8', execa);54+test('Does not split lines when "binary" is true, preserveNewlines, encoding "utf16le"', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUtf16Inverted, false, false, 'utf16le', execa);55+test('Splits lines when "binary" is false, preserveNewlines, encoding "utf16le"', testBinaryOption, false, [simpleFullUtf16Uint8Array], noNewlinesChunks, simpleFullEndUtf16Inverted, false, false, 'utf16le', execa);56+test('Splits lines when "binary" is undefined, preserveNewlines, encoding "utf16le"', testBinaryOption, undefined, [simpleFullUtf16Uint8Array], noNewlinesChunks, simpleFullEndUtf16Inverted, false, false, 'utf16le', execa);57+test('Does not split lines when "binary" is true, encoding "buffer", preserveNewlines', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, false, 'buffer', execa);58+test('Does not split lines when "binary" is undefined, encoding "buffer", preserveNewlines', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, false, 'buffer', execa);59+test('Does not split lines when "binary" is false, encoding "buffer", preserveNewlines', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, false, 'buffer', execa);60+test('Does not split lines when "binary" is true, objectMode, preserveNewlines', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleChunksUint8Array, true, false, 'utf8', execa);61+test('Does not split lines when "binary" is true, encoding "hex", preserveNewlines', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, false, 'hex', execa);62+test('Does not split lines when "binary" is undefined, encoding "hex", preserveNewlines', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, false, 'hex', execa);63+test('Does not split lines when "binary" is false, encoding "hex", preserveNewlines', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, false, 'hex', execa);64+test('Splits lines when "binary" is false, objectMode, preserveNewlines', testBinaryOption, false, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, 'utf8', execa);65+test('Splits lines when "binary" is undefined, objectMode, preserveNewlines', testBinaryOption, undefined, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, 'utf8', execa);66+test('Does not split lines when "binary" is true, sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFull, false, true, 'utf8', execaSync);67+test('Splits lines when "binary" is false, sync', testBinaryOption, false, simpleChunks, simpleLines, simpleFull, false, true, 'utf8', execaSync);68+test('Splits lines when "binary" is undefined, sync', testBinaryOption, undefined, simpleChunks, simpleLines, simpleFull, false, true, 'utf8', execaSync);69+test('Does not split lines when "binary" is true, encoding "utf16le", sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUtf16Inverted, false, true, 'utf16le', execaSync);70+test('Splits lines when "binary" is false, encoding "utf16le", sync', testBinaryOption, false, [simpleFullUtf16Uint8Array], simpleLines, simpleFullUtf16Inverted, false, true, 'utf16le', execaSync);71+test('Splits lines when "binary" is undefined, encoding "utf16le", sync', testBinaryOption, undefined, [simpleFullUtf16Uint8Array], simpleLines, simpleFullUtf16Inverted, false, true, 'utf16le', execaSync);72+test('Does not split lines when "binary" is true, encoding "buffer", sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, true, 'buffer', execaSync);73+test('Does not split lines when "binary" is undefined, encoding "buffer", sync', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, true, 'buffer', execaSync);74+test('Does not split lines when "binary" is false, encoding "buffer", sync', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, true, 'buffer', execaSync);75+test('Does not split lines when "binary" is true, encoding "hex", sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, true, 'hex', execaSync);76+test('Does not split lines when "binary" is undefined, encoding "hex", sync', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, true, 'hex', execaSync);77+test('Does not split lines when "binary" is false, encoding "hex", sync', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, true, 'hex', execaSync);78+test('Does not split lines when "binary" is true, objectMode, sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleChunksUint8Array, true, true, 'utf8', execaSync);79+test('Splits lines when "binary" is false, objectMode, sync', testBinaryOption, false, simpleChunks, simpleLines, simpleLines, true, true, 'utf8', execaSync);80+test('Splits lines when "binary" is undefined, objectMode, sync', testBinaryOption, undefined, simpleChunks, simpleLines, simpleLines, true, true, 'utf8', execaSync);81+test('Does not split lines when "binary" is true, preserveNewlines, sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFull, false, false, 'utf8', execaSync);82+test('Splits lines when "binary" is false, preserveNewlines, sync', testBinaryOption, false, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, 'utf8', execaSync);83+test('Splits lines when "binary" is undefined, preserveNewlines, sync', testBinaryOption, undefined, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, 'utf8', execaSync);84+test('Does not split lines when "binary" is true, preserveNewlines, encoding "utf16le", sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUtf16Inverted, false, false, 'utf16le', execaSync);85+test('Splits lines when "binary" is false, preserveNewlines, encoding "utf16le", sync', testBinaryOption, false, [simpleFullUtf16Uint8Array], noNewlinesChunks, simpleFullEndUtf16Inverted, false, false, 'utf16le', execaSync);86+test('Splits lines when "binary" is undefined, preserveNewlines, encoding "utf16le", sync', testBinaryOption, undefined, [simpleFullUtf16Uint8Array], noNewlinesChunks, simpleFullEndUtf16Inverted, false, false, 'utf16le', execaSync);87+test('Does not split lines when "binary" is true, encoding "buffer", preserveNewlines, sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, false, 'buffer', execaSync);88+test('Does not split lines when "binary" is undefined, encoding "buffer", preserveNewlines, sync', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, false, 'buffer', execaSync);89+test('Does not split lines when "binary" is false, encoding "buffer", preserveNewlines, sync', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, false, 'buffer', execaSync);90+test('Does not split lines when "binary" is true, objectMode, preserveNewlines, sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleChunksUint8Array, true, false, 'utf8', execaSync);91+test('Does not split lines when "binary" is true, encoding "hex", preserveNewlines, sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, false, 'hex', execaSync);92+test('Does not split lines when "binary" is undefined, encoding "hex", preserveNewlines, sync', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, false, 'hex', execaSync);93+test('Does not split lines when "binary" is false, encoding "hex", preserveNewlines, sync', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, false, 'hex', execaSync);94+test('Splits lines when "binary" is false, objectMode, preserveNewlines, sync', testBinaryOption, false, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, 'utf8', execaSync);95+test('Splits lines when "binary" is undefined, objectMode, preserveNewlines, sync', testBinaryOption, undefined, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, 'utf8', execaSync);added:test/transform/split-lines.js+174 added
1+import test from 'ava';2+import {execa, execaSync} from '../../index.js';3+import {setFixtureDir} from '../helpers/fixtures-dir.js';4+import {getStdio} from '../helpers/stdio.js';5+import {getOutputsGenerator, resultGenerator} from '../helpers/generator.js';6+import {7+ singleFull,8+ singleFullEnd,9+ simpleFull,10+ simpleChunks,11+ simpleFullEnd,12+ simpleFullEndChunks,13+ simpleLines,14+ simpleFullEndLines,15+ noNewlinesFull,16+ noNewlinesChunks,17+} from '../helpers/lines.js';18+19+setFixtureDir();20+21+const windowsFull = 'aaa\r\nbbb\r\nccc';22+const windowsFullEnd = `${windowsFull}\r\n`;23+const windowsChunks = [windowsFull];24+const windowsLines = ['aaa\r\n', 'bbb\r\n', 'ccc'];25+const noNewlinesFullEnd = `${noNewlinesFull}\n`;26+const noNewlinesLines = ['aaabbbccc'];27+const singleChunks = [singleFull];28+const noLines = [];29+const emptyFull = '';30+const emptyChunks = [emptyFull];31+const manyEmptyChunks = [emptyFull, emptyFull, emptyFull];32+const newlineFull = '\n';33+const newlineChunks = [newlineFull];34+const newlinesFull = '\n\n\n';35+const newlinesChunks = [newlinesFull];36+const newlinesLines = ['\n', '\n', '\n'];37+const windowsNewlinesFull = '\r\n\r\n\r\n';38+const windowsNewlinesChunks = [windowsNewlinesFull];39+const windowsNewlinesLines = ['\r\n', '\r\n', '\r\n'];40+const runOverChunks = ['aaa\nb', 'b', 'b\nccc'];41+const bigFull = '.'.repeat(1e5);42+const bigFullEnd = `${bigFull}\n`;43+const bigChunks = [bigFull];44+const manyChunks = Array.from({length: 1e3}).fill('.');45+const manyFull = manyChunks.join('');46+const manyFullEnd = `${manyFull}\n`;47+const manyLines = [manyFull];48+49+// eslint-disable-next-line max-params50+const testLines = async (t, fdNumber, input, expectedLines, expectedOutput, objectMode, preserveNewlines, execaMethod) => {51+ const lines = [];52+ const {stdio} = await execaMethod('noop-fd.js', [`${fdNumber}`], {53+ ...getStdio(fdNumber, [54+ getOutputsGenerator(input)(false, true),55+ resultGenerator(lines)(objectMode, false, preserveNewlines),56+ ]),57+ stripFinalNewline: false,58+ });59+ t.deepEqual(lines, expectedLines);60+ t.deepEqual(stdio[fdNumber], expectedOutput);61+};62+63+test('Split stdout - n newlines, 1 chunk', testLines, 1, simpleChunks, simpleLines, simpleFull, false, true, execa);64+test('Split stderr - n newlines, 1 chunk', testLines, 2, simpleChunks, simpleLines, simpleFull, false, true, execa);65+test('Split stdio[*] - n newlines, 1 chunk', testLines, 3, simpleChunks, simpleLines, simpleFull, false, true, execa);66+test('Split stdout - preserveNewlines, n chunks', testLines, 1, noNewlinesChunks, noNewlinesLines, noNewlinesFull, false, true, execa);67+test('Split stdout - 0 newlines, 1 chunk', testLines, 1, singleChunks, singleChunks, singleFull, false, true, execa);68+test('Split stdout - empty, 1 chunk', testLines, 1, emptyChunks, noLines, emptyFull, false, true, execa);69+test('Split stdout - Windows newlines', testLines, 1, windowsChunks, windowsLines, windowsFull, false, true, execa);70+test('Split stdout - chunk ends with newline', testLines, 1, simpleFullEndChunks, simpleFullEndLines, simpleFullEnd, false, true, execa);71+test('Split stdout - single newline', testLines, 1, newlineChunks, newlineChunks, newlineFull, false, true, execa);72+test('Split stdout - only newlines', testLines, 1, newlinesChunks, newlinesLines, newlinesFull, false, true, execa);73+test('Split stdout - only Windows newlines', testLines, 1, windowsNewlinesChunks, windowsNewlinesLines, windowsNewlinesFull, false, true, execa);74+test('Split stdout - line split over multiple chunks', testLines, 1, runOverChunks, simpleLines, simpleFull, false, true, execa);75+test('Split stdout - 0 newlines, big line', testLines, 1, bigChunks, bigChunks, bigFull, false, true, execa);76+test('Split stdout - 0 newlines, many chunks', testLines, 1, manyChunks, manyLines, manyFull, false, true, execa);77+test('Split stdout - n newlines, 1 chunk, objectMode', testLines, 1, simpleChunks, simpleLines, simpleLines, true, true, execa);78+test('Split stderr - n newlines, 1 chunk, objectMode', testLines, 2, simpleChunks, simpleLines, simpleLines, true, true, execa);79+test('Split stdio[*] - n newlines, 1 chunk, objectMode', testLines, 3, simpleChunks, simpleLines, simpleLines, true, true, execa);80+test('Split stdout - preserveNewlines, n chunks, objectMode', testLines, 1, noNewlinesChunks, noNewlinesLines, noNewlinesLines, true, true, execa);81+test('Split stdout - empty, 1 chunk, objectMode', testLines, 1, emptyChunks, noLines, noLines, true, true, execa);82+test('Split stdout - 0 newlines, 1 chunk, objectMode', testLines, 1, singleChunks, singleChunks, singleChunks, true, true, execa);83+test('Split stdout - Windows newlines, objectMode', testLines, 1, windowsChunks, windowsLines, windowsLines, true, true, execa);84+test('Split stdout - chunk ends with newline, objectMode', testLines, 1, simpleFullEndChunks, simpleFullEndLines, simpleFullEndLines, true, true, execa);85+test('Split stdout - single newline, objectMode', testLines, 1, newlineChunks, newlineChunks, newlineChunks, true, true, execa);86+test('Split stdout - only newlines, objectMode', testLines, 1, newlinesChunks, newlinesLines, newlinesLines, true, true, execa);87+test('Split stdout - only Windows newlines, objectMode', testLines, 1, windowsNewlinesChunks, windowsNewlinesLines, windowsNewlinesLines, true, true, execa);88+test('Split stdout - line split over multiple chunks, objectMode', testLines, 1, runOverChunks, simpleLines, simpleLines, true, true, execa);89+test('Split stdout - 0 newlines, big line, objectMode', testLines, 1, bigChunks, bigChunks, bigChunks, true, true, execa);90+test('Split stdout - 0 newlines, many chunks, objectMode', testLines, 1, manyChunks, manyLines, manyLines, true, true, execa);91+test('Split stdout - n newlines, 1 chunk, preserveNewlines', testLines, 1, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, execa);92+test('Split stderr - n newlines, 1 chunk, preserveNewlines', testLines, 2, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, execa);93+test('Split stdio[*] - n newlines, 1 chunk, preserveNewlines', testLines, 3, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, execa);94+test('Split stdout - preserveNewlines, n chunks, preserveNewlines', testLines, 1, noNewlinesChunks, noNewlinesLines, noNewlinesFullEnd, false, false, execa);95+test('Split stdout - empty, 1 chunk, preserveNewlines', testLines, 1, emptyChunks, noLines, emptyFull, false, false, execa);96+test('Split stdout - 0 newlines, 1 chunk, preserveNewlines', testLines, 1, singleChunks, singleChunks, singleFullEnd, false, false, execa);97+test('Split stdout - Windows newlines, preserveNewlines', testLines, 1, windowsChunks, noNewlinesChunks, windowsFullEnd, false, false, execa);98+test('Split stdout - chunk ends with newline, preserveNewlines', testLines, 1, simpleFullEndChunks, noNewlinesChunks, simpleFullEnd, false, false, execa);99+test('Split stdout - single newline, preserveNewlines', testLines, 1, newlineChunks, emptyChunks, newlineFull, false, false, execa);100+test('Split stdout - only newlines, preserveNewlines', testLines, 1, newlinesChunks, manyEmptyChunks, newlinesFull, false, false, execa);101+test('Split stdout - only Windows newlines, preserveNewlines', testLines, 1, windowsNewlinesChunks, manyEmptyChunks, windowsNewlinesFull, false, false, execa);102+test('Split stdout - line split over multiple chunks, preserveNewlines', testLines, 1, runOverChunks, noNewlinesChunks, simpleFullEnd, false, false, execa);103+test('Split stdout - 0 newlines, big line, preserveNewlines', testLines, 1, bigChunks, bigChunks, bigFullEnd, false, false, execa);104+test('Split stdout - 0 newlines, many chunks, preserveNewlines', testLines, 1, manyChunks, manyLines, manyFullEnd, false, false, execa);105+test('Split stdout - n newlines, 1 chunk, objectMode, preserveNewlines', testLines, 1, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, execa);106+test('Split stderr - n newlines, 1 chunk, objectMode, preserveNewlines', testLines, 2, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, execa);107+test('Split stdio[*] - n newlines, 1 chunk, objectMode, preserveNewlines', testLines, 3, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, execa);108+test('Split stdout - preserveNewlines, n chunks, objectMode, preserveNewlines', testLines, 1, noNewlinesChunks, noNewlinesLines, noNewlinesLines, true, false, execa);109+test('Split stdout - empty, 1 chunk, objectMode, preserveNewlines', testLines, 1, emptyChunks, noLines, noLines, true, false, execa);110+test('Split stdout - 0 newlines, 1 chunk, objectMode, preserveNewlines', testLines, 1, singleChunks, singleChunks, singleChunks, true, false, execa);111+test('Split stdout - Windows newlines, objectMode, preserveNewlines', testLines, 1, windowsChunks, noNewlinesChunks, noNewlinesChunks, true, false, execa);112+test('Split stdout - chunk ends with newline, objectMode, preserveNewlines', testLines, 1, simpleFullEndChunks, noNewlinesChunks, noNewlinesChunks, true, false, execa);113+test('Split stdout - single newline, objectMode, preserveNewlines', testLines, 1, newlineChunks, emptyChunks, emptyChunks, true, false, execa);114+test('Split stdout - only newlines, objectMode, preserveNewlines', testLines, 1, newlinesChunks, manyEmptyChunks, manyEmptyChunks, true, false, execa);115+test('Split stdout - only Windows newlines, objectMode, preserveNewlines', testLines, 1, windowsNewlinesChunks, manyEmptyChunks, manyEmptyChunks, true, false, execa);116+test('Split stdout - line split over multiple chunks, objectMode, preserveNewlines', testLines, 1, runOverChunks, noNewlinesChunks, noNewlinesChunks, true, false, execa);117+test('Split stdout - 0 newlines, big line, objectMode, preserveNewlines', testLines, 1, bigChunks, bigChunks, bigChunks, true, false, execa);118+test('Split stdout - 0 newlines, many chunks, objectMode, preserveNewlines', testLines, 1, manyChunks, manyLines, manyLines, true, false, execa);119+test('Split stdout - n newlines, 1 chunk, sync', testLines, 1, simpleChunks, simpleLines, simpleFull, false, true, execaSync);120+test('Split stderr - n newlines, 1 chunk, sync', testLines, 2, simpleChunks, simpleLines, simpleFull, false, true, execaSync);121+test('Split stdio[*] - n newlines, 1 chunk, sync', testLines, 3, simpleChunks, simpleLines, simpleFull, false, true, execaSync);122+test('Split stdout - preserveNewlines, n chunks, sync', testLines, 1, noNewlinesChunks, noNewlinesLines, noNewlinesFull, false, true, execaSync);123+test('Split stdout - 0 newlines, 1 chunk, sync', testLines, 1, singleChunks, singleChunks, singleFull, false, true, execaSync);124+test('Split stdout - empty, 1 chunk, sync', testLines, 1, emptyChunks, noLines, emptyFull, false, true, execaSync);125+test('Split stdout - Windows newlines, sync', testLines, 1, windowsChunks, windowsLines, windowsFull, false, true, execaSync);126+test('Split stdout - chunk ends with newline, sync', testLines, 1, simpleFullEndChunks, simpleFullEndLines, simpleFullEnd, false, true, execaSync);127+test('Split stdout - single newline, sync', testLines, 1, newlineChunks, newlineChunks, newlineFull, false, true, execaSync);128+test('Split stdout - only newlines, sync', testLines, 1, newlinesChunks, newlinesLines, newlinesFull, false, true, execaSync);129+test('Split stdout - only Windows newlines, sync', testLines, 1, windowsNewlinesChunks, windowsNewlinesLines, windowsNewlinesFull, false, true, execaSync);130+test('Split stdout - line split over multiple chunks, sync', testLines, 1, runOverChunks, simpleLines, simpleFull, false, true, execaSync);131+test('Split stdout - 0 newlines, big line, sync', testLines, 1, bigChunks, bigChunks, bigFull, false, true, execaSync);132+test('Split stdout - 0 newlines, many chunks, sync', testLines, 1, manyChunks, manyLines, manyFull, false, true, execaSync);133+test('Split stdout - n newlines, 1 chunk, objectMode, sync', testLines, 1, simpleChunks, simpleLines, simpleLines, true, true, execaSync);134+test('Split stderr - n newlines, 1 chunk, objectMode, sync', testLines, 2, simpleChunks, simpleLines, simpleLines, true, true, execaSync);135+test('Split stdio[*] - n newlines, 1 chunk, objectMode, sync', testLines, 3, simpleChunks, simpleLines, simpleLines, true, true, execaSync);136+test('Split stdout - preserveNewlines, n chunks, objectMode, sync', testLines, 1, noNewlinesChunks, noNewlinesLines, noNewlinesLines, true, true, execaSync);137+test('Split stdout - empty, 1 chunk, objectMode, sync', testLines, 1, emptyChunks, noLines, noLines, true, true, execaSync);138+test('Split stdout - 0 newlines, 1 chunk, objectMode, sync', testLines, 1, singleChunks, singleChunks, singleChunks, true, true, execaSync);139+test('Split stdout - Windows newlines, objectMode, sync', testLines, 1, windowsChunks, windowsLines, windowsLines, true, true, execaSync);140+test('Split stdout - chunk ends with newline, objectMode, sync', testLines, 1, simpleFullEndChunks, simpleFullEndLines, simpleFullEndLines, true, true, execaSync);141+test('Split stdout - single newline, objectMode, sync', testLines, 1, newlineChunks, newlineChunks, newlineChunks, true, true, execaSync);142+test('Split stdout - only newlines, objectMode, sync', testLines, 1, newlinesChunks, newlinesLines, newlinesLines, true, true, execaSync);143+test('Split stdout - only Windows newlines, objectMode, sync', testLines, 1, windowsNewlinesChunks, windowsNewlinesLines, windowsNewlinesLines, true, true, execaSync);144+test('Split stdout - line split over multiple chunks, objectMode, sync', testLines, 1, runOverChunks, simpleLines, simpleLines, true, true, execaSync);145+test('Split stdout - 0 newlines, big line, objectMode, sync', testLines, 1, bigChunks, bigChunks, bigChunks, true, true, execaSync);146+test('Split stdout - 0 newlines, many chunks, objectMode, sync', testLines, 1, manyChunks, manyLines, manyLines, true, true, execaSync);147+test('Split stdout - n newlines, 1 chunk, preserveNewlines, sync', testLines, 1, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, execaSync);148+test('Split stderr - n newlines, 1 chunk, preserveNewlines, sync', testLines, 2, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, execaSync);149+test('Split stdio[*] - n newlines, 1 chunk, preserveNewlines, sync', testLines, 3, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, execaSync);150+test('Split stdout - preserveNewlines, n chunks, preserveNewlines, sync', testLines, 1, noNewlinesChunks, noNewlinesLines, noNewlinesFullEnd, false, false, execaSync);151+test('Split stdout - empty, 1 chunk, preserveNewlines, sync', testLines, 1, emptyChunks, noLines, emptyFull, false, false, execaSync);152+test('Split stdout - 0 newlines, 1 chunk, preserveNewlines, sync', testLines, 1, singleChunks, singleChunks, singleFullEnd, false, false, execaSync);153+test('Split stdout - Windows newlines, preserveNewlines, sync', testLines, 1, windowsChunks, noNewlinesChunks, windowsFullEnd, false, false, execaSync);154+test('Split stdout - chunk ends with newline, preserveNewlines, sync', testLines, 1, simpleFullEndChunks, noNewlinesChunks, simpleFullEnd, false, false, execaSync);155+test('Split stdout - single newline, preserveNewlines, sync', testLines, 1, newlineChunks, emptyChunks, newlineFull, false, false, execaSync);156+test('Split stdout - only newlines, preserveNewlines, sync', testLines, 1, newlinesChunks, manyEmptyChunks, newlinesFull, false, false, execaSync);157+test('Split stdout - only Windows newlines, preserveNewlines, sync', testLines, 1, windowsNewlinesChunks, manyEmptyChunks, windowsNewlinesFull, false, false, execaSync);158+test('Split stdout - line split over multiple chunks, preserveNewlines, sync', testLines, 1, runOverChunks, noNewlinesChunks, simpleFullEnd, false, false, execaSync);159+test('Split stdout - 0 newlines, big line, preserveNewlines, sync', testLines, 1, bigChunks, bigChunks, bigFullEnd, false, false, execaSync);160+test('Split stdout - 0 newlines, many chunks, preserveNewlines, sync', testLines, 1, manyChunks, manyLines, manyFullEnd, false, false, execaSync);161+test('Split stdout - n newlines, 1 chunk, objectMode, preserveNewlines, sync', testLines, 1, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, execaSync);162+test('Split stderr - n newlines, 1 chunk, objectMode, preserveNewlines, sync', testLines, 2, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, execaSync);163+test('Split stdio[*] - n newlines, 1 chunk, objectMode, preserveNewlines, sync', testLines, 3, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, execaSync);164+test('Split stdout - preserveNewlines, n chunks, objectMode, preserveNewlines, sync', testLines, 1, noNewlinesChunks, noNewlinesLines, noNewlinesLines, true, false, execaSync);165+test('Split stdout - empty, 1 chunk, objectMode, preserveNewlines, sync', testLines, 1, emptyChunks, noLines, noLines, true, false, execaSync);166+test('Split stdout - 0 newlines, 1 chunk, objectMode, preserveNewlines, sync', testLines, 1, singleChunks, singleChunks, singleChunks, true, false, execaSync);167+test('Split stdout - Windows newlines, objectMode, preserveNewlines, sync', testLines, 1, windowsChunks, noNewlinesChunks, noNewlinesChunks, true, false, execaSync);168+test('Split stdout - chunk ends with newline, objectMode, preserveNewlines, sync', testLines, 1, simpleFullEndChunks, noNewlinesChunks, noNewlinesChunks, true, false, execaSync);169+test('Split stdout - single newline, objectMode, preserveNewlines, sync', testLines, 1, newlineChunks, emptyChunks, emptyChunks, true, false, execaSync);170+test('Split stdout - only newlines, objectMode, preserveNewlines, sync', testLines, 1, newlinesChunks, manyEmptyChunks, manyEmptyChunks, true, false, execaSync);171+test('Split stdout - only Windows newlines, objectMode, preserveNewlines, sync', testLines, 1, windowsNewlinesChunks, manyEmptyChunks, manyEmptyChunks, true, false, execaSync);172+test('Split stdout - line split over multiple chunks, objectMode, preserveNewlines, sync', testLines, 1, runOverChunks, noNewlinesChunks, noNewlinesChunks, true, false, execaSync);173+test('Split stdout - 0 newlines, big line, objectMode, preserveNewlines, sync', testLines, 1, bigChunks, bigChunks, bigChunks, true, false, execaSync);174+test('Split stdout - 0 newlines, many chunks, objectMode, preserveNewlines, sync', testLines, 1, manyChunks, manyLines, manyLines, true, false, execaSync);added:test/transform/split-newline.js+37 added
1+import test from 'ava';2+import {execa, execaSync} from '../../index.js';3+import {setFixtureDir} from '../helpers/fixtures-dir.js';4+import {getOutputsGenerator, noopGenerator, noopAsyncGenerator} from '../helpers/generator.js';5+import {singleFull, singleFullEnd} from '../helpers/lines.js';6+7+setFixtureDir();8+9+const singleFullEndWindows = `${singleFull}\r\n`;10+const mixedNewlines = '.\n.\r\n.\n.\r\n.\n';11+12+const testStripNewline = async (t, input, expectedOutput, execaMethod) => {13+ const {stdout} = await execaMethod('noop.js', {14+ stdout: getOutputsGenerator([input])(),15+ stripFinalNewline: false,16+ });17+ t.is(stdout, expectedOutput);18+};19+20+test('Strips newline when user do not mistakenly yield one at the end', testStripNewline, singleFull, singleFullEnd, execa);21+test('Strips newline when user mistakenly yielded one at the end', testStripNewline, singleFullEnd, singleFullEnd, execa);22+test('Strips newline when user mistakenly yielded one at the end, Windows newline', testStripNewline, singleFullEndWindows, singleFullEndWindows, execa);23+test('Strips newline when user do not mistakenly yield one at the end, sync', testStripNewline, singleFull, singleFullEnd, execaSync);24+test('Strips newline when user mistakenly yielded one at the end, sync', testStripNewline, singleFullEnd, singleFullEnd, execaSync);25+test('Strips newline when user mistakenly yielded one at the end, Windows newline, sync', testStripNewline, singleFullEndWindows, singleFullEndWindows, execaSync);26+27+const testMixNewlines = async (t, generator, execaMethod) => {28+ const {stdout} = await execaMethod('noop-fd.js', ['1', mixedNewlines], {29+ stdout: generator(),30+ stripFinalNewline: false,31+ });32+ t.is(stdout, mixedNewlines);33+};34+35+test('Can mix Unix and Windows newlines', testMixNewlines, noopGenerator, execa);36+test('Can mix Unix and Windows newlines, sync', testMixNewlines, noopGenerator, execaSync);37+test('Can mix Unix and Windows newlines, async', testMixNewlines, noopAsyncGenerator, execa);added:test/transform/split-transform.js+78 added
1+import test from 'ava';2+import {execa, execaSync} from '../../index.js';3+import {setFixtureDir} from '../helpers/fixtures-dir.js';4+import {getOutputsGenerator, resultGenerator} from '../helpers/generator.js';5+import {foobarString, foobarUint8Array, foobarObject, foobarObjectString} from '../helpers/input.js';6+7+setFixtureDir();8+9+const resultUint8ArrayGenerator = function * (lines, chunk) {10+ lines.push(chunk);11+ yield new TextEncoder().encode(chunk);12+};13+14+// eslint-disable-next-line max-params15+const testStringToUint8Array = async (t, expectedOutput, objectMode, preserveNewlines, execaMethod) => {16+ const lines = [];17+ const {stdout} = await execaMethod('noop-fd.js', ['1', foobarString], {18+ stdout: {19+ transform: resultUint8ArrayGenerator.bind(undefined, lines),20+ objectMode,21+ preserveNewlines,22+ },23+ lines: true,24+ });25+ t.deepEqual(lines, [foobarString]);26+ t.deepEqual(stdout, expectedOutput);27+};28+29+test('Line splitting when converting from string to Uint8Array', testStringToUint8Array, [foobarString], false, true, execa);30+test('Line splitting when converting from string to Uint8Array, objectMode', testStringToUint8Array, [foobarUint8Array], true, true, execa);31+test('Line splitting when converting from string to Uint8Array, preserveNewlines', testStringToUint8Array, [foobarString], false, false, execa);32+test('Line splitting when converting from string to Uint8Array, objectMode, preserveNewlines', testStringToUint8Array, [foobarUint8Array], true, false, execa);33+test('Line splitting when converting from string to Uint8Array, sync', testStringToUint8Array, [foobarString], false, true, execaSync);34+test('Line splitting when converting from string to Uint8Array, objectMode, sync', testStringToUint8Array, [foobarUint8Array], true, true, execaSync);35+test('Line splitting when converting from string to Uint8Array, preserveNewlines, sync', testStringToUint8Array, [foobarString], false, false, execaSync);36+test('Line splitting when converting from string to Uint8Array, objectMode, preserveNewlines, sync', testStringToUint8Array, [foobarUint8Array], true, false, execaSync);37+38+const serializeResultGenerator = function * (lines, chunk) {39+ lines.push(chunk);40+ yield JSON.stringify(chunk);41+};42+43+const testUnsetObjectMode = async (t, expectedOutput, preserveNewlines, execaMethod) => {44+ const lines = [];45+ const {stdout} = await execaMethod('noop.js', {46+ stdout: [47+ getOutputsGenerator([foobarObject])(true),48+ {transform: serializeResultGenerator.bind(undefined, lines), preserveNewlines, objectMode: false},49+ ],50+ stripFinalNewline: false,51+ });52+ t.deepEqual(lines, [foobarObject]);53+ t.is(stdout, expectedOutput);54+};55+56+test('Can switch from objectMode to non-objectMode', testUnsetObjectMode, `${foobarObjectString}\n`, false, execa);57+test('Can switch from objectMode to non-objectMode, preserveNewlines', testUnsetObjectMode, foobarObjectString, true, execa);58+test('Can switch from objectMode to non-objectMode, sync', testUnsetObjectMode, `${foobarObjectString}\n`, false, execaSync);59+test('Can switch from objectMode to non-objectMode, preserveNewlines, sync', testUnsetObjectMode, foobarObjectString, true, execaSync);60+61+// eslint-disable-next-line max-params62+const testYieldArray = async (t, input, expectedLines, expectedOutput, execaMethod) => {63+ const lines = [];64+ const {stdout} = await execaMethod('noop.js', {65+ stdout: [66+ getOutputsGenerator(input)(),67+ resultGenerator(lines)(),68+ ],69+ stripFinalNewline: false,70+ });71+ t.deepEqual(lines, expectedLines);72+ t.deepEqual(stdout, expectedOutput);73+};74+75+test('Can use "yield* array" to produce multiple lines', testYieldArray, [foobarString, foobarString], [foobarString, foobarString], `${foobarString}\n${foobarString}\n`, execa);76+test('Can use "yield* array" to produce empty lines', testYieldArray, [foobarString, ''], [foobarString, ''], `${foobarString}\n\n`, execa);77+test('Can use "yield* array" to produce multiple lines, sync', testYieldArray, [foobarString, foobarString], [foobarString, foobarString], `${foobarString}\n${foobarString}\n`, execaSync);78+test('Can use "yield* array" to produce empty lines, sync', testYieldArray, [foobarString, ''], [foobarString, ''], `${foobarString}\n\n`, execaSync);added:test/transform/validate.js+95 added
1+import {Buffer} from 'node:buffer';2+import test from 'ava';3+import {execa, execaSync} from '../../index.js';4+import {setFixtureDir} from '../helpers/fixtures-dir.js';5+import {getStdio} from '../helpers/stdio.js';6+import {foobarUint8Array, foobarBuffer, foobarObject} from '../helpers/input.js';7+import {serializeGenerator, getOutputGenerator, convertTransformToFinal} from '../helpers/generator.js';8+9+setFixtureDir();10+11+const getMessage = input => {12+ if (input === null || input === undefined) {13+ return 'not be called at all';14+ }15+16+ if (Buffer.isBuffer(input)) {17+ return 'not a buffer';18+ }19+20+ return 'a string or an Uint8Array';21+};22+23+const lastInputGenerator = input => objectMode => [foobarUint8Array, getOutputGenerator(input)(objectMode)];24+const inputGenerator = input => objectMode => [...lastInputGenerator(input)(objectMode), serializeGenerator(true)];25+26+// eslint-disable-next-line max-params27+const testGeneratorReturn = async (t, fdNumber, generator, input, objectMode, isInput) => {28+ const fixtureName = isInput ? 'stdin-fd.js' : 'noop-fd.js';29+ const {message} = await t.throwsAsync(execa(fixtureName, [`${fdNumber}`], getStdio(fdNumber, generator(input)(objectMode))));30+ t.true(message.includes(getMessage(input)));31+};32+33+test('Generators with result.stdin cannot return an object if not in objectMode', testGeneratorReturn, 0, inputGenerator, foobarObject, false, true);34+test('Generators with result.stdio[*] as input cannot return an object if not in objectMode', testGeneratorReturn, 3, inputGenerator, foobarObject, false, true);35+test('The last generator with result.stdin cannot return an object even in objectMode', testGeneratorReturn, 0, lastInputGenerator, foobarObject, true, true);36+test('The last generator with result.stdio[*] as input cannot return an object even in objectMode', testGeneratorReturn, 3, lastInputGenerator, foobarObject, true, true);37+test('Generators with result.stdout cannot return an object if not in objectMode', testGeneratorReturn, 1, getOutputGenerator, foobarObject, false, false);38+test('Generators with result.stderr cannot return an object if not in objectMode', testGeneratorReturn, 2, getOutputGenerator, foobarObject, false, false);39+test('Generators with result.stdio[*] as output cannot return an object if not in objectMode', testGeneratorReturn, 3, getOutputGenerator, foobarObject, false, false);40+test('Generators with result.stdin cannot return a Buffer if not in objectMode', testGeneratorReturn, 0, inputGenerator, foobarBuffer, false, true);41+test('Generators with result.stdio[*] as input cannot return a Buffer if not in objectMode', testGeneratorReturn, 3, inputGenerator, foobarBuffer, false, true);42+test('The last generator with result.stdin cannot return a Buffer even in objectMode', testGeneratorReturn, 0, lastInputGenerator, foobarBuffer, true, true);43+test('The last generator with result.stdio[*] as input cannot return a Buffer even in objectMode', testGeneratorReturn, 3, lastInputGenerator, foobarBuffer, true, true);44+test('Generators with result.stdout cannot return a Buffer if not in objectMode', testGeneratorReturn, 1, getOutputGenerator, foobarBuffer, false, false);45+test('Generators with result.stderr cannot return a Buffer if not in objectMode', testGeneratorReturn, 2, getOutputGenerator, foobarBuffer, false, false);46+test('Generators with result.stdio[*] as output cannot return a Buffer if not in objectMode', testGeneratorReturn, 3, getOutputGenerator, foobarBuffer, false, false);47+test('Generators with result.stdin cannot return null if not in objectMode', testGeneratorReturn, 0, inputGenerator, null, false, true);48+test('Generators with result.stdin cannot return null if in objectMode', testGeneratorReturn, 0, inputGenerator, null, true, true);49+test('Generators with result.stdout cannot return null if not in objectMode', testGeneratorReturn, 1, getOutputGenerator, null, false, false);50+test('Generators with result.stdout cannot return null if in objectMode', testGeneratorReturn, 1, getOutputGenerator, null, true, false);51+test('Generators with result.stdin cannot return undefined if not in objectMode', testGeneratorReturn, 0, inputGenerator, undefined, false, true);52+test('Generators with result.stdin cannot return undefined if in objectMode', testGeneratorReturn, 0, inputGenerator, undefined, true, true);53+test('Generators with result.stdout cannot return undefined if not in objectMode', testGeneratorReturn, 1, getOutputGenerator, undefined, false, false);54+test('Generators with result.stdout cannot return undefined if in objectMode', testGeneratorReturn, 1, getOutputGenerator, undefined, true, false);55+56+// eslint-disable-next-line max-params57+const testGeneratorReturnSync = (t, fdNumber, generator, input, objectMode, isInput) => {58+ const fixtureName = isInput ? 'stdin-fd.js' : 'noop-fd.js';59+ const {message} = t.throws(() => {60+ execaSync(fixtureName, [`${fdNumber}`], getStdio(fdNumber, generator(input)(objectMode)));61+ });62+ t.true(message.includes(getMessage(input)));63+};64+65+test('Generators with result.stdin cannot return an object if not in objectMode, sync', testGeneratorReturnSync, 0, inputGenerator, foobarObject, false, true);66+test('The last generator with result.stdin cannot return an object even in objectMode, sync', testGeneratorReturnSync, 0, lastInputGenerator, foobarObject, true, true);67+test('Generators with result.stdout cannot return an object if not in objectMode, sync', testGeneratorReturnSync, 1, getOutputGenerator, foobarObject, false, false);68+test('Generators with result.stderr cannot return an object if not in objectMode, sync', testGeneratorReturnSync, 2, getOutputGenerator, foobarObject, false, false);69+test('Generators with result.stdio[*] as output cannot return an object if not in objectMode, sync', testGeneratorReturnSync, 3, getOutputGenerator, foobarObject, false, false);70+test('Generators with result.stdin cannot return a Buffer if not in objectMode, sync', testGeneratorReturnSync, 0, inputGenerator, foobarBuffer, false, true);71+test('The last generator with result.stdin cannot return a Buffer even in objectMode, sync', testGeneratorReturnSync, 0, lastInputGenerator, foobarBuffer, true, true);72+test('Generators with result.stdout cannot return a Buffer if not in objectMode, sync', testGeneratorReturnSync, 1, getOutputGenerator, foobarBuffer, false, false);73+test('Generators with result.stderr cannot return a Buffer if not in objectMode, sync', testGeneratorReturnSync, 2, getOutputGenerator, foobarBuffer, false, false);74+test('Generators with result.stdio[*] as output cannot return a Buffer if not in objectMode, sync', testGeneratorReturnSync, 3, getOutputGenerator, foobarBuffer, false, false);75+test('Generators with result.stdin cannot return null if not in objectMode, sync', testGeneratorReturnSync, 0, inputGenerator, null, false, true);76+test('Generators with result.stdin cannot return null if in objectMode, sync', testGeneratorReturnSync, 0, inputGenerator, null, true, true);77+test('Generators with result.stdout cannot return null if not in objectMode, sync', testGeneratorReturnSync, 1, getOutputGenerator, null, false, false);78+test('Generators with result.stdout cannot return null if in objectMode, sync', testGeneratorReturnSync, 1, getOutputGenerator, null, true, false);79+test('Generators with result.stdin cannot return undefined if not in objectMode, sync', testGeneratorReturnSync, 0, inputGenerator, undefined, false, true);80+test('Generators with result.stdin cannot return undefined if in objectMode, sync', testGeneratorReturnSync, 0, inputGenerator, undefined, true, true);81+test('Generators with result.stdout cannot return undefined if not in objectMode, sync', testGeneratorReturnSync, 1, getOutputGenerator, undefined, false, false);82+test('Generators with result.stdout cannot return undefined if in objectMode, sync', testGeneratorReturnSync, 1, getOutputGenerator, undefined, true, false);83+84+test('Generators "final" return value is validated', async t => {85+ await t.throwsAsync(86+ execa('noop.js', {stdout: convertTransformToFinal(getOutputGenerator(null)(true), true)}),87+ {message: /not be called at all/},88+ );89+});90+91+test('Generators "final" return value is validated, sync', t => {92+ t.throws(() => {93+ execaSync('noop.js', {stdout: convertTransformToFinal(getOutputGenerator(null)(true), true)});94+ }, {message: /not be called at all/});95+});deleted:test/async.js-26 removed
1-import process from 'node:process';2-import test from 'ava';3-import {execa} from '../index.js';4-import {setFixtureDir} from './helpers/fixtures-dir.js';5-6-setFixtureDir();7-8-const isWindows = process.platform === 'win32';9-10-if (isWindows) {11- test('execa() - cmd file', async t => {12- const {stdout} = await execa('hello.cmd');13- t.is(stdout, 'Hello World');14- });15-16- test('execa() - run cmd command', async t => {17- const {stdout} = await execa('cmd', ['/c', 'hello.cmd']);18- t.is(stdout, 'Hello World');19- });20-}21-22-test('execa() returns a promise with pid', async t => {23- const subprocess = execa('noop.js', ['foo']);24- t.is(typeof subprocess.pid, 'number');25- await subprocess;26-});deleted:test/command.js-112 removed
1-import {join} from 'node:path';2-import test from 'ava';3-import {execaCommand, execaCommandSync} from '../index.js';4-import {setFixtureDir, FIXTURES_DIR} from './helpers/fixtures-dir.js';5-import {QUOTE} from './helpers/verbose.js';6-7-setFixtureDir();8-const STDIN_FIXTURE = join(FIXTURES_DIR, 'stdin.js');9-10-test('execaCommand()', async t => {11- const {stdout} = await execaCommand('echo.js foo bar');12- t.is(stdout, 'foo\nbar');13-});14-15-test('execaCommandSync()', t => {16- const {stdout} = execaCommandSync('echo.js foo bar');17- t.is(stdout, 'foo\nbar');18-});19-20-test('execaCommand`...`', async t => {21- const {stdout} = await execaCommand`${'echo.js foo bar'}`;22- t.is(stdout, 'foo\nbar');23-});24-25-test('execaCommandSync`...`', t => {26- const {stdout} = execaCommandSync`${'echo.js foo bar'}`;27- t.is(stdout, 'foo\nbar');28-});29-30-test('execaCommand(options)`...`', async t => {31- const {stdout} = await execaCommand({stripFinalNewline: false})`${'echo.js foo bar'}`;32- t.is(stdout, 'foo\nbar\n');33-});34-35-test('execaCommandSync(options)`...`', t => {36- const {stdout} = execaCommandSync({stripFinalNewline: false})`${'echo.js foo bar'}`;37- t.is(stdout, 'foo\nbar\n');38-});39-40-test('execaCommand(options)()', async t => {41- const {stdout} = await execaCommand({stripFinalNewline: false})('echo.js foo bar');42- t.is(stdout, 'foo\nbar\n');43-});44-45-test('execaCommandSync(options)()', t => {46- const {stdout} = execaCommandSync({stripFinalNewline: false})('echo.js foo bar');47- t.is(stdout, 'foo\nbar\n');48-});49-50-test('execaCommand().pipe(execaCommand())', async t => {51- const {stdout} = await execaCommand('echo.js foo bar').pipe(execaCommand(`node ${STDIN_FIXTURE}`));52- t.is(stdout, 'foo\nbar');53-});54-55-test('execaCommand().pipe(...) does not use execaCommand', async t => {56- const {escapedCommand} = await execaCommand('echo.js foo bar').pipe(`node ${STDIN_FIXTURE}`, {reject: false});57- t.true(escapedCommand.startsWith(`${QUOTE}node `));58-});59-60-test('execaCommand() bound options have lower priority', async t => {61- const {stdout} = await execaCommand({stripFinalNewline: false})('echo.js foo bar', {stripFinalNewline: true});62- t.is(stdout, 'foo\nbar');63-});64-65-test('execaCommandSync() bound options have lower priority', t => {66- const {stdout} = execaCommandSync({stripFinalNewline: false})('echo.js foo bar', {stripFinalNewline: true});67- t.is(stdout, 'foo\nbar');68-});69-70-test('execaCommand() ignores consecutive spaces', async t => {71- const {stdout} = await execaCommand('echo.js foo bar');72- t.is(stdout, 'foo\nbar');73-});74-75-test('execaCommand() allows escaping spaces in commands', async t => {76- const {stdout} = await execaCommand('command\\ with\\ space.js foo bar');77- t.is(stdout, 'foo\nbar');78-});79-80-test('execaCommand() allows escaping spaces in arguments', async t => {81- const {stdout} = await execaCommand('echo.js foo\\ bar');82- t.is(stdout, 'foo bar');83-});84-85-test('execaCommand() escapes other whitespaces', async t => {86- const {stdout} = await execaCommand('echo.js foo\tbar');87- t.is(stdout, 'foo\tbar');88-});89-90-test('execaCommand() trims', async t => {91- const {stdout} = await execaCommand(' echo.js foo bar ');92- t.is(stdout, 'foo\nbar');93-});94-95-const testInvalidArgsArray = (t, execaMethod) => {96- t.throws(() => {97- execaMethod('echo', ['foo']);98- }, {message: /The command and its arguments must be passed as a single string/});99-};100-101-test('execaCommand() must not pass an array of arguments', testInvalidArgsArray, execaCommand);102-test('execaCommandSync() must not pass an array of arguments', testInvalidArgsArray, execaCommandSync);103-104-const testInvalidArgsTemplate = (t, execaMethod) => {105- t.throws(() => {106- // eslint-disable-next-line no-unused-expressions107- execaMethod`echo foo`;108- }, {message: /The command and its arguments must be passed as a single string/});109-};110-111-test('execaCommand() must not pass an array of arguments with a template string', testInvalidArgsTemplate, execaCommand);112-test('execaCommandSync() must not pass an array of arguments with a template string', testInvalidArgsTemplate, execaCommandSync);deleted:test/override-promise.js-14 removed
1-import test from 'ava';2-// The helper module overrides Promise on import so has to be imported before `execa`.3-import {restorePromise} from './helpers/override-promise.js';4-// eslint-disable-next-line import/order5-import {execa} from '../index.js';6-import {setFixtureDir} from './helpers/fixtures-dir.js';7-8-restorePromise();9-setFixtureDir();10-11-test('should work with third-party Promise', async t => {12- const {stdout} = await execa('noop.js', ['foo']);13- t.is(stdout, 'foo');14-});deleted:test/promise.js-53 removed
1-import test from 'ava';2-import {execa} from '../index.js';3-import {setFixtureDir} from './helpers/fixtures-dir.js';4-5-setFixtureDir();6-7-test('promise methods are not enumerable', t => {8- const descriptors = Object.getOwnPropertyDescriptors(execa('noop.js'));9- t.false(descriptors.then.enumerable);10- t.false(descriptors.catch.enumerable);11- t.false(descriptors.finally.enumerable);12-});13-14-test('finally function is executed on success', async t => {15- let isCalled = false;16- const {stdout} = await execa('noop.js', ['foo']).finally(() => {17- isCalled = true;18- });19- t.is(isCalled, true);20- t.is(stdout, 'foo');21-});22-23-test('finally function is executed on failure', async t => {24- let isError = false;25- const {stdout, stderr} = await t.throwsAsync(execa('exit.js', ['2']).finally(() => {26- isError = true;27- }));28- t.is(isError, true);29- t.is(typeof stdout, 'string');30- t.is(typeof stderr, 'string');31-});32-33-test('throw in finally function bubbles up on success', async t => {34- const {message} = await t.throwsAsync(execa('noop.js', ['foo']).finally(() => {35- throw new Error('called');36- }));37- t.is(message, 'called');38-});39-40-test('throw in finally bubbles up on error', async t => {41- const {message} = await t.throwsAsync(execa('exit.js', ['2']).finally(() => {42- throw new Error('called');43- }));44- t.is(message, 'called');45-});46-47-const testNoAwait = async (t, fixtureName, options, message) => {48- const {stdout} = await execa('no-await.js', [JSON.stringify(options), fixtureName]);49- t.true(stdout.includes(message));50-};51-52-test('Throws if promise is not awaited and subprocess fails', testNoAwait, 'fail.js', {}, 'exit code 2');53-test('Throws if promise is not awaited and subprocess times out', testNoAwait, 'forever.js', {timeout: 1}, 'timed out');deleted:test/script.js-59 removed
1-import test from 'ava';2-import {isStream} from 'is-stream';3-import {$} from '../index.js';4-import {setFixtureDir} from './helpers/fixtures-dir.js';5-import {foobarString} from './helpers/input.js';6-7-setFixtureDir();8-9-const testScriptStdoutSync = (t, getSubprocess, expectedStdout) => {10- const {stdout} = getSubprocess();11- t.is(stdout, expectedStdout);12-};13-14-test('$.sync`...`', testScriptStdoutSync, () => $.sync`echo.js foo bar`, 'foo\nbar');15-test('$.s`...`', testScriptStdoutSync, () => $.s`echo.js foo bar`, 'foo\nbar');16-test('$(options).sync`...`', testScriptStdoutSync, () => $({stripFinalNewline: false}).sync`echo.js ${foobarString}`, `${foobarString}\n`);17-test('$.sync(options)`...`', testScriptStdoutSync, () => $.sync({stripFinalNewline: false})`echo.js ${foobarString}`, `${foobarString}\n`);18-19-test('Cannot call $.sync.sync', t => {20- t.false('sync' in $.sync);21-});22-23-test('Cannot call $.sync(options).sync', t => {24- t.false('sync' in $.sync({}));25-});26-27-test('$(options)() stdin defaults to "inherit"', async t => {28- const {stdout} = await $({input: foobarString})('stdin-script.js');29- t.is(stdout, foobarString);30-});31-32-test('$.sync(options)() stdin defaults to "inherit"', t => {33- const {stdout} = $.sync({input: foobarString})('stdin-script.js');34- t.is(stdout, foobarString);35-});36-37-test('$(options).sync() stdin defaults to "inherit"', t => {38- const {stdout} = $({input: foobarString}).sync('stdin-script.js');39- t.is(stdout, foobarString);40-});41-42-test('$(options)`...` stdin defaults to "inherit"', async t => {43- const {stdout} = await $({input: foobarString})`stdin-script.js`;44- t.is(stdout, foobarString);45-});46-47-test('$.sync(options)`...` stdin defaults to "inherit"', t => {48- const {stdout} = $.sync({input: foobarString})`stdin-script.js`;49- t.is(stdout, foobarString);50-});51-52-test('$(options).sync`...` stdin defaults to "inherit"', t => {53- const {stdout} = $({input: foobarString}).sync`stdin-script.js`;54- t.is(stdout, foobarString);55-});56-57-test('$ stdin has no default value when stdio is set', t => {58- t.true(isStream($({stdio: 'pipe'})`noop.js`.stdin));59-});modified:index.js+5 added-5 removed
1-import {createExeca} from './lib/arguments/create.js';2-import {mapCommandAsync, mapCommandSync} from './lib/command.js';3-import {mapNode} from './lib/arguments/node.js';4-import {mapScriptAsync, setScriptSync, deepScriptOptions} from './lib/script.js';1+import {createExeca} from './lib/methods/create.js';2+import {mapCommandAsync, mapCommandSync} from './lib/methods/command.js';3+import {mapNode} from './lib/methods/node.js';4+import {mapScriptAsync, setScriptSync, deepScriptOptions} from './lib/methods/script.js';5 6-export {ExecaError, ExecaSyncError} from './lib/return/cause.js';6+export {ExecaError, ExecaSyncError} from './lib/return/final-error.js';7 8 export const execa = createExeca(() => ({}));9 export const execaSync = createExeca(() => ({isSync: true}));10 export const execaCommand = createExeca(mapCommandAsync);3 unmodified lines