Skip to content
Myr

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

229 files+9834 added−9835 removed

deleted:lib/arguments/create.js-64 removed
added:lib/arguments/encoding-option.js+49 added
deleted:lib/arguments/encoding.js-49 removed
added:lib/arguments/fd-options.js+105 added
1import {parseFd} from './specific.js';23export 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];89 if (destinationStream === null) {10 throw new TypeError(getInvalidStdioOptionMessage(fdNumber, to, options, isWritable));11 }1213 return destinationStream;14};1516export 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];2122 if (sourceStream === null || sourceStream === undefined) {23 throw new TypeError(getInvalidStdioOptionMessage(fdNumber, from, options, isWritable));24 }2526 return sourceStream;27};2829export const SUBPROCESS_OPTIONS = new WeakMap();3031const getFdNumber = (fileDescriptors, fdName, isWritable) => {32 const fdNumber = parseFdNumber(fdName, isWritable);33 validateFdNumber(fdNumber, fdName, isWritable, fileDescriptors);34 return fdNumber;35};3637const parseFdNumber = (fdName, isWritable) => {38 const fdNumber = parseFd(fdName);39 if (fdNumber !== undefined) {40 return fdNumber;41 }4243 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}".47It must be ${validOptions} or "fd3", "fd4" (and so on).48It is optional and defaults to "${defaultValue}".`);49};5051const 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.55Please set the "stdio" option to ensure that file descriptor exists.`);56 }5758 if (fileDescriptor.direction === 'input' && !isWritable) {59 throw new TypeError(`"${getOptionName(isWritable)}" must not be ${fdName}. It must be a readable stream, not writable.`);60 }6162 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};6667const getInvalidStdioOptionMessage = (fdNumber, fdName, options, isWritable) => {68 if (fdNumber === 'all' && !options.all) {69 return 'The "all" option must be true to use "from: \'all\'".';70 }7172 const {optionName, optionValue} = getInvalidStdioOption(fdNumber, options);73 return `The "${optionName}: ${serializeOptionValue(optionValue)}" option is incompatible with using "${getOptionName(isWritable)}: ${serializeOptionValue(fdName)}".74Please set this option with "pipe" instead.`;75};7677const getInvalidStdioOption = (fdNumber, {stdin, stdout, stderr, stdio}) => {78 const usedDescriptor = getUsedDescriptor(fdNumber);7980 if (usedDescriptor === 0 && stdin !== undefined) {81 return {optionName: 'stdin', optionValue: stdin};82 }8384 if (usedDescriptor === 1 && stdout !== undefined) {85 return {optionName: 'stdout', optionValue: stdout};86 }8788 if (usedDescriptor === 2 && stderr !== undefined) {89 return {optionName: 'stderr', optionValue: stderr};90 }9192 return {optionName: `stdio[${usedDescriptor}]`, optionValue: stdio[usedDescriptor]};93};9495const getUsedDescriptor = fdNumber => fdNumber === 'all' ? 1 : fdNumber;9697const getOptionName = isWritable => isWritable ? 'to' : 'from';9899export const serializeOptionValue = value => {100 if (typeof value === 'string') {101 return `'${value}'`;102 }103104 return typeof value === 'number' ? `${value}` : 'Stream';105};
deleted:lib/arguments/node.js-42 removed
deleted:lib/arguments/normalize.js-29 removed
modified:lib/arguments/options.js+4 added-4 removed
modified:lib/arguments/specific.js+1 added-1 removed
1import isPlainObject from 'is-plain-obj';2import {STANDARD_STREAMS_ALIASES} from '../utils.js';2import {STANDARD_STREAMS_ALIASES} from '../utils/standard-stream.js';3import {verboseDefault} from '../verbose/info.js';45export const normalizeFdSpecificOptions = options => {6 const optionsCopy = {...options};
88 unmodified lines
deleted:lib/arguments/template.js-135 removed
1import {ChildProcess} from 'node:child_process';2import {isUint8Array, uint8ArrayToString} from '../stdio/uint-array.js';34export const isTemplateString = templates => Array.isArray(templates) && Array.isArray(templates.raw);56export const parseTemplates = (templates, expressions) => {7 let tokens = [];89 for (const [index, template] of templates.entries()) {10 tokens = parseTemplate({templates, expressions, tokens, index, template});11 }1213 if (tokens.length === 0) {14 throw new TypeError('Template script must not be empty');15 }1617 const [file, ...args] = tokens;18 return [file, args, {}];19};2021const parseTemplate = ({templates, expressions, tokens, index, template}) => {22 if (template === undefined) {23 throw new TypeError(`Invalid backslash sequence: ${templates.raw[index]}`);24 }2526 const {nextTokens, leadingWhitespaces, trailingWhitespaces} = splitByWhitespaces(template, templates.raw[index]);27 const newTokens = concatTokens(tokens, nextTokens, leadingWhitespaces);2829 if (index === expressions.length) {30 return newTokens;31 }3233 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};3940// 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 them46const splitByWhitespaces = (template, rawTemplate) => {47 if (rawTemplate.length === 0) {48 return {nextTokens: [], leadingWhitespaces: false, trailingWhitespaces: false};49 }5051 const nextTokens = [];52 let templateStart = 0;53 const leadingWhitespaces = DELIMITERS.has(rawTemplate[0]);5455 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 }6566 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 }7677 const trailingWhitespaces = templateStart === template.length;78 if (!trailingWhitespaces) {79 nextTokens.push(template.slice(templateStart));80 }8182 return {nextTokens, leadingWhitespaces, trailingWhitespaces};83};8485const DELIMITERS = new Set([' ', '\t', '\r', '\n']);8687// 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 mode90const ESCAPE_LENGTH = {x: 3, u: 5};9192const 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 ];101102const parseExpression = expression => {103 const typeOfExpression = typeof expression;104105 if (typeOfExpression === 'string') {106 return expression;107 }108109 if (typeOfExpression === 'number') {110 return String(expression);111 }112113 if (114 typeOfExpression === 'object'115 && expression !== null116 && !isSubprocess(expression)117 && 'stdout' in expression118 ) {119 const typeOfStdout = typeof expression.stdout;120121 if (typeOfStdout === 'string') {122 return expression.stdout;123 }124125 if (isUint8Array(expression.stdout)) {126 return uint8ArrayToString(expression.stdout);127 }128129 throw new TypeError(`Unexpected "${typeOfStdout}" stdout in template expression`);130 }131132 throw new TypeError(`Unexpected "${typeOfExpression}" in template expression`);133};134135const isSubprocess = value => value instanceof ChildProcess;
modified:lib/convert/duplex.js+1 added-1 removed
1import {Duplex} from 'node:stream';2import {callbackify} from 'node:util';3import {BINARY_ENCODINGS} from '../arguments/encoding.js';3import {BINARY_ENCODINGS} from '../arguments/encoding-option.js';4import {5 getSubprocessStdout,6 getReadableOptions,7 getReadableMethods,
38 unmodified lines
deleted:lib/convert/fd-options.js-105 removed
1import {parseFd} from '../arguments/specific.js';23export 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];89 if (destinationStream === null) {10 throw new TypeError(getInvalidStdioOptionMessage(fdNumber, to, options, isWritable));11 }1213 return destinationStream;14};1516export 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];2122 if (sourceStream === null || sourceStream === undefined) {23 throw new TypeError(getInvalidStdioOptionMessage(fdNumber, from, options, isWritable));24 }2526 return sourceStream;27};2829export const SUBPROCESS_OPTIONS = new WeakMap();3031const getFdNumber = (fileDescriptors, fdName, isWritable) => {32 const fdNumber = parseFdNumber(fdName, isWritable);33 validateFdNumber(fdNumber, fdName, isWritable, fileDescriptors);34 return fdNumber;35};3637const parseFdNumber = (fdName, isWritable) => {38 const fdNumber = parseFd(fdName);39 if (fdNumber !== undefined) {40 return fdNumber;41 }4243 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}".47It must be ${validOptions} or "fd3", "fd4" (and so on).48It is optional and defaults to "${defaultValue}".`);49};5051const 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.55Please set the "stdio" option to ensure that file descriptor exists.`);56 }5758 if (fileDescriptor.direction === 'input' && !isWritable) {59 throw new TypeError(`"${getOptionName(isWritable)}" must not be ${fdName}. It must be a readable stream, not writable.`);60 }6162 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};6667const getInvalidStdioOptionMessage = (fdNumber, fdName, options, isWritable) => {68 if (fdNumber === 'all' && !options.all) {69 return 'The "all" option must be true to use "from: \'all\'".';70 }7172 const {optionName, optionValue} = getInvalidStdioOption(fdNumber, options);73 return `The "${optionName}: ${serializeOptionValue(optionValue)}" option is incompatible with using "${getOptionName(isWritable)}: ${serializeOptionValue(fdName)}".74Please set this option with "pipe" instead.`;75};7677const getInvalidStdioOption = (fdNumber, {stdin, stdout, stderr, stdio}) => {78 const usedDescriptor = getUsedDescriptor(fdNumber);7980 if (usedDescriptor === 0 && stdin !== undefined) {81 return {optionName: 'stdin', optionValue: stdin};82 }8384 if (usedDescriptor === 1 && stdout !== undefined) {85 return {optionName: 'stdout', optionValue: stdout};86 }8788 if (usedDescriptor === 2 && stderr !== undefined) {89 return {optionName: 'stderr', optionValue: stderr};90 }9192 return {optionName: `stdio[${usedDescriptor}]`, optionValue: stdio[usedDescriptor]};93};9495const getUsedDescriptor = fdNumber => fdNumber === 'all' ? 1 : fdNumber;9697const getOptionName = isWritable => isWritable ? 'to' : 'from';9899export const serializeOptionValue = value => {100 if (typeof value === 'string') {101 return `'${value}'`;102 }103104 return typeof value === 'number' ? `${value}` : 'Stream';105};
modified:lib/convert/iterable.js+3 added-3 removed
1import {BINARY_ENCODINGS} from '../arguments/encoding.js';2import {getReadable} from './fd-options.js';3import {iterateOnSubprocessStream} from './loop.js';1import {BINARY_ENCODINGS} from '../arguments/encoding-option.js';2import {getReadable} from '../arguments/fd-options.js';3import {iterateOnSubprocessStream} from '../io/iterate.js';45export const createIterable = (subprocess, encoding, {6 from,7 binary: binaryOption = false,
19 unmodified lines
deleted:lib/convert/loop.js-96 removed
1import {on} from 'node:events';2import {getEncodingTransformGenerator} from '../stdio/encoding-transform.js';3import {getSplitLinesGenerator} from '../stdio/split.js';4import {transformChunkSync, finalChunksSync} from '../stdio/transform-sync.js';56// Iterate over lines of `subprocess.stdout`, used by `subprocess.readable|duplex|iterable()`7export 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};2021const stopReadingOnExit = async (subprocess, controller) => {22 try {23 await subprocess;24 } catch {} finally {25 controller.abort();26 }27};2829// Iterate over lines of `subprocess.stdout`, used by `result.stdout` and the `verbose: 'full'` option.30// Applies the `lines` and `encoding` options.31export 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};4546const stopReadingOnStreamEnd = async (onStreamEnd, controller, stream) => {47 try {48 await onStreamEnd;49 } catch {50 stream.destroy();51 } finally {52 controller.abort();53 }54};5556const 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};6768// @todo: replace with `getDefaultHighWaterMark(true)` after dropping support for Node <18.17.069export const DEFAULT_OBJECT_HIGH_WATER_MARK = 16;7071// 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.75const HIGH_WATER_MARK = DEFAULT_OBJECT_HIGH_WATER_MARK;7677const iterateOnData = async function * ({onStdoutChunk, controller, binary, shouldEncode, encoding, shouldSplit, preserveNewlines}) {78 const generators = getGenerators({binary, shouldEncode, encoding, shouldSplit, preserveNewlines});7980 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};9293const 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
1import {Readable} from 'node:stream';2import {callbackify} from 'node:util';3import {BINARY_ENCODINGS} from '../arguments/encoding.js';4import {getReadable} from './fd-options.js';3import {BINARY_ENCODINGS} from '../arguments/encoding-option.js';4import {getReadable} from '../arguments/fd-options.js';5import {iterateOnSubprocessStream, DEFAULT_OBJECT_HIGH_WATER_MARK} from '../io/iterate.js';6import {addConcurrentStream, waitForConcurrentStreams} from './concurrent.js';7import {8 createDeferred,9 safeWaitForSubprocessStdin,10 waitForSubprocessStdout,11 waitForSubprocess,12 destroyOtherStream,13} from './shared.js';13import {iterateOnSubprocessStream, DEFAULT_OBJECT_HIGH_WATER_MARK} from './loop.js';1415// Create a `Readable` stream that forwards from `stdout` and awaits the subprocess16export const createReadable = ({subprocess, concurrentStreams, encoding}, {from, binary: binaryOption = true, preserveNewlines = true} = {}) => {17 const binary = binaryOption || BINARY_ENCODINGS.has(encoding);
78 unmodified lines
modified:lib/convert/shared.js+1 added-1 removed
1import {finished} from 'node:stream/promises';2import {isStreamAbort} from '../stream/wait.js';2import {isStreamAbort} from '../resolve/wait-stream.js';34export const safeWaitForSubprocessStdin = async subprocessStdin => {5 if (subprocessStdin === undefined) {6 return;
48 unmodified lines
modified:lib/convert/writable.js+1 added-1 removed
1import {Writable} from 'node:stream';2import {callbackify} from 'node:util';3import {getWritable} from './fd-options.js';3import {getWritable} from '../arguments/fd-options.js';4import {addConcurrentStream, waitForConcurrentStreams} from './concurrent.js';5import {6 safeWaitForSubprocessStdout,7 waitForSubprocessStdin,
78 unmodified lines
deleted:lib/exit/cleanup.js-16 removed
1import {addAbortListener} from 'node:events';2import {onExit} from 'signal-exit';34// `cleanup` option handling5export const cleanupOnExit = (subprocess, {cleanup, detached}, {signal}) => {6 if (!cleanup || detached) {7 return;8 }910 const removeExitHandler = onExit(() => {11 subprocess.kill();12 });13 addAbortListener(signal, () => {14 removeExitHandler();15 });16};
deleted:lib/exit/kill.js-76 removed
1import os from 'node:os';2import {setTimeout} from 'node:timers/promises';3import {isErrorInstance} from '../return/cause.js';45export const normalizeForceKillAfterDelay = forceKillAfterDelay => {6 if (forceKillAfterDelay === false) {7 return forceKillAfterDelay;8 }910 if (forceKillAfterDelay === true) {11 return DEFAULT_FORCE_KILL_TIMEOUT;12 }1314 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 }1718 return forceKillAfterDelay;19};2021const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5;2223// Monkey-patches `subprocess.kill()` to add `forceKillAfterDelay` behavior and `.kill(error)`24export 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};3132const parseKillArguments = (signalOrError, errorArgument, killSignal) => {33 const [signal = killSignal, error] = isErrorInstance(signalOrError)34 ? [undefined, signalOrError]35 : [signalOrError, errorArgument];3637 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 }4041 if (error !== undefined && !isErrorInstance(error)) {42 throw new TypeError(`The second argument is optional. If specified, it must be an error instance: ${error}`);43 }4445 return {signal, error};46};4748const emitKillError = (subprocess, error) => {49 if (error !== undefined) {50 subprocess.emit(errorSignal, error);51 }52};5354// Like `error` signal but internal to Execa.55// E.g. does not make subprocess crash when no `error` listener is set.56export const errorSignal = Symbol('error');5758const setKillTimeout = async ({kill, signal, forceKillAfterDelay, killSignal, killResult, controller}) => {59 if (!shouldForceKill(signal, forceKillAfterDelay, killSignal, killResult)) {60 return;61 }6263 try {64 await setTimeout(forceKillAfterDelay, undefined, {signal: controller.signal});65 kill('SIGKILL');66 } catch {}67};6869const shouldForceKill = (signal, forceKillAfterDelay, killSignal, killResult) =>70 normalizeSignal(signal) === normalizeSignal(killSignal)71 && forceKillAfterDelay !== false72 && killResult;7374const normalizeSignal = signal => typeof signal === 'string'75 ? os.constants.signals[signal.toUpperCase()]76 : signal;
deleted:lib/exit/timeout.js-20 removed
1import {setTimeout} from 'node:timers/promises';2import {DiscardedError} from '../return/cause.js';34export 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};910// `timeout` option handling11export const throwOnTimeout = (subprocess, timeout, context, controller) => timeout === 0 || timeout === undefined12 ? []13 : [killAfterTimeout(subprocess, timeout, context, controller)];1415const 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
1import {setImmediate} from 'node:timers/promises';2import getStream, {getStreamAsArrayBuffer, getStreamAsArray} from 'get-stream';3import {isArrayBuffer} from '../utils/uint-array.js';4import {shouldLogOutput, logLines} from '../verbose/output.js';5import {iterateForResult} from './iterate.js';6import {handleMaxBuffer} from './max-buffer.js';7import {getStripFinalNewline} from './strip-newline.js';89export 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 }1415 if (!buffer) {16 await resumeStream(stream);17 return;18 }1920 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};2425// 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_r146549631027const resumeStream = async stream => {28 await setImmediate();29 if (stream.readableFlowing === null) {30 stream.resume();31 }32};3334const getStreamContents = async ({stream, stream: {readableObjectMode}, iterable, fdNumber, encoding, maxBuffer, lines}) => {35 try {36 if (readableObjectMode || lines) {37 return await getStreamAsArray(iterable, {maxBuffer});38 }3940 if (encoding === 'buffer') {41 return new Uint8Array(await getStreamAsArrayBuffer(iterable, {maxBuffer}));42 }4344 return await getStream(iterable, {maxBuffer});45 } catch (error) {46 return handleBufferedData(handleMaxBuffer({error, stream, readableObjectMode, lines, encoding, fdNumber}));47 }48};4950// 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 retrieve53export const getBufferedData = async streamPromise => {54 try {55 return await streamPromise;56 } catch (error) {57 return handleBufferedData(error);58 }59};6061const handleBufferedData = ({bufferedData}) => isArrayBuffer(bufferedData)62 ? new Uint8Array(bufferedData)63 : bufferedData;
added:lib/io/input-sync.js+44 added
1import {runGeneratorsSync} from '../transform/generator.js';2import {joinToUint8Array, isUint8Array} from '../utils/uint-array.js';3import {TYPE_TO_MESSAGE} from '../stdio/type.js';45// Apply `stdin`/`input`/`inputFile` options, before spawning, in sync mode, by converting it to the `input` option6export const addInputOptionsSync = (fileDescriptors, options) => {7 for (const fdNumber of getInputFdNumbers(fileDescriptors)) {8 addInputOptionSync(fileDescriptors, fdNumber, options);9 }10};1112const getInputFdNumbers = fileDescriptors => new Set(Object.entries(fileDescriptors)13 .filter(([, {direction}]) => direction === 'input')14 .map(([fdNumber]) => Number(fdNumber)));1516const 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 }2223 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 }2728 const allContents = allStdioItems.map(({contents}) => contents);29 const transformedContents = allContents.map(contents => applySingleInputGeneratorsSync(contents, stdioItems));30 options.input = joinToUint8Array(transformedContents);31};3233const applySingleInputGeneratorsSync = (contents, stdioItems) => {34 const newContents = runGeneratorsSync(contents, stdioItems, 'utf8', true);35 validateSerializable(newContents);36 return joinToUint8Array(newContents);37};3839const 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
1import {on} from 'node:events';2import {getEncodingTransformGenerator} from '../transform/encoding-transform.js';3import {getSplitLinesGenerator} from '../transform/split.js';4import {transformChunkSync, finalChunksSync} from '../transform/run-sync.js';56// Iterate over lines of `subprocess.stdout`, used by `subprocess.readable|duplex|iterable()`7export 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};2021const stopReadingOnExit = async (subprocess, controller) => {22 try {23 await subprocess;24 } catch {} finally {25 controller.abort();26 }27};2829// Iterate over lines of `subprocess.stdout`, used by `result.stdout` and the `verbose: 'full'` option.30// Applies the `lines` and `encoding` options.31export 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};4546const stopReadingOnStreamEnd = async (onStreamEnd, controller, stream) => {47 try {48 await onStreamEnd;49 } catch {50 stream.destroy();51 } finally {52 controller.abort();53 }54};5556const 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};6768// @todo: replace with `getDefaultHighWaterMark(true)` after dropping support for Node <18.17.069export const DEFAULT_OBJECT_HIGH_WATER_MARK = 16;7071// 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.75const HIGH_WATER_MARK = DEFAULT_OBJECT_HIGH_WATER_MARK;7677const iterateOnData = async function * ({onStdoutChunk, controller, binary, shouldEncode, encoding, shouldSplit, preserveNewlines}) {78 const generators = getGenerators({binary, shouldEncode, encoding, shouldSplit, preserveNewlines});7980 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};9293const 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
1import {MaxBufferError} from 'get-stream';2import {getStreamName} from '../utils/standard-stream.js';34export const handleMaxBuffer = ({error, stream, readableObjectMode, lines, encoding, fdNumber}) => {5 if (!(error instanceof MaxBufferError)) {6 throw error;7 }89 if (fdNumber === 'all') {10 return error;11 }1213 const unit = getMaxBufferUnit(readableObjectMode, lines, encoding);14 error.maxBufferInfo = {fdNumber, unit};15 stream.destroy();16 throw error;17};1819const getMaxBufferUnit = (readableObjectMode, lines, encoding) => {20 if (readableObjectMode) {21 return 'objects';22 }2324 if (lines) {25 return 'lines';26 }2728 if (encoding === 'buffer') {29 return 'bytes';30 }3132 return 'characters';33};3435export const getMaxBufferMessage = (error, maxBuffer) => {36 const {streamName, threshold, unit} = getMaxBufferInfo(error, maxBuffer);37 return `Command's ${streamName} was larger than ${threshold} ${unit}`;38};3940const getMaxBufferInfo = (error, maxBuffer) => {41 if (error?.maxBufferInfo === undefined) {42 return {streamName: 'output', threshold: maxBuffer[1], unit: 'bytes'};43 }4445 const {maxBufferInfo: {fdNumber, unit}} = error;46 delete error.maxBufferInfo;47 return {streamName: getStreamName(fdNumber), threshold: maxBuffer[fdNumber], unit};48};4950export const isMaxBufferSync = (resultError, output, maxBuffer) => resultError?.code === 'ENOBUFS'51 && output !== null52 && output.some(result => result !== null && result.length > getMaxBufferSync(maxBuffer));5354// `spawnSync()` does not allow differentiating `maxBuffer` per file descriptor, so we always use `stdout`55export const getMaxBufferSync = maxBuffer => maxBuffer[1];
added:lib/io/output-async.js+71 added
1import mergeStreams from '@sindresorhus/merge-streams';2import {isStandardStream} from '../utils/standard-stream.js';3import {incrementMaxListeners} from '../utils/max-listeners.js';4import {TRANSFORM_TYPES} from '../stdio/type.js';5import {pipeStreams} from './pipeline.js';67// 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 ended9export const pipeOutputAsync = (subprocess, fileDescriptors, controller) => {10 const inputStreamsGroups = {};1112 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 }1617 for (const {stream} of stdioItems.filter(({type}) => !TRANSFORM_TYPES.has(type))) {18 pipeStdioItem({subprocess, stream, direction, fdNumber, inputStreamsGroups, controller});19 }20 }2122 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};2728// `subprocess.stdin|stdout|stderr|stdio` is directly mutated.29const pipeTransform = (subprocess, stream, direction, fdNumber) => {30 if (direction === 'output') {31 pipeStreams(subprocess.stdio[fdNumber], stream);32 } else {33 pipeStreams(stream, subprocess.stdio[fdNumber]);34 }3536 const streamProperty = SUBPROCESS_STREAM_PROPERTIES[fdNumber];37 if (streamProperty !== undefined) {38 subprocess[streamProperty] = stream;39 }4041 subprocess.stdio[fdNumber] = stream;42};4344const SUBPROCESS_STREAM_PROPERTIES = ['stdin', 'stdout', 'stderr'];4546const pipeStdioItem = ({subprocess, stream, direction, fdNumber, inputStreamsGroups, controller}) => {47 if (stream === undefined) {48 return;49 }5051 setStandardStreamMaxListeners(stream, controller);5253 if (direction === 'output') {54 pipeStreams(subprocess.stdio[fdNumber], stream);55 } else {56 inputStreamsGroups[fdNumber] = [...(inputStreamsGroups[fdNumber] ?? []), stream];57 }58};5960// 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.62const setStandardStreamMaxListeners = (stream, {signal}) => {63 if (isStandardStream(stream)) {64 incrementMaxListeners(stream, MAX_LISTENERS_INCREMENT, signal);65 }66};6768// `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.71const MAX_LISTENERS_INCREMENT = 2;
added:lib/io/output-sync.js+90 added
1import {writeFileSync} from 'node:fs';2import {shouldLogOutput, logLinesSync} from '../verbose/output.js';3import {runGeneratorsSync} from '../transform/generator.js';4import {splitLinesSync} from '../transform/split.js';5import {joinToString, joinToUint8Array, bufferToUint8Array} from '../utils/uint-array.js';6import {FILE_TYPES} from '../stdio/type.js';7import {getMaxBufferSync} from './max-buffer.js';89// Apply `stdout`/`stderr` options, after spawning, in sync mode10export const transformOutputSync = ({fileDescriptors, syncResult: {output}, options, isMaxBuffer, verboseInfo}) => {11 if (output === null) {12 return {output: Array.from({length: 3})};13 }1415 const state = {};16 const transformedOutput = output.map((result, fdNumber) =>17 transformOutputResultSync({result, fileDescriptors, fdNumber, state, isMaxBuffer, verboseInfo}, options));18 return {output: transformedOutput, ...state};19};2021const transformOutputResultSync = ({result, fileDescriptors, fdNumber, state, isMaxBuffer, verboseInfo}, {buffer, encoding, lines, stripFinalNewline, maxBuffer}) => {22 if (result === null) {23 return;24 }2526 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});3435 if (shouldLogOutput({stdioItems, encoding, verboseInfo, fdNumber})) {36 const linesArray = splitLinesSync(serializedResult, false, objectMode);37 logLinesSync(linesArray, verboseInfo);38 }3940 const returnedResult = buffer[fdNumber] ? finalResult : undefined;4142 try {43 if (state.error === undefined) {44 writeToFiles(serializedResult, stdioItems);45 }4647 return returnedResult;48 } catch (error) {49 state.error = error;50 return returnedResult;51 }52};5354const truncateResult = (result, isMaxBuffer, maxBuffer) => isMaxBuffer && result.length > maxBuffer55 ? result.slice(0, maxBuffer)56 : result;5758const 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};6667const serializeChunks = ({chunks, objectMode, encoding, lines, stripFinalNewline, fdNumber}) => {68 if (objectMode) {69 return {serializedResult: chunks};70 }7172 if (encoding === 'buffer') {73 return {serializedResult: joinToUint8Array(chunks)};74 }7576 const serializedResult = joinToString(chunks, encoding);77 if (lines[fdNumber]) {78 return {serializedResult, finalResult: splitLinesSync(serializedResult, !stripFinalNewline[fdNumber], objectMode)};79 }8081 return {serializedResult};82};8384const 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
1import {finished} from 'node:stream/promises';2import {isStandardStream} from '../utils/standard-stream.js';34// Like `Stream.pipeline(source, destination)`, but does not destroy standard streams.5export const pipeStreams = (source, destination) => {6 source.pipe(destination);7 onSourceFinish(source, destination);8 onDestinationFinish(source, destination);9};1011// `source.pipe(destination)` makes `destination` end when `source` ends.12// But it does not propagate aborts or errors. This function does it.13const onSourceFinish = async (source, destination) => {14 if (isStandardStream(source) || isStandardStream(destination)) {15 return;16 }1718 try {19 await finished(source, {cleanup: true, readable: true, writable: false});20 } catch {}2122 endDestinationStream(destination);23};2425export const endDestinationStream = destination => {26 if (destination.writable) {27 destination.end();28 }29};3031// We do the same thing in the other direction as well.32const onDestinationFinish = async (source, destination) => {33 if (isStandardStream(source) || isStandardStream(destination)) {34 return;35 }3637 try {38 await finished(destination, {cleanup: true, readable: false, writable: true});39 } catch {}4041 abortSourceStream(source);42};4344export const abortSourceStream = source => {45 if (source.readable) {46 source.destroy();47 }48};
added:lib/io/strip-newline.js+9 added
1import stripFinalNewlineFunction from 'strip-final-newline';23export const stripNewline = (value, {stripFinalNewline}, fdNumber) => getStripFinalNewline(stripFinalNewline, fdNumber) && value !== undefined && !Array.isArray(value)4 ? stripFinalNewlineFunction(value)5 : value;67export const getStripFinalNewline = (stripFinalNewline, fdNumber) => fdNumber === 'all'8 ? stripFinalNewline[1] || stripFinalNewline[2]9 : stripFinalNewline[fdNumber];
added:lib/methods/command.js+25 added
1export const mapCommandAsync = ({file, args}) => parseCommand(file, args);2export const mapCommandSync = ({file, args}) => ({...parseCommand(file, args), isSync: true});34const 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 }89 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 }2021 const [file, ...args] = tokens;22 return {file, args};23};2425const SPACES_REGEXP = / +/g;
added:lib/methods/create.js+64 added
1import isPlainObject from 'is-plain-obj';2import {FD_SPECIFIC_OPTIONS} from '../arguments/specific.js';3import {normalizeParameters} from './parameters.js';4import {isTemplateString, parseTemplates} from './template.js';5import {execaCoreSync} from './main-sync.js';6import {execaCoreAsync} from './main-async.js';78export 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);1112 if (setBoundExeca !== undefined) {13 setBoundExeca(boundExeca, createNested, boundOptions);14 }1516 return boundExeca;17};1819const callBoundExeca = ({mapArguments, deepOptions = {}, boundOptions = {}, setBoundExeca, createNested}, firstArgument, ...nextArguments) => {20 if (isPlainObject(firstArgument)) {21 return createNested(mapArguments, mergeOptions(boundOptions, firstArgument), setBoundExeca);22 }2324 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};2930const 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};4445// Deep merge specific options like `env`. Shallow merge the other ones.46const 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};5556const mergeOption = (optionName, boundOptionValue, optionValue) => {57 if (DEEP_OPTIONS.has(optionName) && isPlainObject(boundOptionValue) && isPlainObject(optionValue)) {58 return {...boundOptionValue, ...optionValue};59 }6061 return optionValue;62};6364const DEEP_OPTIONS = new Set(['env', ...FD_SPECIFIC_OPTIONS]);
added:lib/methods/main-async.js+110 added
1import {setMaxListeners} from 'node:events';2import {spawn} from 'node:child_process';3import {MaxBufferError} from 'get-stream';4import {handleCommand} from '../arguments/command.js';5import {handleOptions} from '../arguments/options.js';6import {SUBPROCESS_OPTIONS} from '../arguments/fd-options.js';7import {makeError, makeSuccessResult} from '../return/result.js';8import {handleResult} from '../return/reject.js';9import {handleEarlyError} from '../return/early-error.js';10import {handleStdioAsync} from '../stdio/handle-async.js';11import {stripNewline} from '../io/strip-newline.js';12import {pipeOutputAsync} from '../io/output-async.js';13import {subprocessKill} from '../terminate/kill.js';14import {cleanupOnExit} from '../terminate/cleanup.js';15import {pipeToSubprocess} from '../pipe/setup.js';16import {logEarlyResult} from '../verbose/complete.js';17import {makeAllStream} from '../resolve/all-async.js';18import {waitForSubprocessResult} from '../resolve/wait-subprocess.js';19import {addConvertedStreams} from '../convert/add.js';20import {mergePromise} from './promise.js';2122export 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};3031const handleAsyncArguments = (rawFile, rawArgs, rawOptions) => {32 const {command, escapedCommand, startTime, verboseInfo} = handleCommand(rawFile, rawArgs, rawOptions);3334 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};4445// Prevent passing the `timeout` option directly to `child_process.spawn()`46const handleAsyncOptions = ({timeout, signal, cancelSignal, ...options}) => {47 if (signal !== undefined) {48 throw new TypeError('The "signal" option has been renamed to "cancelSignal" instead.');49 }5051 return {...options, timeoutDuration: timeout, signal: cancelSignal};52};5354const 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 }6162 const controller = new AbortController();63 setMaxListeners(Number.POSITIVE_INFINITY, controller.signal);6465 const originalStreams = [...subprocess.stdio];66 pipeOutputAsync(subprocess, fileDescriptors, controller);67 cleanupOnExit(subprocess, options, controller);6869 subprocess.kill = subprocessKill.bind(undefined, {kill: subprocess.kill.bind(subprocess), subprocess, options, controller});70 subprocess.all = makeAllStream(subprocess, options);71 addConvertedStreams(subprocess, options);7273 const promise = handlePromise({subprocess, options, startTime, verboseInfo, fileDescriptors, originalStreams, command, escapedCommand, controller});74 return {subprocess, promise};75};7677const handlePromise = async ({subprocess, options, startTime, verboseInfo, fileDescriptors, originalStreams, command, escapedCommand, controller}) => {78 const context = {timedOut: false};7980 const [81 errorInfo,82 [exitCode, signal],83 stdioResults,84 allResult,85 ] = await waitForSubprocessResult({subprocess, options, context, verboseInfo, fileDescriptors, originalStreams, controller});86 controller.abort();8788 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};9394const 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
1import {spawnSync} from 'node:child_process';2import {handleCommand} from '../arguments/command.js';3import {handleOptions} from '../arguments/options.js';4import {makeError, makeEarlyError, makeSuccessResult} from '../return/result.js';5import {handleResult} from '../return/reject.js';6import {handleStdioSync} from '../stdio/handle-sync.js';7import {stripNewline} from '../io/strip-newline.js';8import {addInputOptionsSync} from '../io/input-sync.js';9import {transformOutputSync} from '../io/output-sync.js';10import {getMaxBufferSync} from '../io/max-buffer.js';11import {logEarlyResult} from '../verbose/complete.js';12import {getAllSync} from '../resolve/all-sync.js';13import {getExitResultSync} from '../resolve/exit-sync.js';1415export 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};2021const handleSyncArguments = (rawFile, rawArgs, rawOptions) => {22 const {command, escapedCommand, startTime, verboseInfo} = handleCommand(rawFile, rawArgs, rawOptions);2324 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};3536const normalizeSyncOptions = options => options.node && !options.ipc ? {...options, ipc: false} : options;3738const validateSyncOptions = ({ipc, detached, cancelSignal}) => {39 if (ipc) {40 throwInvalidSyncOption('ipc: true');41 }4243 if (detached) {44 throwInvalidSyncOption('detached: true');45 }4647 if (cancelSignal) {48 throwInvalidSyncOption('cancelSignal');49 }50};5152const throwInvalidSyncOption = value => {53 throw new TypeError(`The "${value}" option cannot be used with synchronous methods.`);54};5556const 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 }6162 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};6869const 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};7879const normalizeSpawnSyncOptions = ({encoding, maxBuffer, ...options}) => ({...options, encoding: 'buffer', maxBuffer: getMaxBufferSync(maxBuffer)});8081const 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
1import {execPath, execArgv} from 'node:process';2import {basename, resolve} from 'node:path';3import {safeNormalizeFileUrl} from '../arguments/file-url.js';45export const mapNode = ({options}) => {6 if (options.node === false) {7 throw new TypeError('The "node" option cannot be false with `execaNode()`.');8 }910 return {options: {...options, node: true}};11};1213export 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 }2425 const normalizedNodePath = safeNormalizeFileUrl(nodePath, 'The "nodePath" option');26 const resolvedNodePath = resolve(cwd, normalizedNodePath);27 const newOptions = {...options, nodePath: resolvedNodePath, node: shouldHandleNode, cwd};2829 if (!shouldHandleNode) {30 return [file, args, newOptions];31 }3233 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 }3637 return [38 resolvedNodePath,39 [...nodeOptions, file, ...args],40 {ipc: true, ...newOptions, shell: false},41 ];42};
added:lib/methods/parameters.js+29 added
1import isPlainObject from 'is-plain-obj';2import {safeNormalizeFileUrl} from '../arguments/file-url.js';34export const normalizeParameters = (rawFile, rawArgs = [], rawOptions = {}) => {5 const filePath = safeNormalizeFileUrl(rawFile, 'First argument');6 const [args, options] = isPlainObject(rawArgs)7 ? [[], rawArgs]8 : [rawArgs, rawOptions];910 if (!Array.isArray(args)) {11 throw new TypeError(`Second argument must be either an array of arguments or an options object: ${args}`);12 }1314 if (args.some(arg => typeof arg === 'object' && arg !== null)) {15 throw new TypeError(`Second argument must be an array of strings: ${args}`);16 }1718 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 }2324 if (!isPlainObject(options)) {25 throw new TypeError(`Last argument must be an options object: ${options}`);26 }2728 return [filePath, normalizedArgs, options];29};
added:lib/methods/promise.js+15 added
1// The return value is a mixin of `subprocess` and `Promise`2export 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};89// eslint-disable-next-line unicorn/prefer-top-level-await10const nativePromisePrototype = (async () => {})().constructor.prototype;1112const descriptors = ['then', 'catch', 'finally'].map(property => [13 property,14 Reflect.getOwnPropertyDescriptor(nativePromisePrototype, property),15]);
added:lib/methods/script.js+15 added
1export const setScriptSync = (boundExeca, createNested, boundOptions) => {2 boundExeca.sync = createNested(mapScriptSync, boundOptions);3 boundExeca.s = boundExeca.sync;4};56export const mapScriptAsync = ({options}) => getScriptOptions(options);7const mapScriptSync = ({options}) => ({...getScriptOptions(options), isSync: true});89const getScriptOptions = options => ({options: {...getScriptStdinOption(options), ...options}});1011const getScriptStdinOption = ({input, inputFile, stdio}) => input === undefined && inputFile === undefined && stdio === undefined12 ? {stdin: 'inherit'}13 : {};1415export const deepScriptOptions = {preferLocal: true};
added:lib/methods/template.js+135 added
1import {ChildProcess} from 'node:child_process';2import {isUint8Array, uint8ArrayToString} from '../utils/uint-array.js';34export const isTemplateString = templates => Array.isArray(templates) && Array.isArray(templates.raw);56export const parseTemplates = (templates, expressions) => {7 let tokens = [];89 for (const [index, template] of templates.entries()) {10 tokens = parseTemplate({templates, expressions, tokens, index, template});11 }1213 if (tokens.length === 0) {14 throw new TypeError('Template script must not be empty');15 }1617 const [file, ...args] = tokens;18 return [file, args, {}];19};2021const parseTemplate = ({templates, expressions, tokens, index, template}) => {22 if (template === undefined) {23 throw new TypeError(`Invalid backslash sequence: ${templates.raw[index]}`);24 }2526 const {nextTokens, leadingWhitespaces, trailingWhitespaces} = splitByWhitespaces(template, templates.raw[index]);27 const newTokens = concatTokens(tokens, nextTokens, leadingWhitespaces);2829 if (index === expressions.length) {30 return newTokens;31 }3233 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};3940// 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 them46const splitByWhitespaces = (template, rawTemplate) => {47 if (rawTemplate.length === 0) {48 return {nextTokens: [], leadingWhitespaces: false, trailingWhitespaces: false};49 }5051 const nextTokens = [];52 let templateStart = 0;53 const leadingWhitespaces = DELIMITERS.has(rawTemplate[0]);5455 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 }6566 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 }7677 const trailingWhitespaces = templateStart === template.length;78 if (!trailingWhitespaces) {79 nextTokens.push(template.slice(templateStart));80 }8182 return {nextTokens, leadingWhitespaces, trailingWhitespaces};83};8485const DELIMITERS = new Set([' ', '\t', '\r', '\n']);8687// 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 mode90const ESCAPE_LENGTH = {x: 3, u: 5};9192const 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 ];101102const parseExpression = expression => {103 const typeOfExpression = typeof expression;104105 if (typeOfExpression === 'string') {106 return expression;107 }108109 if (typeOfExpression === 'number') {110 return String(expression);111 }112113 if (114 typeOfExpression === 'object'115 && expression !== null116 && !isSubprocess(expression)117 && 'stdout' in expression118 ) {119 const typeOfStdout = typeof expression.stdout;120121 if (typeOfStdout === 'string') {122 return expression.stdout;123 }124125 if (isUint8Array(expression.stdout)) {126 return uint8ArrayToString(expression.stdout);127 }128129 throw new TypeError(`Unexpected "${typeOfStdout}" stdout in template expression`);130 }131132 throw new TypeError(`Unexpected "${typeOfExpression}" in template expression`);133};134135const isSubprocess = value => value instanceof ChildProcess;
added:lib/pipe/pipe-arguments.js+79 added
1import {normalizeParameters} from '../methods/parameters.js';2import {getStartTime} from '../return/duration.js';3import {SUBPROCESS_OPTIONS, getWritable, getReadable} from '../arguments/fd-options.js';45export 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};2930const 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};4243const getDestination = (boundOptions, createNested, firstArgument, ...args) => {44 if (Array.isArray(firstArgument)) {45 const destination = createNested(mapDestinationArguments, boundOptions)(firstArgument, ...args);46 return {destination, pipeOptions: boundOptions};47 }4849 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 }5354 const [rawFile, rawArgs, rawOptions] = normalizeParameters(firstArgument, ...args);55 const destination = createNested(mapDestinationArguments)(rawFile, rawArgs, rawOptions);56 return {destination, pipeOptions: rawOptions};57 }5859 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 }6364 return {destination: firstArgument, pipeOptions: args[0]};65 }6667 throw new TypeError(`The first argument must be a template string, an options object, or an Execa subprocess: ${firstArgument}`);68};6970const mapDestinationArguments = ({options}) => ({options: {...options, stdin: 'pipe', piped: true}});7172const 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
1import isPlainObject from 'is-plain-obj';2import {normalizePipeArguments} from './validate.js';2import {normalizePipeArguments} from './pipe-arguments.js';3import {handlePipeArgumentsError} from './throw.js';4import {waitForBothSubprocesses} from './sequence.js';5import {pipeSubprocessStream} from './streaming.js';6import {unpipeOnAbort} from './abort.js';
54 unmodified lines
modified:lib/pipe/streaming.js+2 added-2 removed
1import {finished} from 'node:stream/promises';2import mergeStreams from '@sindresorhus/merge-streams';3import {incrementMaxListeners} from '../max-listener.js';4import {pipeStreams} from '../stdio/pipeline.js';3import {incrementMaxListeners} from '../utils/max-listeners.js';4import {pipeStreams} from '../io/pipeline.js';56// 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 lines
modified:lib/pipe/throw.js+2 added-2 removed
1import {makeEarlyError} from '../return/error.js';2import {abortSourceStream, endDestinationStream} from '../stdio/pipeline.js';1import {makeEarlyError} from '../return/result.js';2import {abortSourceStream, endDestinationStream} from '../io/pipeline.js';34export const handlePipeArgumentsError = ({5 sourceStream,6 sourceError,
39 unmodified lines
deleted:lib/pipe/validate.js-79 removed
1import {normalizeArguments} from '../arguments/normalize.js';2import {getStartTime} from '../return/duration.js';3import {SUBPROCESS_OPTIONS, getWritable, getReadable} from '../convert/fd-options.js';45export 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};2930const 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};4243const getDestination = (boundOptions, createNested, firstArgument, ...args) => {44 if (Array.isArray(firstArgument)) {45 const destination = createNested(mapDestinationArguments, boundOptions)(firstArgument, ...args);46 return {destination, pipeOptions: boundOptions};47 }4849 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 }5354 const [rawFile, rawArgs, rawOptions] = normalizeArguments(firstArgument, ...args);55 const destination = createNested(mapDestinationArguments)(rawFile, rawArgs, rawOptions);56 return {destination, pipeOptions: rawOptions};57 }5859 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 }6364 return {destination: firstArgument, pipeOptions: args[0]};65 }6667 throw new TypeError(`The first argument must be a template string, an options object, or an Execa subprocess: ${firstArgument}`);68};6970const mapDestinationArguments = ({options}) => ({options: {...options, stdin: 'pipe', piped: true}});7172const 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
1import mergeStreams from '@sindresorhus/merge-streams';2import {waitForSubprocessStream} from './stdio.js';34// `all` interleaves `stdout` and `stderr`5export const makeAllStream = ({stdout, stderr}, {all}) => all && (stdout || stderr)6 ? mergeStreams([stdout, stderr].filter(Boolean))7 : undefined;89// Read the contents of `subprocess.all` and|or wait for its completion10export 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});2122const getAllStream = ({stdout, stderr, all}, [, bufferStdout, bufferStderr]) => {23 const buffer = bufferStdout || bufferStderr;24 if (!buffer) {25 return {stream: all, buffer};26 }2728 if (!bufferStdout) {29 return {stream: stderr, buffer};30 }3132 if (!bufferStderr) {33 return {stream: stdout, buffer};34 }3536 return {stream: all, buffer};37};3839// 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.43const getAllMixed = ({all, stdout, stderr}) => all44 && stdout45 && stderr46 && stdout.readableObjectMode !== stderr.readableObjectMode;
added:lib/resolve/all-sync.js+32 added
1import {isUint8Array, concatUint8Arrays} from '../utils/uint-array.js';2import {stripNewline} from '../io/strip-newline.js';34export const getAllSync = ([, stdout, stderr], options) => {5 if (!options.all) {6 return;7 }89 if (stdout === undefined) {10 return stderr;11 }1213 if (stderr === undefined) {14 return stdout;15 }1617 if (Array.isArray(stdout)) {18 return Array.isArray(stderr)19 ? [...stdout, ...stderr]20 : [...stdout, stripNewline(stderr, options, 'all')];21 }2223 if (Array.isArray(stderr)) {24 return [stripNewline(stdout, options, 'all'), ...stderr];25 }2627 if (isUint8Array(stdout) && isUint8Array(stderr)) {28 return concatUint8Arrays([stdout, stderr]);29 }3031 return `${stdout}${stderr}`;32};
added:lib/resolve/exit-async.js+45 added
1import {once} from 'node:events';2import {DiscardedError} from '../return/final-error.js';34// 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 times11export const waitForExit = async subprocess => {12 const [spawnPayload, exitPayload] = await Promise.allSettled([13 once(subprocess, 'spawn'),14 once(subprocess, 'exit'),15 ]);1617 if (spawnPayload.status === 'rejected') {18 return [];19 }2021 return exitPayload.status === 'rejected'22 ? waitForSubprocessExit(subprocess)23 : exitPayload.value;24};2526const waitForSubprocessExit = async subprocess => {27 try {28 return await once(subprocess, 'exit');29 } catch {30 return waitForSubprocessExit(subprocess);31 }32};3334export const waitForSuccessfulExit = async exitPromise => {35 const [exitCode, signal] = await exitPromise;3637 if (!isSubprocessErrorExit(exitCode, signal) && isFailedExit(exitCode, signal)) {38 throw new DiscardedError();39 }4041 return [exitCode, signal];42};4344const isSubprocessErrorExit = (exitCode, signal) => exitCode === undefined && signal === undefined;45export const isFailedExit = (exitCode, signal) => exitCode !== 0 || signal !== null;
added:lib/resolve/exit-sync.js+18 added
1import {DiscardedError} from '../return/final-error.js';2import {isMaxBufferSync} from '../io/max-buffer.js';3import {isFailedExit} from './exit-async.js';45export 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};1112const getResultError = (error, exitCode, signal) => {13 if (error !== undefined) {14 return error;15 }1617 return isFailedExit(exitCode, signal) ? new DiscardedError() : undefined;18};
added:lib/resolve/stdio.js+34 added
1import {getStreamOutput} from '../io/contents.js';2import {waitForStream, isInputFileDescriptor} from './wait-stream.js';34// Read the contents of `subprocess.std*` and|or wait for its completion5export 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}));1718export const waitForSubprocessStream = async ({stream, fdNumber, encoding, buffer, maxBuffer, lines, allMixed, stripFinalNewline, verboseInfo, streamInfo}) => {19 if (!stream) {20 return;21 }2223 const onStreamEnd = waitForStream(stream, fdNumber, streamInfo);24 if (isInputFileDescriptor(streamInfo, fdNumber)) {25 await onStreamEnd;26 return;27 }2829 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
1import {finished} from 'node:stream/promises';23// 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.6export 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};2223// 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.34const handleStdinDestroy = (stream, {originalStreams: [originalStdin], subprocess}) => {35 const state = {stdinCleanedUp: false};36 if (stream === originalStdin) {37 spyOnStdinDestroy(stream, subprocess, state);38 }3940 return state;41};4243const spyOnStdinDestroy = (subprocessStdin, subprocess, state) => {44 const {_destroy} = subprocessStdin;45 subprocessStdin._destroy = (...args) => {46 setStdinCleanedUp(subprocess, state);47 _destroy.call(subprocessStdin, ...args);48 };49};5051const setStdinCleanedUp = ({exitCode, signalCode}, state) => {52 if (exitCode !== null || signalCode !== null) {53 state.stdinCleanedUp = true;54 }55};5657// 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.62const handleStreamError = (error, fdNumber, streamInfo, isSameDirection) => {63 if (!shouldIgnoreStreamError(error, fdNumber, streamInfo, isSameDirection)) {64 throw error;65 }66};6768const shouldIgnoreStreamError = (error, fdNumber, streamInfo, isSameDirection = true) => {69 if (streamInfo.propagating) {70 return isStreamEpipe(error) || isStreamAbort(error);71 }7273 streamInfo.propagating = true;74 return isInputFileDescriptor(streamInfo, fdNumber) === isSameDirection75 ? isStreamEpipe(error)76 : isStreamAbort(error);77};7879// 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.84export const isInputFileDescriptor = ({fileDescriptors}, fdNumber) => fdNumber !== 'all' && fileDescriptors[fdNumber].direction === 'input';8586// 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.89export const isStreamAbort = error => error?.code === 'ERR_STREAM_PREMATURE_CLOSE';9091// 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.96const isStreamEpipe = error => error?.code === 'EPIPE';
added:lib/resolve/wait-subprocess.js+82 added
1import {once} from 'node:events';2import {isStream as isNodeStream} from 'is-stream';3import {errorSignal} from '../terminate/kill.js';4import {throwOnTimeout} from '../terminate/timeout.js';5import {isStandardStream} from '../utils/standard-stream.js';6import {TRANSFORM_TYPES} from '../stdio/type.js';7import {getBufferedData} from '../io/contents.js';8import {waitForAllStream} from './all-async.js';9import {waitForStdioStreams} from './stdio.js';10import {waitForExit, waitForSuccessfulExit} from './exit-async.js';11import {waitForStream} from './wait-stream.js';1213// Retrieve result of subprocess: exit code, signal, error, streams (stdout/stderr/all)14export 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};2526 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);3031 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};5657// Transforms replace `subprocess.std*`, which means they are not exposed to users.58// However, we still want to wait for their completion.59const waitForOriginalStreams = (originalStreams, subprocess, streamInfo) =>60 originalStreams.map((stream, fdNumber) => stream === subprocess.stdio[fdNumber]61 ? undefined62 : waitForStream(stream, fdNumber, streamInfo));6364// 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.67const 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 })));7374const throwOnSubprocessError = async (subprocess, {signal}) => {75 const [error] = await once(subprocess, 'error', {signal});76 throw error;77};7879const throwOnInternalError = async (subprocess, {signal}) => {80 const [error] = await once(subprocess, errorSignal, {signal});81 throw error;82};
deleted:lib/return/cause.js-37 removed
1export 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};67// Indicates that the error is used only to interrupt control flow, but not in the return value8export class DiscardedError extends Error {}910// Proper way to set `error.name`: it should be inherited and non-enumerable11const 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};2526// Unlike `instanceof`, this works across realms27export const isExecaError = error => isErrorInstance(error) && execaErrorSymbol in error;2829const execaErrorSymbol = Symbol('isExecaError');3031export const isErrorInstance = value => Object.prototype.toString.call(value) === '[object Error]';3233export class ExecaError extends Error {}34setErrorName(ExecaError, ExecaError.name);3536export class ExecaSyncError extends Error {}37setErrorName(ExecaSyncError, ExecaSyncError.name);
modified:lib/return/early-error.js+2 added-2 removed
1import {ChildProcess} from 'node:child_process';2import {PassThrough, Readable, Writable, Duplex} from 'node:stream';3import {cleanupCustomStreams} from '../stdio/async.js';4import {makeEarlyError} from './error.js';3import {cleanupCustomStreams} from '../stdio/handle-async.js';4import {makeEarlyError} from './result.js';5import {handleResult} from './reject.js';67// When the subprocess fails to spawn.8// We ensure the returned error is always both a promise and a subprocess.
33 unmodified lines
deleted:lib/return/error.js-122 removed
1import {signalsByName} from 'human-signals';2import {getDurationMs} from './duration.js';3import {getFinalError} from './cause.js';4import {createMessages} from './message.js';56export 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});3031export 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});5152export 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);8485 error.shortMessage = shortMessage;86 error.originalMessage = originalMessage;87 error.command = command;88 error.escapedCommand = escapedCommand;89 error.cwd = cwd;90 error.durationMs = getDurationMs(startTime);9192 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;101102 error.stdout = stdio[1];103 error.stderr = stdio[2];104105 if (all !== undefined) {106 error.all = all;107 }108109 error.stdio = stdio;110 error.pipedFrom = [];111112 return error;113};114115// `signal` and `exitCode` emitted on `subprocess.on('exit')` event can be `null`.116// We normalize them to `undefined`117const 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
1export 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};67// Indicates that the error is used only to interrupt control flow, but not in the return value8export class DiscardedError extends Error {}910// Proper way to set `error.name`: it should be inherited and non-enumerable11const 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};2526// Unlike `instanceof`, this works across realms27export const isExecaError = error => isErrorInstance(error) && execaErrorSymbol in error;2829const execaErrorSymbol = Symbol('isExecaError');3031export const isErrorInstance = value => Object.prototype.toString.call(value) === '[object Error]';3233export class ExecaError extends Error {}34setErrorName(ExecaError, ExecaError.name);3536export class ExecaSyncError extends Error {}37setErrorName(ExecaSyncError, ExecaSyncError.name);
modified:lib/return/message.js+3 added-3 removed
1import stripFinalNewline from 'strip-final-newline';2import {isUint8Array, uint8ArrayToString} from '../stdio/uint-array.js';2import {isUint8Array, uint8ArrayToString} from '../utils/uint-array.js';3import {fixCwdError} from '../arguments/cwd.js';4import {escapeLines} from '../arguments/escape.js';5import {getMaxBufferMessage} from '../stream/max-buffer.js';6import {DiscardedError, isExecaError} from './cause.js';5import {getMaxBufferMessage} from '../io/max-buffer.js';6import {DiscardedError, isExecaError} from './final-error.js';78export const createMessages = ({9 stdio,10 all,
79 unmodified lines
added:lib/return/result.js+122 added
1import {signalsByName} from 'human-signals';2import {getDurationMs} from './duration.js';3import {getFinalError} from './final-error.js';4import {createMessages} from './message.js';56export 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});3031export 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});5152export 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);8485 error.shortMessage = shortMessage;86 error.originalMessage = originalMessage;87 error.command = command;88 error.escapedCommand = escapedCommand;89 error.cwd = cwd;90 error.durationMs = getDurationMs(startTime);9192 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;101102 error.stdout = stdio[1];103 error.stderr = stdio[2];104105 if (all !== undefined) {106 error.all = all;107 }108109 error.stdio = stdio;110 error.pipedFrom = [];111112 return error;113};114115// `signal` and `exitCode` emitted on `subprocess.on('exit')` event can be `null`.116// We normalize them to `undefined`117const 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
1import stripFinalNewlineFunction from 'strip-final-newline';23export const stripNewline = (value, {stripFinalNewline}, fdNumber) => getStripFinalNewline(stripFinalNewline, fdNumber) && value !== undefined && !Array.isArray(value)4 ? stripFinalNewlineFunction(value)5 : value;67export const getStripFinalNewline = (stripFinalNewline, fdNumber) => fdNumber === 'all'8 ? stripFinalNewline[1] || stripFinalNewline[2]9 : stripFinalNewline[fdNumber];
deleted:lib/stdio/all-sync.js-32 removed
1import {stripNewline} from '../return/strip-newline.js';2import {isUint8Array, concatUint8Arrays} from './uint-array.js';34export const getAllSync = ([, stdout, stderr], options) => {5 if (!options.all) {6 return;7 }89 if (stdout === undefined) {10 return stderr;11 }1213 if (stderr === undefined) {14 return stdout;15 }1617 if (Array.isArray(stdout)) {18 return Array.isArray(stderr)19 ? [...stdout, ...stderr]20 : [...stdout, stripNewline(stderr, options, 'all')];21 }2223 if (Array.isArray(stderr)) {24 return [stripNewline(stdout, options, 'all'), ...stderr];25 }2627 if (isUint8Array(stdout) && isUint8Array(stderr)) {28 return concatUint8Arrays([stdout, stderr]);29 }3031 return `${stdout}${stderr}`;32};
deleted:lib/stdio/async.js-64 removed
1import {createReadStream, createWriteStream} from 'node:fs';2import {Buffer} from 'node:buffer';3import {Readable, Writable, Duplex} from 'node:stream';4import {isStandardStream} from '../utils.js';5import {handleInput} from './handle.js';6import {TYPE_TO_MESSAGE} from './type.js';7import {generatorToStream} from './transform-run.js';89// Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in async mode10export const handleInputAsync = (options, verboseInfo) => handleInput(addPropertiesAsync, options, verboseInfo, false);1112const forbiddenIfAsync = ({type, optionName}) => {13 throw new TypeError(`The \`${optionName}\` option cannot be ${TYPE_TO_MESSAGE[type]}.`);14};1516const 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};2829const 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};5152// 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.56export 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
1import {Buffer} from 'node:buffer';2import {StringDecoder} from 'node:string_decoder';3import {isUint8Array, bufferToUint8Array} from './uint-array.js';45/*6When using generators, add an internal generator that converts chunks from `Buffer` to `string` or `Uint8Array`.7This allows generator functions to operate with those types instead.8Chunks 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 string1213However, those are converted to Buffer:14- on writes: `Duplex.writable` `decodeStrings: true` default option15- on reads: `Duplex.readable` `readableEncoding: null` default option16*/17export const getEncodingTransformGenerator = (binary, encoding, skipped) => {18 if (skipped) {19 return;20 }2122 if (binary) {23 return {transform: encodingUint8ArrayGenerator.bind(undefined, new TextEncoder())};24 }2526 const stringDecoder = new StringDecoder(encoding);27 return {28 transform: encodingStringGenerator.bind(undefined, stringDecoder),29 final: encodingStringFinal.bind(undefined, stringDecoder),30 };31};3233const 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};4243const encodingStringGenerator = function * (stringDecoder, chunk) {44 yield Buffer.isBuffer(chunk) || isUint8Array(chunk)45 ? stringDecoder.write(chunk)46 : chunk;47};4849const encodingStringFinal = function * (stringDecoder) {50 const lastChunk = stringDecoder.end();51 if (lastChunk !== '') {52 yield lastChunk;53 }54};
added:lib/stdio/handle-async.js+64 added
1import {createReadStream, createWriteStream} from 'node:fs';2import {Buffer} from 'node:buffer';3import {Readable, Writable, Duplex} from 'node:stream';4import {isStandardStream} from '../utils/standard-stream.js';5import {generatorToStream} from '../transform/generator.js';6import {handleStdio} from './handle.js';7import {TYPE_TO_MESSAGE} from './type.js';89// Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in async mode10export const handleStdioAsync = (options, verboseInfo) => handleStdio(addPropertiesAsync, options, verboseInfo, false);1112const forbiddenIfAsync = ({type, optionName}) => {13 throw new TypeError(`The \`${optionName}\` option cannot be ${TYPE_TO_MESSAGE[type]}.`);14};1516const 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};2829const 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};5152// 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.56export 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
1import {readFileSync} from 'node:fs';2import {bufferToUint8Array} from '../utils/uint-array.js';3import {handleStdio} from './handle.js';4import {TYPE_TO_MESSAGE} from './type.js';56// Normalize `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in sync mode7export const handleStdioSync = (options, verboseInfo) => handleStdio(addPropertiesSync, options, verboseInfo, true);89const forbiddenIfSync = ({type, optionName}) => {10 throwInvalidSyncValue(optionName, TYPE_TO_MESSAGE[type]);11};1213const forbiddenNativeIfSync = ({optionName, value}) => {14 if (value === 'ipc' || value === 'overlapped') {15 throwInvalidSyncValue(optionName, `"${value}"`);16 }1718 return {};19};2021const throwInvalidSyncValue = (optionName, value) => {22 throw new TypeError(`The \`${optionName}\` option cannot be ${value} with synchronous methods.`);23};2425const 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};3536const 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
1import {getStreamName} from '../utils.js';1import {getStreamName} from '../utils/standard-stream.js';2import {normalizeTransforms} from '../transform/normalize.js';3import {getFdObjectMode} from '../transform/object-mode.js';4import {getStdioItemType, isRegularUrl, isUnknownStdioString, FILE_TYPES} from './type.js';5import {getStreamDirection} from './direction.js';4import {normalizeStdio} from './option.js';6import {normalizeStdioOption} from './stdio-option.js';7import {handleNativeStream} from './native.js';6import {handleInputOptions} from './input.js';7import {normalizeTransforms} from './normalize-transform.js';8import {getFdObjectMode} from './object-mode.js';8import {handleInputOptions} from './input-option.js';910// Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in async/sync mode11export const handleInput = (addProperties, options, verboseInfo, isSync) => {12 const stdio = normalizeStdio(options, isSync);11export 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 lines
added:lib/stdio/input-option.js+50 added
1import {isReadableStream} from 'is-stream';2import {isUint8Array} from '../utils/uint-array.js';3import {isUrl, isFilePathString} from './type.js';45// Append the `stdin` option with the `input` and `inputFile` options6export const handleInputOptions = ({input, inputFile}, fdNumber) => fdNumber === 07 ? [8 ...handleInputOption(input),9 ...handleInputFileOption(inputFile),10 ]11 : [];1213const handleInputOption = input => input === undefined ? [] : [{14 type: getInputType(input),15 value: input,16 optionName: 'input',17}];1819const getInputType = input => {20 if (isReadableStream(input, {checkOpen: false})) {21 return 'nodeStream';22 }2324 if (typeof input === 'string') {25 return 'string';26 }2728 if (isUint8Array(input)) {29 return 'uint8Array';30 }3132 throw new Error('The `input` option must be a string, a Uint8Array or a Node.js Readable stream.');33};3435const handleInputFileOption = inputFile => inputFile === undefined ? [] : [{36 ...getInputFileType(inputFile),37 optionName: 'inputFile',38}];3940const getInputFileType = inputFile => {41 if (isUrl(inputFile)) {42 return {type: 'fileUrl', value: inputFile};43 }4445 if (isFilePathString(inputFile)) {46 return {type: 'filePath', value: {file: inputFile}};47 }4849 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
1import {joinToUint8Array, isUint8Array} from './uint-array.js';2import {TYPE_TO_MESSAGE} from './type.js';3import {runGeneratorsSync} from './transform-run.js';45// Apply `stdin`/`input`/`inputFile` options, before spawning, in sync mode, by converting it to the `input` option6export const addInputOptionsSync = (fileDescriptors, options) => {7 for (const fdNumber of getInputFdNumbers(fileDescriptors)) {8 addInputOptionSync(fileDescriptors, fdNumber, options);9 }10};1112const getInputFdNumbers = fileDescriptors => new Set(Object.entries(fileDescriptors)13 .filter(([, {direction}]) => direction === 'input')14 .map(([fdNumber]) => Number(fdNumber)));1516const 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 }2223 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 }2728 const allContents = allStdioItems.map(({contents}) => contents);29 const transformedContents = allContents.map(contents => applySingleInputGeneratorsSync(contents, stdioItems));30 options.input = joinToUint8Array(transformedContents);31};3233const applySingleInputGeneratorsSync = (contents, stdioItems) => {34 const newContents = runGeneratorsSync(contents, stdioItems, 'utf8', true);35 validateSerializable(newContents);36 return joinToUint8Array(newContents);37};3839const 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
1import {isReadableStream} from 'is-stream';2import {isUint8Array} from './uint-array.js';3import {isUrl, isFilePathString} from './type.js';45// Append the `stdin` option with the `input` and `inputFile` options6export const handleInputOptions = ({input, inputFile}, fdNumber) => fdNumber === 07 ? [8 ...handleInputOption(input),9 ...handleInputFileOption(inputFile),10 ]11 : [];1213const handleInputOption = input => input === undefined ? [] : [{14 type: getInputType(input),15 value: input,16 optionName: 'input',17}];1819const getInputType = input => {20 if (isReadableStream(input, {checkOpen: false})) {21 return 'nodeStream';22 }2324 if (typeof input === 'string') {25 return 'string';26 }2728 if (isUint8Array(input)) {29 return 'uint8Array';30 }3132 throw new Error('The `input` option must be a string, a Uint8Array or a Node.js Readable stream.');33};3435const handleInputFileOption = inputFile => inputFile === undefined ? [] : [{36 ...getInputFileType(inputFile),37 optionName: 'inputFile',38}];3940const getInputFileType = inputFile => {41 if (isUrl(inputFile)) {42 return {type: 'fileUrl', value: inputFile};43 }4445 if (isFilePathString(inputFile)) {46 return {type: 'filePath', value: {file: inputFile}};47 }4849 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
1import {readFileSync} from 'node:fs';2import tty from 'node:tty';3import {isStream as isNodeStream} from 'is-stream';4import {STANDARD_STREAMS} from '../utils.js';5import {serializeOptionValue} from '../convert/fd-options.js';6import {bufferToUint8Array} from './uint-array.js';4import {STANDARD_STREAMS} from '../utils/standard-stream.js';5import {bufferToUint8Array} from '../utils/uint-array.js';6import {serializeOptionValue} from '../arguments/fd-options.js';78// 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 lines
deleted:lib/stdio/normalize-transform.js-83 removed
1import isPlainObj from 'is-plain-obj';2import {BINARY_ENCODINGS} from '../arguments/encoding.js';3import {TRANSFORM_TYPES} from './type.js';4import {getTransformObjectModes} from './object-mode.js';56// Transforms generators/duplex/TransformStream can have multiple shapes.7// This normalizes it and applies default values.8export const normalizeTransforms = (stdioItems, optionName, direction, options) => [9 ...stdioItems.filter(({type}) => !TRANSFORM_TYPES.has(type)),10 ...getTransforms(stdioItems, optionName, direction, options),11];1213const getTransforms = (stdioItems, optionName, direction, {encoding}) => {14 const transforms = stdioItems.filter(({type}) => TRANSFORM_TYPES.has(type));15 const newTransforms = Array.from({length: transforms.length});1617 for (const [index, stdioItem] of Object.entries(transforms)) {18 newTransforms[index] = normalizeTransform({stdioItem, index: Number(index), newTransforms, optionName, direction, encoding});19 }2021 return sortTransforms(newTransforms, direction);22};2324const normalizeTransform = ({stdioItem, stdioItem: {type}, index, newTransforms, optionName, direction, encoding}) => {25 if (type === 'duplex') {26 return normalizeDuplex({stdioItem, optionName});27 }2829 if (type === 'webTransform') {30 return normalizeTransformStream({stdioItem, index, newTransforms, direction});31 }3233 return normalizeGenerator({stdioItem, index, newTransforms, direction, encoding});34};3536const 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 }5051 if (!objectMode && readableObjectMode) {52 throw new TypeError(`The \`${optionName}.objectMode\` option cannot be \`false\` if \`new Duplex({objectMode: true})\` is used.`);53 }5455 return {56 ...stdioItem,57 value: {transform, writableObjectMode, readableObjectMode},58 };59};6061const 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};6970const 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};8283const sortTransforms = (newTransforms, direction) => direction === 'input' ? newTransforms.reverse() : newTransforms;
deleted:lib/stdio/object-mode.js-41 removed
1import {TRANSFORM_TYPES} from './type.js';23/*4Retrieve the `objectMode`s of a single transform.5`objectMode` determines the return value's type, i.e. the `readableObjectMode`.6The chunk argument's type is based on the previous generator's return value, i.e. the `writableObjectMode` is based on the previous `readableObjectMode`.7The 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.10Therefore its `readableObjectMode` must be `false`.11The same applies to the first output's generator's `writableObjectMode`.12*/13export const getTransformObjectModes = (objectMode, index, newTransforms, direction) => direction === 'output'14 ? getOutputObjectModes(objectMode, index, newTransforms)15 : getInputObjectModes(objectMode, index, newTransforms);1617const getOutputObjectModes = (objectMode, index, newTransforms) => {18 const writableObjectMode = index !== 0 && newTransforms[index - 1].value.readableObjectMode;19 const readableObjectMode = objectMode ?? writableObjectMode;20 return {writableObjectMode, readableObjectMode};21};2223const 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};3031// Retrieve the `objectMode` of a file descriptor, e.g. `stdout` or `stderr`32export const getFdObjectMode = (stdioItems, direction) => {33 const lastTransform = stdioItems.findLast(({type}) => TRANSFORM_TYPES.has(type));34 if (lastTransform === undefined) {35 return false;36 }3738 return direction === 'input'39 ? lastTransform.value.writableObjectMode40 : lastTransform.value.readableObjectMode;41};
deleted:lib/stdio/option.js-57 removed
1import {STANDARD_STREAMS_ALIASES} from '../utils.js';23// Add support for `stdin`/`stdout`/`stderr` as an alias for `stdio`4export 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};89const getStdioArray = (stdio, options) => {10 if (stdio === undefined) {11 return STANDARD_STREAMS_ALIASES.map(alias => options[alias]);12 }1314 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 }1718 if (typeof stdio === 'string') {19 return [stdio, stdio, stdio];20 }2122 if (!Array.isArray(stdio)) {23 throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``);24 }2526 const length = Math.max(stdio.length, STANDARD_STREAMS_ALIASES.length);27 return Array.from({length}, (_, fdNumber) => stdio[fdNumber]);28};2930const hasAlias = options => STANDARD_STREAMS_ALIASES.some(alias => options[alias] !== undefined);3132const addDefaultValue = (stdioOption, fdNumber) => {33 if (Array.isArray(stdioOption)) {34 return stdioOption.map(item => addDefaultValue(item, fdNumber));35 }3637 if (stdioOption === null || stdioOption === undefined) {38 return fdNumber >= STANDARD_STREAMS_ALIASES.length ? 'ignore' : 'pipe';39 }4041 return stdioOption;42};4344const normalizeStdioSync = (stdioArray, buffer, verbose) => stdioArray.map((stdioOption, fdNumber) =>45 !buffer[fdNumber]46 && fdNumber !== 047 && verbose[fdNumber] !== 'full'48 && isOutputPipeOnly(stdioOption)49 ? 'ignore'50 : stdioOption);5152const isOutputPipeOnly = stdioOption => stdioOption === 'pipe'53 || (Array.isArray(stdioOption) && stdioOption.every(item => item === 'pipe'));5455const normalizeStdioAsync = (stdioArray, ipc) => ipc && !stdioArray.includes('ipc')56 ? [...stdioArray, 'ipc']57 : stdioArray;
deleted:lib/stdio/output-async.js-71 removed
1import mergeStreams from '@sindresorhus/merge-streams';2import {isStandardStream} from '../utils.js';3import {incrementMaxListeners} from '../max-listener.js';4import {pipeStreams} from './pipeline.js';5import {TRANSFORM_TYPES} from './type.js';67// 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 ended9export const pipeOutputAsync = (subprocess, fileDescriptors, controller) => {10 const inputStreamsGroups = {};1112 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 }1617 for (const {stream} of stdioItems.filter(({type}) => !TRANSFORM_TYPES.has(type))) {18 pipeStdioItem({subprocess, stream, direction, fdNumber, inputStreamsGroups, controller});19 }20 }2122 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};2728// `subprocess.stdin|stdout|stderr|stdio` is directly mutated.29const pipeTransform = (subprocess, stream, direction, fdNumber) => {30 if (direction === 'output') {31 pipeStreams(subprocess.stdio[fdNumber], stream);32 } else {33 pipeStreams(stream, subprocess.stdio[fdNumber]);34 }3536 const streamProperty = SUBPROCESS_STREAM_PROPERTIES[fdNumber];37 if (streamProperty !== undefined) {38 subprocess[streamProperty] = stream;39 }4041 subprocess.stdio[fdNumber] = stream;42};4344const SUBPROCESS_STREAM_PROPERTIES = ['stdin', 'stdout', 'stderr'];4546const pipeStdioItem = ({subprocess, stream, direction, fdNumber, inputStreamsGroups, controller}) => {47 if (stream === undefined) {48 return;49 }5051 setStandardStreamMaxListeners(stream, controller);5253 if (direction === 'output') {54 pipeStreams(subprocess.stdio[fdNumber], stream);55 } else {56 inputStreamsGroups[fdNumber] = [...(inputStreamsGroups[fdNumber] ?? []), stream];57 }58};5960// 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.62const setStandardStreamMaxListeners = (stream, {signal}) => {63 if (isStandardStream(stream)) {64 incrementMaxListeners(stream, MAX_LISTENERS_INCREMENT, signal);65 }66};6768// `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.71const MAX_LISTENERS_INCREMENT = 2;
deleted:lib/stdio/output-sync.js-90 removed
1import {writeFileSync} from 'node:fs';2import {shouldLogOutput, logLinesSync} from '../verbose/output.js';3import {getMaxBufferSync} from '../stream/max-buffer.js';4import {joinToString, joinToUint8Array, bufferToUint8Array} from './uint-array.js';5import {runGeneratorsSync} from './transform-run.js';6import {splitLinesSync} from './split.js';7import {FILE_TYPES} from './type.js';89// Apply `stdout`/`stderr` options, after spawning, in sync mode10export const transformOutputSync = ({fileDescriptors, syncResult: {output}, options, isMaxBuffer, verboseInfo}) => {11 if (output === null) {12 return {output: Array.from({length: 3})};13 }1415 const state = {};16 const transformedOutput = output.map((result, fdNumber) =>17 transformOutputResultSync({result, fileDescriptors, fdNumber, state, isMaxBuffer, verboseInfo}, options));18 return {output: transformedOutput, ...state};19};2021const transformOutputResultSync = ({result, fileDescriptors, fdNumber, state, isMaxBuffer, verboseInfo}, {buffer, encoding, lines, stripFinalNewline, maxBuffer}) => {22 if (result === null) {23 return;24 }2526 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});3435 if (shouldLogOutput({stdioItems, encoding, verboseInfo, fdNumber})) {36 const linesArray = splitLinesSync(serializedResult, false, objectMode);37 logLinesSync(linesArray, verboseInfo);38 }3940 const returnedResult = buffer[fdNumber] ? finalResult : undefined;4142 try {43 if (state.error === undefined) {44 writeToFiles(serializedResult, stdioItems);45 }4647 return returnedResult;48 } catch (error) {49 state.error = error;50 return returnedResult;51 }52};5354const truncateResult = (result, isMaxBuffer, maxBuffer) => isMaxBuffer && result.length > maxBuffer55 ? result.slice(0, maxBuffer)56 : result;5758const 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};6667const serializeChunks = ({chunks, objectMode, encoding, lines, stripFinalNewline, fdNumber}) => {68 if (objectMode) {69 return {serializedResult: chunks};70 }7172 if (encoding === 'buffer') {73 return {serializedResult: joinToUint8Array(chunks)};74 }7576 const serializedResult = joinToString(chunks, encoding);77 if (lines[fdNumber]) {78 return {serializedResult, finalResult: splitLinesSync(serializedResult, !stripFinalNewline[fdNumber], objectMode)};79 }8081 return {serializedResult};82};8384const 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
1import {finished} from 'node:stream/promises';2import {isStandardStream} from '../utils.js';34// Like `Stream.pipeline(source, destination)`, but does not destroy standard streams.5export const pipeStreams = (source, destination) => {6 source.pipe(destination);7 onSourceFinish(source, destination);8 onDestinationFinish(source, destination);9};1011// `source.pipe(destination)` makes `destination` end when `source` ends.12// But it does not propagate aborts or errors. This function does it.13const onSourceFinish = async (source, destination) => {14 if (isStandardStream(source) || isStandardStream(destination)) {15 return;16 }1718 try {19 await finished(source, {cleanup: true, readable: true, writable: false});20 } catch {}2122 endDestinationStream(destination);23};2425export const endDestinationStream = destination => {26 if (destination.writable) {27 destination.end();28 }29};3031// We do the same thing in the other direction as well.32const onDestinationFinish = async (source, destination) => {33 if (isStandardStream(source) || isStandardStream(destination)) {34 return;35 }3637 try {38 await finished(destination, {cleanup: true, readable: false, writable: true});39 } catch {}4041 abortSourceStream(source);42};4344export 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*` options2export const getSplitLinesGenerator = (binary, preserveNewlines, skipped, state) => binary || skipped3 ? undefined4 : initializeSplitLines(preserveNewlines, state);56export const splitLinesSync = (chunk, preserveNewlines, objectMode) => objectMode7 ? chunk.flatMap(item => splitLinesItemSync(item, preserveNewlines))8 : splitLinesItemSync(chunk, preserveNewlines);910const splitLinesItemSync = (chunk, preserveNewlines) => {11 const {transform, final} = initializeSplitLines(preserveNewlines, {});12 return [...transform(chunk), ...final()];13};1415const initializeSplitLines = (preserveNewlines, state) => {16 state.previousChunks = '';17 return {18 transform: splitGenerator.bind(undefined, state, preserveNewlines),19 final: linesFinal.bind(undefined, state),20 };21};2223// This imperative logic is much faster than using `String.split()` and uses very low memory.24const splitGenerator = function * (state, preserveNewlines, chunk) {25 if (typeof chunk !== 'string') {26 yield chunk;27 return;28 }2930 let {previousChunks} = state;31 let start = -1;3233 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);3738 if (previousChunks.length > 0) {39 line = concatString(previousChunks, line);40 previousChunks = '';41 }4243 yield line;44 start = end;45 }46 }4748 if (start !== chunk.length - 1) {49 previousChunks = concatString(previousChunks, chunk.slice(start + 1));50 }5152 state.previousChunks = previousChunks;53};5455const getNewlineLength = (chunk, end, preserveNewlines, state) => {56 if (preserveNewlines) {57 return 0;58 }5960 state.isWindowsNewline = end !== 0 && chunk[end - 1] === '\r';61 return state.isWindowsNewline ? 2 : 1;62};6364const linesFinal = function * ({previousChunks}) {65 if (previousChunks.length > 0) {66 yield previousChunks;67 }68};6970// Unless `preserveNewlines: true` is used, we strip the newline of each line.71// This re-adds them after the user `transform` code has run.72export const getAppendNewlineGenerator = ({binary, preserveNewlines, readableObjectMode, state}) => binary || preserveNewlines || readableObjectMode73 ? undefined74 : {transform: appendNewlineGenerator.bind(undefined, state)};7576const appendNewlineGenerator = function * ({isWindowsNewline = false}, chunk) {77 const {unixNewline, windowsNewline, LF, concatBytes} = typeof chunk === 'string' ? linesStringInfo : linesUint8ArrayInfo;7879 if (chunk.at(-1) === LF) {80 yield chunk;81 return;82 }8384 const newline = isWindowsNewline ? windowsNewline : unixNewline;85 yield concatBytes(chunk, newline);86};8788const concatString = (firstChunk, secondChunk) => `${firstChunk}${secondChunk}`;8990const linesStringInfo = {91 windowsNewline: '\r\n',92 unixNewline: '\n',93 LF: '\n',94 concatBytes: concatString,95};9697const 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};103104const 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
1import {STANDARD_STREAMS_ALIASES} from '../utils/standard-stream.js';23// Add support for `stdin`/`stdout`/`stderr` as an alias for `stdio`4export 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};89const getStdioArray = (stdio, options) => {10 if (stdio === undefined) {11 return STANDARD_STREAMS_ALIASES.map(alias => options[alias]);12 }1314 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 }1718 if (typeof stdio === 'string') {19 return [stdio, stdio, stdio];20 }2122 if (!Array.isArray(stdio)) {23 throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``);24 }2526 const length = Math.max(stdio.length, STANDARD_STREAMS_ALIASES.length);27 return Array.from({length}, (_, fdNumber) => stdio[fdNumber]);28};2930const hasAlias = options => STANDARD_STREAMS_ALIASES.some(alias => options[alias] !== undefined);3132const addDefaultValue = (stdioOption, fdNumber) => {33 if (Array.isArray(stdioOption)) {34 return stdioOption.map(item => addDefaultValue(item, fdNumber));35 }3637 if (stdioOption === null || stdioOption === undefined) {38 return fdNumber >= STANDARD_STREAMS_ALIASES.length ? 'ignore' : 'pipe';39 }4041 return stdioOption;42};4344const normalizeStdioSync = (stdioArray, buffer, verbose) => stdioArray.map((stdioOption, fdNumber) =>45 !buffer[fdNumber]46 && fdNumber !== 047 && verbose[fdNumber] !== 'full'48 && isOutputPipeOnly(stdioOption)49 ? 'ignore'50 : stdioOption);5152const isOutputPipeOnly = stdioOption => stdioOption === 'pipe'53 || (Array.isArray(stdioOption) && stdioOption.every(item => item === 'pipe'));5455const normalizeStdioAsync = (stdioArray, ipc) => ipc && !stdioArray.includes('ipc')56 ? [...stdioArray, 'ipc']57 : stdioArray;
deleted:lib/stdio/sync.js-54 removed
1import {readFileSync} from 'node:fs';2import {bufferToUint8Array} from './uint-array.js';3import {handleInput} from './handle.js';4import {TYPE_TO_MESSAGE} from './type.js';56// Normalize `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in sync mode7export const handleInputSync = (options, verboseInfo) => handleInput(addPropertiesSync, options, verboseInfo, true);89const forbiddenIfSync = ({type, optionName}) => {10 throwInvalidSyncValue(optionName, TYPE_TO_MESSAGE[type]);11};1213const forbiddenNativeIfSync = ({optionName, value}) => {14 if (value === 'ipc' || value === 'overlapped') {15 throwInvalidSyncValue(optionName, `"${value}"`);16 }1718 return {};19};2021const throwInvalidSyncValue = (optionName, value) => {22 throw new TypeError(`The \`${optionName}\` option cannot be ${value} with synchronous methods.`);23};2425const 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};3536const 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
1import {callbackify} from 'node:util';23export const pushChunks = callbackify(async (getChunks, state, args, transformStream) => {4 state.currentIterable = getChunks(...args);56 try {7 for await (const chunk of state.currentIterable) {8 transformStream.push(chunk);9 }10 } finally {11 delete state.currentIterable;12 }13});1415// For each new chunk, apply each `transform()` method16export const transformChunk = async function * (chunk, generators, index) {17 if (index === generators.length) {18 yield chunk;19 return;20 }2122 const {transform = identityGenerator} = generators[index];23 for await (const transformedChunk of transform(chunk)) {24 yield * transformChunk(transformedChunk, generators, index + 1);25 }26};2728// At the end, apply each `final()` method, followed by the `transform()` method of the next transforms29export const finalChunks = async function * (generators) {30 for (const [index, {final}] of Object.entries(generators)) {31 yield * generatorFinalChunks(final, Number(index), generators);32 }33};3435const generatorFinalChunks = async function * (final, index, generators) {36 if (final === undefined) {37 return;38 }3940 for await (const finalChunk of final()) {41 yield * transformChunk(finalChunk, generators, index + 1);42 }43};4445// Cancel any ongoing async generator when the Transform is destroyed, e.g. when the subprocess errors46export const destroyTransform = callbackify(async ({currentIterable}, error) => {47 if (currentIterable !== undefined) {48 await (error ? currentIterable.throw(error) : currentIterable.return());49 return;50 }5152 if (error) {53 throw error;54 }55});5657const identityGenerator = function * (chunk) {58 yield chunk;59};
deleted:lib/stdio/transform-run.js-90 removed
1import {Transform, getDefaultHighWaterMark} from 'node:stream';2import {pushChunks, transformChunk, finalChunks, destroyTransform} from './transform-async.js';3import {pushChunksSync, transformChunkSync, finalChunksSync, runTransformSync} from './transform-sync.js';4import {getEncodingTransformGenerator} from './encoding-transform.js';5import {getSplitLinesGenerator, getAppendNewlineGenerator} from './split.js';6import {getValidateTransformInput, getValidateTransformReturn} from './validate.js';7import {isAsyncGenerator} from './type.js';89/*10Generators can be used to transform/filter standard streams.1112Generators 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`1819Therefore, there is no need to allow Node.js or web transform streams.2021The `highWaterMark` is kept as the default value, since this is what `subprocess.std*` uses.2223Chunks are currently processed serially. We could add a `concurrency` option to parallelize in the future.2425Transform 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*/28export const generatorToStream = ({29 value,30 value: {transform, final, writableObjectMode, readableObjectMode},31 optionName,32}, {encoding}) => {33 const state = {};34 const generators = addInternalGenerators(value, encoding, optionName);3536 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;4748 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};6364export const runGeneratorsSync = (chunks, stdioItems, encoding, isInput) => {65 const generators = stdioItems.filter(({type}) => type === 'generator');66 const reversedGenerators = isInput ? generators.reverse() : generators;6768 for (const {value, optionName} of reversedGenerators) {69 const generators = addInternalGenerators(value, encoding, optionName);70 chunks = runTransformSync(generators, chunks);71 }7273 return chunks;74};7576const 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 functions2export const pushChunksSync = (getChunksSync, args, transformStream, done) => {3 try {4 for (const chunk of getChunksSync(...args)) {5 transformStream.push(chunk);6 }78 done();9 } catch (error) {10 done(error);11 }12};1314// Run synchronous generators with `execaSync()`15export const runTransformSync = (generators, chunks) => [16 ...chunks.flatMap(chunk => [...transformChunkSync(chunk, generators, 0)]),17 ...finalChunksSync(generators),18];1920export const transformChunkSync = function * (chunk, generators, index) {21 if (index === generators.length) {22 yield chunk;23 return;24 }2526 const {transform = identityGenerator} = generators[index];27 for (const transformedChunk of transform(chunk)) {28 yield * transformChunkSync(transformedChunk, generators, index + 1);29 }30};3132export const finalChunksSync = function * (generators) {33 for (const [index, {final}] of Object.entries(generators)) {34 yield * generatorFinalChunksSync(final, Number(index), generators);35 }36};3738const generatorFinalChunksSync = function * (final, index, generators) {39 if (final === undefined) {40 return;41 }4243 for (const finalChunk of final()) {44 yield * transformChunkSync(finalChunk, generators, index + 1);45 }46};4748const identityGenerator = function * (chunk) {49 yield chunk;50};
modified:lib/stdio/type.js+1 added-1 removed
1import {isStream as isNodeStream, isDuplexStream} from 'is-stream';2import isPlainObj from 'is-plain-obj';3import {isUint8Array} from './uint-array.js';3import {isUint8Array} from '../utils/uint-array.js';45// The `stdin`/`stdout`/`stderr` option can be of many types. This detects it.6export const getStdioItemType = (value, optionName) => {7 if (isAsyncGenerator(value)) {
156 unmodified lines
deleted:lib/stdio/uint-array.js-69 removed
1import {Buffer} from 'node:buffer';2import {StringDecoder} from 'node:string_decoder';34const {toString: objectToString} = Object.prototype;56export const isArrayBuffer = value => objectToString.call(value) === '[object ArrayBuffer]';78export const isUint8Array = value => objectToString.call(value) === '[object Uint8Array]' && !Buffer.isBuffer(value);910export const bufferToUint8Array = buffer => new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);1112const textEncoder = new TextEncoder();13const stringToUint8Array = string => textEncoder.encode(string);1415const textDecoder = new TextDecoder();16export const uint8ArrayToString = uint8Array => textDecoder.decode(uint8Array);1718export const joinToString = (uint8ArraysOrStrings, encoding) => {19 const strings = uint8ArraysToStrings(uint8ArraysOrStrings, encoding);20 return strings.join('');21};2223const uint8ArraysToStrings = (uint8ArraysOrStrings, encoding) => {24 if (encoding === 'utf8' && uint8ArraysOrStrings.every(uint8ArrayOrString => typeof uint8ArrayOrString === 'string')) {25 return uint8ArraysOrStrings;26 }2728 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};3738export const joinToUint8Array = uint8ArraysOrStrings => {39 if (uint8ArraysOrStrings.length === 1 && isUint8Array(uint8ArraysOrStrings[0])) {40 return uint8ArraysOrStrings[0];41 }4243 return concatUint8Arrays(stringsToUint8Arrays(uint8ArraysOrStrings));44};4546const stringsToUint8Arrays = uint8ArraysOrStrings => uint8ArraysOrStrings.map(uint8ArrayOrString => typeof uint8ArrayOrString === 'string'47 ? stringToUint8Array(uint8ArrayOrString)48 : uint8ArrayOrString);4950export const concatUint8Arrays = uint8Arrays => {51 const result = new Uint8Array(getJoinLength(uint8Arrays));5253 let index = 0;54 for (const uint8Array of uint8Arrays) {55 result.set(uint8Array, index);56 index += uint8Array.length;57 }5859 return result;60};6162const getJoinLength = uint8Arrays => {63 let joinLength = 0;64 for (const uint8Array of uint8Arrays) {65 joinLength += uint8Array.length;66 }6768 return joinLength;69};
deleted:lib/stdio/validate.js-42 removed
1import {Buffer} from 'node:buffer';2import {isUint8Array} from './uint-array.js';34export const getValidateTransformInput = (writableObjectMode, optionName) => writableObjectMode5 ? undefined6 : validateStringTransformInput.bind(undefined, optionName);78const 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 }1213 yield chunk;14};1516export const getValidateTransformReturn = (readableObjectMode, optionName) => readableObjectMode17 ? validateObjectTransformReturn.bind(undefined, optionName)18 : validateStringTransformReturn.bind(undefined, optionName);1920const validateObjectTransformReturn = function * (optionName, chunk) {21 validateEmptyReturn(optionName, chunk);22 yield chunk;23};2425const validateStringTransformReturn = function * (optionName, chunk) {26 validateEmptyReturn(optionName, chunk);2728 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 }3233 yield chunk;34};3536const validateEmptyReturn = (optionName, chunk) => {37 if (chunk === null || chunk === undefined) {38 throw new TypeError(`The \`${optionName}\` option's function must not call \`yield ${chunk}\`.39Instead, \`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
1import mergeStreams from '@sindresorhus/merge-streams';2import {waitForSubprocessStream} from './subprocess.js';34// `all` interleaves `stdout` and `stderr`5export const makeAllStream = ({stdout, stderr}, {all}) => all && (stdout || stderr)6 ? mergeStreams([stdout, stderr].filter(Boolean))7 : undefined;89// Read the contents of `subprocess.all` and|or wait for its completion10export 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});2122const getAllStream = ({stdout, stderr, all}, [, bufferStdout, bufferStderr]) => {23 const buffer = bufferStdout || bufferStderr;24 if (!buffer) {25 return {stream: all, buffer};26 }2728 if (!bufferStdout) {29 return {stream: stderr, buffer};30 }3132 if (!bufferStderr) {33 return {stream: stdout, buffer};34 }3536 return {stream: all, buffer};37};3839// 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.43const getAllMixed = ({all, stdout, stderr}) => all44 && stdout45 && stderr46 && stdout.readableObjectMode !== stderr.readableObjectMode;
deleted:lib/stream/contents.js-63 removed
1import {setImmediate} from 'node:timers/promises';2import getStream, {getStreamAsArrayBuffer, getStreamAsArray} from 'get-stream';3import {isArrayBuffer} from '../stdio/uint-array.js';4import {iterateForResult} from '../convert/loop.js';5import {shouldLogOutput, logLines} from '../verbose/output.js';6import {getStripFinalNewline} from '../return/strip-newline.js';7import {handleMaxBuffer} from './max-buffer.js';89export 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 }1415 if (!buffer) {16 await resumeStream(stream);17 return;18 }1920 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};2425// 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_r146549631027const resumeStream = async stream => {28 await setImmediate();29 if (stream.readableFlowing === null) {30 stream.resume();31 }32};3334const getStreamContents = async ({stream, stream: {readableObjectMode}, iterable, fdNumber, encoding, maxBuffer, lines}) => {35 try {36 if (readableObjectMode || lines) {37 return await getStreamAsArray(iterable, {maxBuffer});38 }3940 if (encoding === 'buffer') {41 return new Uint8Array(await getStreamAsArrayBuffer(iterable, {maxBuffer}));42 }4344 return await getStream(iterable, {maxBuffer});45 } catch (error) {46 return handleBufferedData(handleMaxBuffer({error, stream, readableObjectMode, lines, encoding, fdNumber}));47 }48};4950// 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 retrieve53export const getBufferedData = async streamPromise => {54 try {55 return await streamPromise;56 } catch (error) {57 return handleBufferedData(error);58 }59};6061const handleBufferedData = ({bufferedData}) => isArrayBuffer(bufferedData)62 ? new Uint8Array(bufferedData)63 : bufferedData;
deleted:lib/stream/exit-async.js-45 removed
1import {once} from 'node:events';2import {DiscardedError} from '../return/cause.js';34// 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 times11export const waitForExit = async subprocess => {12 const [spawnPayload, exitPayload] = await Promise.allSettled([13 once(subprocess, 'spawn'),14 once(subprocess, 'exit'),15 ]);1617 if (spawnPayload.status === 'rejected') {18 return [];19 }2021 return exitPayload.status === 'rejected'22 ? waitForSubprocessExit(subprocess)23 : exitPayload.value;24};2526const waitForSubprocessExit = async subprocess => {27 try {28 return await once(subprocess, 'exit');29 } catch {30 return waitForSubprocessExit(subprocess);31 }32};3334export const waitForSuccessfulExit = async exitPromise => {35 const [exitCode, signal] = await exitPromise;3637 if (!isSubprocessErrorExit(exitCode, signal) && isFailedExit(exitCode, signal)) {38 throw new DiscardedError();39 }4041 return [exitCode, signal];42};4344const isSubprocessErrorExit = (exitCode, signal) => exitCode === undefined && signal === undefined;45export const isFailedExit = (exitCode, signal) => exitCode !== 0 || signal !== null;
deleted:lib/stream/exit-sync.js-18 removed
1import {DiscardedError} from '../return/cause.js';2import {isMaxBufferSync} from './max-buffer.js';3import {isFailedExit} from './exit-async.js';45export 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};1112const getResultError = (error, exitCode, signal) => {13 if (error !== undefined) {14 return error;15 }1617 return isFailedExit(exitCode, signal) ? new DiscardedError() : undefined;18};
deleted:lib/stream/max-buffer.js-55 removed
1import {MaxBufferError} from 'get-stream';2import {getStreamName} from '../utils.js';34export const handleMaxBuffer = ({error, stream, readableObjectMode, lines, encoding, fdNumber}) => {5 if (!(error instanceof MaxBufferError)) {6 throw error;7 }89 if (fdNumber === 'all') {10 return error;11 }1213 const unit = getMaxBufferUnit(readableObjectMode, lines, encoding);14 error.maxBufferInfo = {fdNumber, unit};15 stream.destroy();16 throw error;17};1819const getMaxBufferUnit = (readableObjectMode, lines, encoding) => {20 if (readableObjectMode) {21 return 'objects';22 }2324 if (lines) {25 return 'lines';26 }2728 if (encoding === 'buffer') {29 return 'bytes';30 }3132 return 'characters';33};3435export const getMaxBufferMessage = (error, maxBuffer) => {36 const {streamName, threshold, unit} = getMaxBufferInfo(error, maxBuffer);37 return `Command's ${streamName} was larger than ${threshold} ${unit}`;38};3940const getMaxBufferInfo = (error, maxBuffer) => {41 if (error?.maxBufferInfo === undefined) {42 return {streamName: 'output', threshold: maxBuffer[1], unit: 'bytes'};43 }4445 const {maxBufferInfo: {fdNumber, unit}} = error;46 delete error.maxBufferInfo;47 return {streamName: getStreamName(fdNumber), threshold: maxBuffer[fdNumber], unit};48};4950export const isMaxBufferSync = (resultError, output, maxBuffer) => resultError?.code === 'ENOBUFS'51 && output !== null52 && output.some(result => result !== null && result.length > getMaxBufferSync(maxBuffer));5354// `spawnSync()` does not allow differentiating `maxBuffer` per file descriptor, so we always use `stdout`55export const getMaxBufferSync = maxBuffer => maxBuffer[1];
deleted:lib/stream/resolve.js-82 removed
1import {once} from 'node:events';2import {isStream as isNodeStream} from 'is-stream';3import {errorSignal} from '../exit/kill.js';4import {throwOnTimeout} from '../exit/timeout.js';5import {isStandardStream} from '../utils.js';6import {TRANSFORM_TYPES} from '../stdio/type.js';7import {waitForAllStream} from './all.js';8import {waitForSubprocessStreams} from './subprocess.js';9import {getBufferedData} from './contents.js';10import {waitForExit, waitForSuccessfulExit} from './exit-async.js';11import {waitForStream} from './wait.js';1213// Retrieve result of subprocess: exit code, signal, error, streams (stdout/stderr/all)14export 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};2526 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);3031 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};5657// Transforms replace `subprocess.std*`, which means they are not exposed to users.58// However, we still want to wait for their completion.59const waitForOriginalStreams = (originalStreams, subprocess, streamInfo) =>60 originalStreams.map((stream, fdNumber) => stream === subprocess.stdio[fdNumber]61 ? undefined62 : waitForStream(stream, fdNumber, streamInfo));6364// 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.67const 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 })));7374const throwOnSubprocessError = async (subprocess, {signal}) => {75 const [error] = await once(subprocess, 'error', {signal});76 throw error;77};7879const throwOnInternalError = async (subprocess, {signal}) => {80 const [error] = await once(subprocess, errorSignal, {signal});81 throw error;82};
deleted:lib/stream/subprocess.js-34 removed
1import {waitForStream, isInputFileDescriptor} from './wait.js';2import {getStreamOutput} from './contents.js';34// Read the contents of `subprocess.std*` and|or wait for its completion5export 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}));1718export const waitForSubprocessStream = async ({stream, fdNumber, encoding, buffer, maxBuffer, lines, allMixed, stripFinalNewline, verboseInfo, streamInfo}) => {19 if (!stream) {20 return;21 }2223 const onStreamEnd = waitForStream(stream, fdNumber, streamInfo);24 if (isInputFileDescriptor(streamInfo, fdNumber)) {25 await onStreamEnd;26 return;27 }2829 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
1import {finished} from 'node:stream/promises';23// 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.6export 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};2223// 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.34const handleStdinDestroy = (stream, {originalStreams: [originalStdin], subprocess}) => {35 const state = {stdinCleanedUp: false};36 if (stream === originalStdin) {37 spyOnStdinDestroy(stream, subprocess, state);38 }3940 return state;41};4243const spyOnStdinDestroy = (subprocessStdin, subprocess, state) => {44 const {_destroy} = subprocessStdin;45 subprocessStdin._destroy = (...args) => {46 setStdinCleanedUp(subprocess, state);47 _destroy.call(subprocessStdin, ...args);48 };49};5051const setStdinCleanedUp = ({exitCode, signalCode}, state) => {52 if (exitCode !== null || signalCode !== null) {53 state.stdinCleanedUp = true;54 }55};5657// 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.62const handleStreamError = (error, fdNumber, streamInfo, isSameDirection) => {63 if (!shouldIgnoreStreamError(error, fdNumber, streamInfo, isSameDirection)) {64 throw error;65 }66};6768const shouldIgnoreStreamError = (error, fdNumber, streamInfo, isSameDirection = true) => {69 if (streamInfo.propagating) {70 return isStreamEpipe(error) || isStreamAbort(error);71 }7273 streamInfo.propagating = true;74 return isInputFileDescriptor(streamInfo, fdNumber) === isSameDirection75 ? isStreamEpipe(error)76 : isStreamAbort(error);77};7879// 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.84export const isInputFileDescriptor = ({fileDescriptors}, fdNumber) => fdNumber !== 'all' && fileDescriptors[fdNumber].direction === 'input';8586// 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.89export const isStreamAbort = error => error?.code === 'ERR_STREAM_PREMATURE_CLOSE';9091// 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.96const isStreamEpipe = error => error?.code === 'EPIPE';
added:lib/terminate/cleanup.js+16 added
1import {addAbortListener} from 'node:events';2import {onExit} from 'signal-exit';34// `cleanup` option handling5export const cleanupOnExit = (subprocess, {cleanup, detached}, {signal}) => {6 if (!cleanup || detached) {7 return;8 }910 const removeExitHandler = onExit(() => {11 subprocess.kill();12 });13 addAbortListener(signal, () => {14 removeExitHandler();15 });16};
added:lib/terminate/kill.js+76 added
1import os from 'node:os';2import {setTimeout} from 'node:timers/promises';3import {isErrorInstance} from '../return/final-error.js';45export const normalizeForceKillAfterDelay = forceKillAfterDelay => {6 if (forceKillAfterDelay === false) {7 return forceKillAfterDelay;8 }910 if (forceKillAfterDelay === true) {11 return DEFAULT_FORCE_KILL_TIMEOUT;12 }1314 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 }1718 return forceKillAfterDelay;19};2021const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5;2223// Monkey-patches `subprocess.kill()` to add `forceKillAfterDelay` behavior and `.kill(error)`24export 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};3132const parseKillArguments = (signalOrError, errorArgument, killSignal) => {33 const [signal = killSignal, error] = isErrorInstance(signalOrError)34 ? [undefined, signalOrError]35 : [signalOrError, errorArgument];3637 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 }4041 if (error !== undefined && !isErrorInstance(error)) {42 throw new TypeError(`The second argument is optional. If specified, it must be an error instance: ${error}`);43 }4445 return {signal, error};46};4748const emitKillError = (subprocess, error) => {49 if (error !== undefined) {50 subprocess.emit(errorSignal, error);51 }52};5354// Like `error` signal but internal to Execa.55// E.g. does not make subprocess crash when no `error` listener is set.56export const errorSignal = Symbol('error');5758const setKillTimeout = async ({kill, signal, forceKillAfterDelay, killSignal, killResult, controller}) => {59 if (!shouldForceKill(signal, forceKillAfterDelay, killSignal, killResult)) {60 return;61 }6263 try {64 await setTimeout(forceKillAfterDelay, undefined, {signal: controller.signal});65 kill('SIGKILL');66 } catch {}67};6869const shouldForceKill = (signal, forceKillAfterDelay, killSignal, killResult) =>70 normalizeSignal(signal) === normalizeSignal(killSignal)71 && forceKillAfterDelay !== false72 && killResult;7374const normalizeSignal = signal => typeof signal === 'string'75 ? os.constants.signals[signal.toUpperCase()]76 : signal;
added:lib/terminate/timeout.js+20 added
1import {setTimeout} from 'node:timers/promises';2import {DiscardedError} from '../return/final-error.js';34export 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};910// `timeout` option handling11export const throwOnTimeout = (subprocess, timeout, context, controller) => timeout === 0 || timeout === undefined12 ? []13 : [killAfterTimeout(subprocess, timeout, context, controller)];1415const 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
1import {Buffer} from 'node:buffer';2import {StringDecoder} from 'node:string_decoder';3import {isUint8Array, bufferToUint8Array} from '../utils/uint-array.js';45/*6When using generators, add an internal generator that converts chunks from `Buffer` to `string` or `Uint8Array`.7This allows generator functions to operate with those types instead.8Chunks 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 string1213However, those are converted to Buffer:14- on writes: `Duplex.writable` `decodeStrings: true` default option15- on reads: `Duplex.readable` `readableEncoding: null` default option16*/17export const getEncodingTransformGenerator = (binary, encoding, skipped) => {18 if (skipped) {19 return;20 }2122 if (binary) {23 return {transform: encodingUint8ArrayGenerator.bind(undefined, new TextEncoder())};24 }2526 const stringDecoder = new StringDecoder(encoding);27 return {28 transform: encodingStringGenerator.bind(undefined, stringDecoder),29 final: encodingStringFinal.bind(undefined, stringDecoder),30 };31};3233const 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};4243const encodingStringGenerator = function * (stringDecoder, chunk) {44 yield Buffer.isBuffer(chunk) || isUint8Array(chunk)45 ? stringDecoder.write(chunk)46 : chunk;47};4849const encodingStringFinal = function * (stringDecoder) {50 const lastChunk = stringDecoder.end();51 if (lastChunk !== '') {52 yield lastChunk;53 }54};
added:lib/transform/generator.js+90 added
1import {Transform, getDefaultHighWaterMark} from 'node:stream';2import {isAsyncGenerator} from '../stdio/type.js';3import {getSplitLinesGenerator, getAppendNewlineGenerator} from './split.js';4import {getValidateTransformInput, getValidateTransformReturn} from './validate.js';5import {getEncodingTransformGenerator} from './encoding-transform.js';6import {pushChunks, transformChunk, finalChunks, destroyTransform} from './run-async.js';7import {pushChunksSync, transformChunkSync, finalChunksSync, runTransformSync} from './run-sync.js';89/*10Generators can be used to transform/filter standard streams.1112Generators 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`1819Therefore, there is no need to allow Node.js or web transform streams.2021The `highWaterMark` is kept as the default value, since this is what `subprocess.std*` uses.2223Chunks are currently processed serially. We could add a `concurrency` option to parallelize in the future.2425Transform 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*/28export const generatorToStream = ({29 value,30 value: {transform, final, writableObjectMode, readableObjectMode},31 optionName,32}, {encoding}) => {33 const state = {};34 const generators = addInternalGenerators(value, encoding, optionName);3536 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;4748 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};6364export const runGeneratorsSync = (chunks, stdioItems, encoding, isInput) => {65 const generators = stdioItems.filter(({type}) => type === 'generator');66 const reversedGenerators = isInput ? generators.reverse() : generators;6768 for (const {value, optionName} of reversedGenerators) {69 const generators = addInternalGenerators(value, encoding, optionName);70 chunks = runTransformSync(generators, chunks);71 }7273 return chunks;74};7576const 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
1import isPlainObj from 'is-plain-obj';2import {BINARY_ENCODINGS} from '../arguments/encoding-option.js';3import {TRANSFORM_TYPES} from '../stdio/type.js';4import {getTransformObjectModes} from './object-mode.js';56// Transforms generators/duplex/TransformStream can have multiple shapes.7// This normalizes it and applies default values.8export const normalizeTransforms = (stdioItems, optionName, direction, options) => [9 ...stdioItems.filter(({type}) => !TRANSFORM_TYPES.has(type)),10 ...getTransforms(stdioItems, optionName, direction, options),11];1213const getTransforms = (stdioItems, optionName, direction, {encoding}) => {14 const transforms = stdioItems.filter(({type}) => TRANSFORM_TYPES.has(type));15 const newTransforms = Array.from({length: transforms.length});1617 for (const [index, stdioItem] of Object.entries(transforms)) {18 newTransforms[index] = normalizeTransform({stdioItem, index: Number(index), newTransforms, optionName, direction, encoding});19 }2021 return sortTransforms(newTransforms, direction);22};2324const normalizeTransform = ({stdioItem, stdioItem: {type}, index, newTransforms, optionName, direction, encoding}) => {25 if (type === 'duplex') {26 return normalizeDuplex({stdioItem, optionName});27 }2829 if (type === 'webTransform') {30 return normalizeTransformStream({stdioItem, index, newTransforms, direction});31 }3233 return normalizeGenerator({stdioItem, index, newTransforms, direction, encoding});34};3536const 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 }5051 if (!objectMode && readableObjectMode) {52 throw new TypeError(`The \`${optionName}.objectMode\` option cannot be \`false\` if \`new Duplex({objectMode: true})\` is used.`);53 }5455 return {56 ...stdioItem,57 value: {transform, writableObjectMode, readableObjectMode},58 };59};6061const 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};6970const 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};8283const sortTransforms = (newTransforms, direction) => direction === 'input' ? newTransforms.reverse() : newTransforms;
added:lib/transform/object-mode.js+41 added
1import {TRANSFORM_TYPES} from '../stdio/type.js';23/*4Retrieve the `objectMode`s of a single transform.5`objectMode` determines the return value's type, i.e. the `readableObjectMode`.6The chunk argument's type is based on the previous generator's return value, i.e. the `writableObjectMode` is based on the previous `readableObjectMode`.7The 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.10Therefore its `readableObjectMode` must be `false`.11The same applies to the first output's generator's `writableObjectMode`.12*/13export const getTransformObjectModes = (objectMode, index, newTransforms, direction) => direction === 'output'14 ? getOutputObjectModes(objectMode, index, newTransforms)15 : getInputObjectModes(objectMode, index, newTransforms);1617const getOutputObjectModes = (objectMode, index, newTransforms) => {18 const writableObjectMode = index !== 0 && newTransforms[index - 1].value.readableObjectMode;19 const readableObjectMode = objectMode ?? writableObjectMode;20 return {writableObjectMode, readableObjectMode};21};2223const 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};3031// Retrieve the `objectMode` of a file descriptor, e.g. `stdout` or `stderr`32export const getFdObjectMode = (stdioItems, direction) => {33 const lastTransform = stdioItems.findLast(({type}) => TRANSFORM_TYPES.has(type));34 if (lastTransform === undefined) {35 return false;36 }3738 return direction === 'input'39 ? lastTransform.value.writableObjectMode40 : lastTransform.value.readableObjectMode;41};
added:lib/transform/run-async.js+59 added
1import {callbackify} from 'node:util';23export const pushChunks = callbackify(async (getChunks, state, args, transformStream) => {4 state.currentIterable = getChunks(...args);56 try {7 for await (const chunk of state.currentIterable) {8 transformStream.push(chunk);9 }10 } finally {11 delete state.currentIterable;12 }13});1415// For each new chunk, apply each `transform()` method16export const transformChunk = async function * (chunk, generators, index) {17 if (index === generators.length) {18 yield chunk;19 return;20 }2122 const {transform = identityGenerator} = generators[index];23 for await (const transformedChunk of transform(chunk)) {24 yield * transformChunk(transformedChunk, generators, index + 1);25 }26};2728// At the end, apply each `final()` method, followed by the `transform()` method of the next transforms29export const finalChunks = async function * (generators) {30 for (const [index, {final}] of Object.entries(generators)) {31 yield * generatorFinalChunks(final, Number(index), generators);32 }33};3435const generatorFinalChunks = async function * (final, index, generators) {36 if (final === undefined) {37 return;38 }3940 for await (const finalChunk of final()) {41 yield * transformChunk(finalChunk, generators, index + 1);42 }43};4445// Cancel any ongoing async generator when the Transform is destroyed, e.g. when the subprocess errors46export const destroyTransform = callbackify(async ({currentIterable}, error) => {47 if (currentIterable !== undefined) {48 await (error ? currentIterable.throw(error) : currentIterable.return());49 return;50 }5152 if (error) {53 throw error;54 }55});5657const 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 functions2export const pushChunksSync = (getChunksSync, args, transformStream, done) => {3 try {4 for (const chunk of getChunksSync(...args)) {5 transformStream.push(chunk);6 }78 done();9 } catch (error) {10 done(error);11 }12};1314// Run synchronous generators with `execaSync()`15export const runTransformSync = (generators, chunks) => [16 ...chunks.flatMap(chunk => [...transformChunkSync(chunk, generators, 0)]),17 ...finalChunksSync(generators),18];1920export const transformChunkSync = function * (chunk, generators, index) {21 if (index === generators.length) {22 yield chunk;23 return;24 }2526 const {transform = identityGenerator} = generators[index];27 for (const transformedChunk of transform(chunk)) {28 yield * transformChunkSync(transformedChunk, generators, index + 1);29 }30};3132export const finalChunksSync = function * (generators) {33 for (const [index, {final}] of Object.entries(generators)) {34 yield * generatorFinalChunksSync(final, Number(index), generators);35 }36};3738const generatorFinalChunksSync = function * (final, index, generators) {39 if (final === undefined) {40 return;41 }4243 for (const finalChunk of final()) {44 yield * transformChunkSync(finalChunk, generators, index + 1);45 }46};4748const 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*` options2export const getSplitLinesGenerator = (binary, preserveNewlines, skipped, state) => binary || skipped3 ? undefined4 : initializeSplitLines(preserveNewlines, state);56export const splitLinesSync = (chunk, preserveNewlines, objectMode) => objectMode7 ? chunk.flatMap(item => splitLinesItemSync(item, preserveNewlines))8 : splitLinesItemSync(chunk, preserveNewlines);910const splitLinesItemSync = (chunk, preserveNewlines) => {11 const {transform, final} = initializeSplitLines(preserveNewlines, {});12 return [...transform(chunk), ...final()];13};1415const initializeSplitLines = (preserveNewlines, state) => {16 state.previousChunks = '';17 return {18 transform: splitGenerator.bind(undefined, state, preserveNewlines),19 final: linesFinal.bind(undefined, state),20 };21};2223// This imperative logic is much faster than using `String.split()` and uses very low memory.24const splitGenerator = function * (state, preserveNewlines, chunk) {25 if (typeof chunk !== 'string') {26 yield chunk;27 return;28 }2930 let {previousChunks} = state;31 let start = -1;3233 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);3738 if (previousChunks.length > 0) {39 line = concatString(previousChunks, line);40 previousChunks = '';41 }4243 yield line;44 start = end;45 }46 }4748 if (start !== chunk.length - 1) {49 previousChunks = concatString(previousChunks, chunk.slice(start + 1));50 }5152 state.previousChunks = previousChunks;53};5455const getNewlineLength = (chunk, end, preserveNewlines, state) => {56 if (preserveNewlines) {57 return 0;58 }5960 state.isWindowsNewline = end !== 0 && chunk[end - 1] === '\r';61 return state.isWindowsNewline ? 2 : 1;62};6364const linesFinal = function * ({previousChunks}) {65 if (previousChunks.length > 0) {66 yield previousChunks;67 }68};6970// Unless `preserveNewlines: true` is used, we strip the newline of each line.71// This re-adds them after the user `transform` code has run.72export const getAppendNewlineGenerator = ({binary, preserveNewlines, readableObjectMode, state}) => binary || preserveNewlines || readableObjectMode73 ? undefined74 : {transform: appendNewlineGenerator.bind(undefined, state)};7576const appendNewlineGenerator = function * ({isWindowsNewline = false}, chunk) {77 const {unixNewline, windowsNewline, LF, concatBytes} = typeof chunk === 'string' ? linesStringInfo : linesUint8ArrayInfo;7879 if (chunk.at(-1) === LF) {80 yield chunk;81 return;82 }8384 const newline = isWindowsNewline ? windowsNewline : unixNewline;85 yield concatBytes(chunk, newline);86};8788const concatString = (firstChunk, secondChunk) => `${firstChunk}${secondChunk}`;8990const linesStringInfo = {91 windowsNewline: '\r\n',92 unixNewline: '\n',93 LF: '\n',94 concatBytes: concatString,95};9697const 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};103104const 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
1import {Buffer} from 'node:buffer';2import {isUint8Array} from '../utils/uint-array.js';34export const getValidateTransformInput = (writableObjectMode, optionName) => writableObjectMode5 ? undefined6 : validateStringTransformInput.bind(undefined, optionName);78const 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 }1213 yield chunk;14};1516export const getValidateTransformReturn = (readableObjectMode, optionName) => readableObjectMode17 ? validateObjectTransformReturn.bind(undefined, optionName)18 : validateStringTransformReturn.bind(undefined, optionName);1920const validateObjectTransformReturn = function * (optionName, chunk) {21 validateEmptyReturn(optionName, chunk);22 yield chunk;23};2425const validateStringTransformReturn = function * (optionName, chunk) {26 validateEmptyReturn(optionName, chunk);2728 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 }3233 yield chunk;34};3536const validateEmptyReturn = (optionName, chunk) => {37 if (chunk === null || chunk === undefined) {38 throw new TypeError(`The \`${optionName}\` option's function must not call \`yield ${chunk}\`.39Instead, \`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
1import {addAbortListener} from 'node:events';23export const incrementMaxListeners = (eventEmitter, maxListenersIncrement, signal) => {4 const maxListeners = eventEmitter.getMaxListeners();5 if (maxListeners === 0 || maxListeners === Number.POSITIVE_INFINITY) {6 return;7 }89 eventEmitter.setMaxListeners(maxListeners + maxListenersIncrement);10 addAbortListener(signal, () => {11 eventEmitter.setMaxListeners(eventEmitter.getMaxListeners() - maxListenersIncrement);12 });13};
added:lib/utils/standard-stream.js+6 added
1import process from 'node:process';23export const isStandardStream = stream => STANDARD_STREAMS.includes(stream);4export const STANDARD_STREAMS = [process.stdin, process.stdout, process.stderr];5export const STANDARD_STREAMS_ALIASES = ['stdin', 'stdout', 'stderr'];6export const getStreamName = fdNumber => STANDARD_STREAMS_ALIASES[fdNumber] ?? `stdio[${fdNumber}]`;
added:lib/utils/uint-array.js+69 added
1import {Buffer} from 'node:buffer';2import {StringDecoder} from 'node:string_decoder';34const {toString: objectToString} = Object.prototype;56export const isArrayBuffer = value => objectToString.call(value) === '[object ArrayBuffer]';78export const isUint8Array = value => objectToString.call(value) === '[object Uint8Array]' && !Buffer.isBuffer(value);910export const bufferToUint8Array = buffer => new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);1112const textEncoder = new TextEncoder();13const stringToUint8Array = string => textEncoder.encode(string);1415const textDecoder = new TextDecoder();16export const uint8ArrayToString = uint8Array => textDecoder.decode(uint8Array);1718export const joinToString = (uint8ArraysOrStrings, encoding) => {19 const strings = uint8ArraysToStrings(uint8ArraysOrStrings, encoding);20 return strings.join('');21};2223const uint8ArraysToStrings = (uint8ArraysOrStrings, encoding) => {24 if (encoding === 'utf8' && uint8ArraysOrStrings.every(uint8ArrayOrString => typeof uint8ArrayOrString === 'string')) {25 return uint8ArraysOrStrings;26 }2728 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};3738export const joinToUint8Array = uint8ArraysOrStrings => {39 if (uint8ArraysOrStrings.length === 1 && isUint8Array(uint8ArraysOrStrings[0])) {40 return uint8ArraysOrStrings[0];41 }4243 return concatUint8Arrays(stringsToUint8Arrays(uint8ArraysOrStrings));44};4546const stringsToUint8Arrays = uint8ArraysOrStrings => uint8ArraysOrStrings.map(uint8ArrayOrString => typeof uint8ArrayOrString === 'string'47 ? stringToUint8Array(uint8ArrayOrString)48 : uint8ArrayOrString);4950export const concatUint8Arrays = uint8Arrays => {51 const result = new Uint8Array(getJoinLength(uint8Arrays));5253 let index = 0;54 for (const uint8Array of uint8Arrays) {55 result.set(uint8Array, index);56 index += uint8Array.length;57 }5859 return result;60};6162const getJoinLength = uint8Arrays => {63 let joinLength = 0;64 for (const uint8Array of uint8Arrays) {65 joinLength += uint8Array.length;66 }6768 return joinLength;69};
modified:lib/verbose/output.js+1 added-1 removed
1import {inspect} from 'node:util';2import {escapeLines} from '../arguments/escape.js';3import {BINARY_ENCODINGS} from '../arguments/encoding.js';3import {BINARY_ENCODINGS} from '../arguments/encoding-option.js';4import {TRANSFORM_TYPES} from '../stdio/type.js';5import {verboseLog} from './log.js';67// `ignore` opts-out of `verbose` for a specific stream.
52 unmodified lines
deleted:lib/async.js-110 removed
1import {setMaxListeners} from 'node:events';2import {spawn} from 'node:child_process';3import {MaxBufferError} from 'get-stream';4import {handleCommand} from './arguments/command.js';5import {handleOptions} from './arguments/options.js';6import {makeError, makeSuccessResult} from './return/error.js';7import {stripNewline} from './return/strip-newline.js';8import {handleResult} from './return/reject.js';9import {handleEarlyError} from './return/early-error.js';10import {handleInputAsync} from './stdio/async.js';11import {pipeOutputAsync} from './stdio/output-async.js';12import {subprocessKill} from './exit/kill.js';13import {cleanupOnExit} from './exit/cleanup.js';14import {pipeToSubprocess} from './pipe/setup.js';15import {SUBPROCESS_OPTIONS} from './convert/fd-options.js';16import {logEarlyResult} from './verbose/complete.js';17import {makeAllStream} from './stream/all.js';18import {addConvertedStreams} from './convert/add.js';19import {getSubprocessResult} from './stream/resolve.js';20import {mergePromise} from './promise.js';2122export 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};3031const handleAsyncArguments = (rawFile, rawArgs, rawOptions) => {32 const {command, escapedCommand, startTime, verboseInfo} = handleCommand(rawFile, rawArgs, rawOptions);3334 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};4445// Prevent passing the `timeout` option directly to `child_process.spawn()`46const handleAsyncOptions = ({timeout, signal, cancelSignal, ...options}) => {47 if (signal !== undefined) {48 throw new TypeError('The "signal" option has been renamed to "cancelSignal" instead.');49 }5051 return {...options, timeoutDuration: timeout, signal: cancelSignal};52};5354const 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 }6162 const controller = new AbortController();63 setMaxListeners(Number.POSITIVE_INFINITY, controller.signal);6465 const originalStreams = [...subprocess.stdio];66 pipeOutputAsync(subprocess, fileDescriptors, controller);67 cleanupOnExit(subprocess, options, controller);6869 subprocess.kill = subprocessKill.bind(undefined, {kill: subprocess.kill.bind(subprocess), subprocess, options, controller});70 subprocess.all = makeAllStream(subprocess, options);71 addConvertedStreams(subprocess, options);7273 const promise = handlePromise({subprocess, options, startTime, verboseInfo, fileDescriptors, originalStreams, command, escapedCommand, controller});74 return {subprocess, promise};75};7677const handlePromise = async ({subprocess, options, startTime, verboseInfo, fileDescriptors, originalStreams, command, escapedCommand, controller}) => {78 const context = {timedOut: false};7980 const [81 errorInfo,82 [exitCode, signal],83 stdioResults,84 allResult,85 ] = await getSubprocessResult({subprocess, options, context, verboseInfo, fileDescriptors, originalStreams, controller});86 controller.abort();8788 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};9394const 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
1export const mapCommandAsync = ({file, args}) => parseCommand(file, args);2export const mapCommandSync = ({file, args}) => ({...parseCommand(file, args), isSync: true});34const 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 }89 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 }2021 const [file, ...args] = tokens;22 return {file, args};23};2425const SPACES_REGEXP = / +/g;
deleted:lib/max-listener.js-13 removed
1import {addAbortListener} from 'node:events';23export const incrementMaxListeners = (eventEmitter, maxListenersIncrement, signal) => {4 const maxListeners = eventEmitter.getMaxListeners();5 if (maxListeners === 0 || maxListeners === Number.POSITIVE_INFINITY) {6 return;7 }89 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`2export 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};89// eslint-disable-next-line unicorn/prefer-top-level-await10const nativePromisePrototype = (async () => {})().constructor.prototype;1112const descriptors = ['then', 'catch', 'finally'].map(property => [13 property,14 Reflect.getOwnPropertyDescriptor(nativePromisePrototype, property),15]);
deleted:lib/script.js-15 removed
1export const setScriptSync = (boundExeca, createNested, boundOptions) => {2 boundExeca.sync = createNested(mapScriptSync, boundOptions);3 boundExeca.s = boundExeca.sync;4};56export const mapScriptAsync = ({options}) => getScriptOptions(options);7const mapScriptSync = ({options}) => ({...getScriptOptions(options), isSync: true});89const getScriptOptions = options => ({options: {...getScriptStdinOption(options), ...options}});1011const getScriptStdinOption = ({input, inputFile, stdio}) => input === undefined && inputFile === undefined && stdio === undefined12 ? {stdin: 'inherit'}13 : {};1415export const deepScriptOptions = {preferLocal: true};
deleted:lib/sync.js-97 removed
1import {spawnSync} from 'node:child_process';2import {handleCommand} from './arguments/command.js';3import {handleOptions} from './arguments/options.js';4import {makeError, makeEarlyError, makeSuccessResult} from './return/error.js';5import {stripNewline} from './return/strip-newline.js';6import {handleResult} from './return/reject.js';7import {handleInputSync} from './stdio/sync.js';8import {addInputOptionsSync} from './stdio/input-sync.js';9import {transformOutputSync} from './stdio/output-sync.js';10import {getAllSync} from './stdio/all-sync.js';11import {logEarlyResult} from './verbose/complete.js';12import {getExitResultSync} from './stream/exit-sync.js';13import {getMaxBufferSync} from './stream/max-buffer.js';1415export 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};2021const handleSyncArguments = (rawFile, rawArgs, rawOptions) => {22 const {command, escapedCommand, startTime, verboseInfo} = handleCommand(rawFile, rawArgs, rawOptions);2324 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};3536const normalizeSyncOptions = options => options.node && !options.ipc ? {...options, ipc: false} : options;3738const validateSyncOptions = ({ipc, detached, cancelSignal}) => {39 if (ipc) {40 throwInvalidSyncOption('ipc: true');41 }4243 if (detached) {44 throwInvalidSyncOption('detached: true');45 }4647 if (cancelSignal) {48 throwInvalidSyncOption('cancelSignal');49 }50};5152const throwInvalidSyncOption = value => {53 throw new TypeError(`The "${value}" option cannot be used with synchronous methods.`);54};5556const 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 }6162 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};6869const 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};7879const normalizeSpawnSyncOptions = ({encoding, maxBuffer, ...options}) => ({...options, encoding: 'buffer', maxBuffer: getMaxBufferSync(maxBuffer)});8081const 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
1import process from 'node:process';23export const isStandardStream = stream => STANDARD_STREAMS.includes(stream);4export const STANDARD_STREAMS = [process.stdin, process.stdout, process.stderr];5export const STANDARD_STREAMS_ALIASES = ['stdin', 'stdout', 'stderr'];6export const getStreamName = fdNumber => STANDARD_STREAMS_ALIASES[fdNumber] ?? `stdio[${fdNumber}]`;
deleted:test/arguments/create-bind.js-104 removed
1import {join} from 'node:path';2import test from 'ava';3import {execa, execaSync, execaNode, $} from '../../index.js';4import {foobarString, foobarUppercase} from '../helpers/input.js';5import {uppercaseGenerator} from '../helpers/generator.js';6import {setFixtureDir, FIXTURES_DIR} from '../helpers/fixtures-dir.js';78setFixtureDir();910const NOOP_PATH = join(FIXTURES_DIR, 'noop.js');11const PRINT_ENV_PATH = join(FIXTURES_DIR, 'environment.js');1213const testBindOptions = async (t, execaMethod) => {14 const {stdout} = await execaMethod({stripFinalNewline: false})(NOOP_PATH, [foobarString]);15 t.is(stdout, `${foobarString}\n`);16};1718test('execa() can bind options', testBindOptions, execa);19test('execaNode() can bind options', testBindOptions, execaNode);20test('$ can bind options', testBindOptions, $);2122const testBindOptionsSync = (t, execaMethod) => {23 const {stdout} = execaMethod({stripFinalNewline: false})(NOOP_PATH, [foobarString]);24 t.is(stdout, `${foobarString}\n`);25};2627test('execaSync() can bind options', testBindOptionsSync, execaSync);28test('$.sync can bind options', testBindOptionsSync, $.sync);2930const testBindPriority = async (t, execaMethod) => {31 const {stdout} = await execaMethod({stripFinalNewline: false})(NOOP_PATH, [foobarString], {stripFinalNewline: true});32 t.is(stdout, foobarString);33};3435test('execa() bound options have lower priority', testBindPriority, execa);36test('execaSync() bound options have lower priority', testBindPriority, execaSync);37test('execaNode() bound options have lower priority', testBindPriority, execaNode);38test('$ bound options have lower priority', testBindPriority, $);39test('$.sync bound options have lower priority', testBindPriority, $.sync);4041const testBindUndefined = async (t, execaMethod) => {42 const {stdout} = await execaMethod({stripFinalNewline: false})(NOOP_PATH, [foobarString], {stripFinalNewline: undefined});43 t.is(stdout, foobarString);44};4546test('execa() undefined options use default value', testBindUndefined, execa);47test('execaSync() undefined options use default value', testBindUndefined, execaSync);48test('execaNode() undefined options use default value', testBindUndefined, execaNode);49test('$ undefined options use default value', testBindUndefined, $);50test('$.sync undefined options use default value', testBindUndefined, $.sync);5152const 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};5657test('execa() bound options are merged', testMergeEnv, execa);58test('execaSync() bound options are merged', testMergeEnv, execaSync);59test('execaNode() bound options are merged', testMergeEnv, execaNode);60test('$ bound options are merged', testMergeEnv, $);61test('$.sync bound options are merged', testMergeEnv, $.sync);6263const 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};6768test('execa() bound options are merged multiple times', testMergeMultiple, execa);69test('execaSync() bound options are merged multiple times', testMergeMultiple, execaSync);70test('execaNode() bound options are merged multiple times', testMergeMultiple, execaNode);71test('$ bound options are merged multiple times', testMergeMultiple, $);72test('$.sync bound options are merged multiple times', testMergeMultiple, $.sync);7374const 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};7980test('execa() bound options merge fd-specific ones', testMergeFdSpecific, execa);81test('execaNode() bound options merge fd-specific ones', testMergeFdSpecific, execaNode);82test('$ bound options merge fd-specific ones', testMergeFdSpecific, $);8384const 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};8889test('execa() bound options are merged even if undefined', testMergeEnvUndefined, execa);90test('execaSync() bound options are merged even if undefined', testMergeEnvUndefined, execaSync);91test('execaNode() bound options are merged even if undefined', testMergeEnvUndefined, execaNode);92test('$ bound options are merged even if undefined', testMergeEnvUndefined, $);93test('$.sync bound options are merged even if undefined', testMergeEnvUndefined, $.sync);9495const 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};99100test('execa() bound options only merge specific ones', testMergeSpecific, execa);101test('execaSync() bound options only merge specific ones', testMergeSpecific, execaSync);102test('execaNode() bound options only merge specific ones', testMergeSpecific, execaNode);103test('$ bound options only merge specific ones', testMergeSpecific, $);104test('$.sync bound options only merge specific ones', testMergeSpecific, $.sync);
deleted:test/arguments/create-main.js-58 removed
1import {join} from 'node:path';2import test from 'ava';3import {execa, execaSync, execaNode, $} from '../../index.js';4import {foobarString, foobarArray} from '../helpers/input.js';5import {setFixtureDir, FIXTURES_DIR} from '../helpers/fixtures-dir.js';67setFixtureDir();89const NOOP_PATH = join(FIXTURES_DIR, 'noop.js');1011const testTemplate = async (t, execaMethod) => {12 const {stdout} = await execaMethod`${NOOP_PATH} ${foobarString}`;13 t.is(stdout, foobarString);14};1516test('execa() can use template strings', testTemplate, execa);17test('execaNode() can use template strings', testTemplate, execaNode);18test('$ can use template strings', testTemplate, $);1920const testTemplateSync = (t, execaMethod) => {21 const {stdout} = execaMethod`${NOOP_PATH} ${foobarString}`;22 t.is(stdout, foobarString);23};2425test('execaSync() can use template strings', testTemplateSync, execaSync);26test('$.sync can use template strings', testTemplateSync, $.sync);2728const testTemplateOptions = async (t, execaMethod) => {29 const {stdout} = await execaMethod({stripFinalNewline: false})`${NOOP_PATH} ${foobarString}`;30 t.is(stdout, `${foobarString}\n`);31};3233test('execa() can use template strings with options', testTemplateOptions, execa);34test('execaNode() can use template strings with options', testTemplateOptions, execaNode);35test('$ can use template strings with options', testTemplateOptions, $);3637const testTemplateOptionsSync = (t, execaMethod) => {38 const {stdout} = execaMethod({stripFinalNewline: false})`${NOOP_PATH} ${foobarString}`;39 t.is(stdout, `${foobarString}\n`);40};4142test('execaSync() can use template strings with options', testTemplateOptionsSync, execaSync);43test('$.sync can use template strings with options', testTemplateOptionsSync, $.sync);4445const 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};5051test('allow commands with spaces and no array arguments', testSpacedCommand, undefined, execa);52test('allow commands with spaces and array arguments', testSpacedCommand, foobarArray, execa);53test('allow commands with spaces and no array arguments, execaSync', testSpacedCommand, undefined, execaSync);54test('allow commands with spaces and array arguments, execaSync', testSpacedCommand, foobarArray, execaSync);55test('allow commands with spaces and no array arguments, $', testSpacedCommand, undefined, $);56test('allow commands with spaces and array arguments, $', testSpacedCommand, foobarArray, $);57test('allow commands with spaces and no array arguments, $.sync', testSpacedCommand, undefined, $.sync);58test('allow commands with spaces and array arguments, $.sync', testSpacedCommand, foobarArray, $.sync);
added:test/arguments/encoding-option.js+39 added
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';45setFixtureDir();67const testInvalidEncoding = (t, encoding, message, execaMethod) => {8 const error = t.throws(() => {9 execaMethod('empty.js', {encoding});10 });11 t.true(error.message.includes(message));12};1314const UNKNOWN_ENCODING_MESSAGE = 'Please rename it to one of';15const getCorrectEncodingMessage = correctEncoding => `Please rename it to "${correctEncoding}"`;1617test('cannot pass unknown encodings', testInvalidEncoding, 'unknown', UNKNOWN_ENCODING_MESSAGE, execa);18test('cannot pass unknown encodings, sync', testInvalidEncoding, 'unknown', UNKNOWN_ENCODING_MESSAGE, execaSync);19test('cannot pass empty encodings', testInvalidEncoding, '', UNKNOWN_ENCODING_MESSAGE, execa);20test('cannot pass encoding: false', testInvalidEncoding, false, UNKNOWN_ENCODING_MESSAGE, execa);21test('cannot pass encoding: Symbol', testInvalidEncoding, Symbol('test'), UNKNOWN_ENCODING_MESSAGE, execa);22test('cannot pass encoding: null', testInvalidEncoding, null, getCorrectEncodingMessage('buffer'), execa);23test('cannot pass encoding: null, sync', testInvalidEncoding, null, getCorrectEncodingMessage('buffer'), execaSync);24/* eslint-disable unicorn/text-encoding-identifier-case */25test('cannot pass encoding: utf-8', testInvalidEncoding, 'utf-8', getCorrectEncodingMessage('utf8'), execa);26test('cannot pass encoding: utf-8, sync', testInvalidEncoding, 'utf-8', getCorrectEncodingMessage('utf8'), execaSync);27test('cannot pass encoding: UTF-8', testInvalidEncoding, 'UTF-8', getCorrectEncodingMessage('utf8'), execa);28test('cannot pass encoding: UTF-8, sync', testInvalidEncoding, 'UTF-8', getCorrectEncodingMessage('utf8'), execaSync);29test('cannot pass encoding: UTF8', testInvalidEncoding, 'UTF8', getCorrectEncodingMessage('utf8'), execa);30test('cannot pass encoding: UTF8, sync', testInvalidEncoding, 'UTF8', getCorrectEncodingMessage('utf8'), execaSync);31/* eslint-enable unicorn/text-encoding-identifier-case */32test('cannot pass encoding: utf-16le', testInvalidEncoding, 'utf-16le', getCorrectEncodingMessage('utf16le'), execa);33test('cannot pass encoding: UTF-16LE', testInvalidEncoding, 'UTF-16LE', getCorrectEncodingMessage('utf16le'), execa);34test('cannot pass encoding: UTF16LE', testInvalidEncoding, 'UTF16LE', getCorrectEncodingMessage('utf16le'), execa);35test('cannot pass encoding: ucs2', testInvalidEncoding, 'ucs2', getCorrectEncodingMessage('utf16le'), execa);36test('cannot pass encoding: UCS2', testInvalidEncoding, 'UCS2', getCorrectEncodingMessage('utf16le'), execa);37test('cannot pass encoding: ucs-2', testInvalidEncoding, 'ucs-2', getCorrectEncodingMessage('utf16le'), execa);38test('cannot pass encoding: UCS-2', testInvalidEncoding, 'UCS-2', getCorrectEncodingMessage('utf16le'), execa);39test('cannot pass encoding: binary', testInvalidEncoding, 'binary', getCorrectEncodingMessage('latin1'), execa);
deleted:test/arguments/encoding.js-39 removed
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';45setFixtureDir();67const testInvalidEncoding = (t, encoding, message, execaMethod) => {8 const error = t.throws(() => {9 execaMethod('empty.js', {encoding});10 });11 t.true(error.message.includes(message));12};1314const UNKNOWN_ENCODING_MESSAGE = 'Please rename it to one of';15const getCorrectEncodingMessage = correctEncoding => `Please rename it to "${correctEncoding}"`;1617test('cannot pass unknown encodings', testInvalidEncoding, 'unknown', UNKNOWN_ENCODING_MESSAGE, execa);18test('cannot pass unknown encodings, sync', testInvalidEncoding, 'unknown', UNKNOWN_ENCODING_MESSAGE, execaSync);19test('cannot pass empty encodings', testInvalidEncoding, '', UNKNOWN_ENCODING_MESSAGE, execa);20test('cannot pass encoding: false', testInvalidEncoding, false, UNKNOWN_ENCODING_MESSAGE, execa);21test('cannot pass encoding: Symbol', testInvalidEncoding, Symbol('test'), UNKNOWN_ENCODING_MESSAGE, execa);22test('cannot pass encoding: null', testInvalidEncoding, null, getCorrectEncodingMessage('buffer'), execa);23test('cannot pass encoding: null, sync', testInvalidEncoding, null, getCorrectEncodingMessage('buffer'), execaSync);24/* eslint-disable unicorn/text-encoding-identifier-case */25test('cannot pass encoding: utf-8', testInvalidEncoding, 'utf-8', getCorrectEncodingMessage('utf8'), execa);26test('cannot pass encoding: utf-8, sync', testInvalidEncoding, 'utf-8', getCorrectEncodingMessage('utf8'), execaSync);27test('cannot pass encoding: UTF-8', testInvalidEncoding, 'UTF-8', getCorrectEncodingMessage('utf8'), execa);28test('cannot pass encoding: UTF-8, sync', testInvalidEncoding, 'UTF-8', getCorrectEncodingMessage('utf8'), execaSync);29test('cannot pass encoding: UTF8', testInvalidEncoding, 'UTF8', getCorrectEncodingMessage('utf8'), execa);30test('cannot pass encoding: UTF8, sync', testInvalidEncoding, 'UTF8', getCorrectEncodingMessage('utf8'), execaSync);31/* eslint-enable unicorn/text-encoding-identifier-case */32test('cannot pass encoding: utf-16le', testInvalidEncoding, 'utf-16le', getCorrectEncodingMessage('utf16le'), execa);33test('cannot pass encoding: UTF-16LE', testInvalidEncoding, 'UTF-16LE', getCorrectEncodingMessage('utf16le'), execa);34test('cannot pass encoding: UTF16LE', testInvalidEncoding, 'UTF16LE', getCorrectEncodingMessage('utf16le'), execa);35test('cannot pass encoding: ucs2', testInvalidEncoding, 'ucs2', getCorrectEncodingMessage('utf16le'), execa);36test('cannot pass encoding: UCS2', testInvalidEncoding, 'UCS2', getCorrectEncodingMessage('utf16le'), execa);37test('cannot pass encoding: ucs-2', testInvalidEncoding, 'ucs-2', getCorrectEncodingMessage('utf16le'), execa);38test('cannot pass encoding: UCS-2', testInvalidEncoding, 'UCS-2', getCorrectEncodingMessage('utf16le'), execa);39test('cannot pass encoding: binary', testInvalidEncoding, 'binary', getCorrectEncodingMessage('latin1'), execa);
added:test/arguments/fd-options.js+725 added
1import {PassThrough} from 'node:stream';2import {spawn} from 'node:child_process';3import process from 'node:process';4import test from 'ava';5import {execa} from '../../index.js';6import {setFixtureDir} from '../helpers/fixtures-dir.js';7import {fullStdio, getStdio} from '../helpers/stdio.js';8import {getEarlyErrorSubprocess} from '../helpers/early-error.js';9import {assertPipeError} from '../helpers/pipe.js';1011setFixtureDir();1213const getMessage = message => Array.isArray(message)14 ? `"${message[0]}: ${message[1]}" option is incompatible`15 : message;1617const 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};3132const 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};4344const 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};5051const 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};6263test('Must set "all" option to "true" to use .pipe("all")', testPipeError, {64 from: 'all',65 message: '"all" option must be true',66});67test('Must set "all" option to "true" to use .duplex("all")', testNodeStream, {68 from: 'all',69 message: '"all" option must be true',70});71test('Must set "all" option to "true" to use .iterable("all")', testIterable, {72 from: 'all',73 message: '"all" option must be true',74});75test('.pipe() cannot pipe to non-subprocesses', testPipeError, {76 getDestination: () => new PassThrough(),77 message: 'an Execa subprocess',78});79test('.pipe() cannot pipe to non-Execa subprocesses', testPipeError, {80 getDestination: () => spawn('node', ['--version']),81 message: 'an Execa subprocess',82});83test('.pipe() "from" option cannot be "stdin"', testPipeError, {84 from: 'stdin',85 message: '"from" must not be',86});87test('.duplex() "from" option cannot be "stdin"', testNodeStream, {88 from: 'stdin',89 message: '"from" must not be',90});91test('.iterable() "from" option cannot be "stdin"', testIterable, {92 from: 'stdin',93 message: '"from" must not be',94});95test('$.pipe() "from" option cannot be "stdin"', testPipeError, {96 from: 'stdin',97 isScript: true,98 message: '"from" must not be',99});100test('.pipe() "to" option cannot be "stdout"', testPipeError, {101 to: 'stdout',102 message: '"to" must not be',103});104test('.duplex() "to" option cannot be "stdout"', testNodeStream, {105 to: 'stdout',106 message: '"to" must not be',107});108test('$.pipe() "to" option cannot be "stdout"', testPipeError, {109 to: 'stdout',110 isScript: true,111 message: '"to" must not be',112});113test('.pipe() "from" option cannot be any string', testPipeError, {114 from: 'other',115 message: 'must be "stdout", "stderr", "all"',116});117test('.duplex() "from" option cannot be any string', testNodeStream, {118 from: 'other',119 message: 'must be "stdout", "stderr", "all"',120});121test('.iterable() "from" option cannot be any string', testIterable, {122 from: 'other',123 message: 'must be "stdout", "stderr", "all"',124});125test('.pipe() "to" option cannot be any string', testPipeError, {126 to: 'other',127 message: 'must be "stdin"',128});129test('.duplex() "to" option cannot be any string', testNodeStream, {130 to: 'other',131 message: 'must be "stdin"',132});133test('.pipe() "from" option cannot be a number without "fd"', testPipeError, {134 from: '1',135 message: 'must be "stdout", "stderr", "all"',136});137test('.duplex() "from" option cannot be a number without "fd"', testNodeStream, {138 from: '1',139 message: 'must be "stdout", "stderr", "all"',140});141test('.iterable() "from" option cannot be a number without "fd"', testIterable, {142 from: '1',143 message: 'must be "stdout", "stderr", "all"',144});145test('.pipe() "to" option cannot be a number without "fd"', testPipeError, {146 to: '0',147 message: 'must be "stdin"',148});149test('.duplex() "to" option cannot be a number without "fd"', testNodeStream, {150 to: '0',151 message: 'must be "stdin"',152});153test('.pipe() "from" option cannot be just "fd"', testPipeError, {154 from: 'fd',155 message: 'must be "stdout", "stderr", "all"',156});157test('.duplex() "from" option cannot be just "fd"', testNodeStream, {158 from: 'fd',159 message: 'must be "stdout", "stderr", "all"',160});161test('.iterable() "from" option cannot be just "fd"', testIterable, {162 from: 'fd',163 message: 'must be "stdout", "stderr", "all"',164});165test('.pipe() "to" option cannot be just "fd"', testPipeError, {166 to: 'fd',167 message: 'must be "stdin"',168});169test('.duplex() "to" option cannot be just "fd"', testNodeStream, {170 to: 'fd',171 message: 'must be "stdin"',172});173test('.pipe() "from" option cannot be a float', testPipeError, {174 from: 'fd1.5',175 message: 'must be "stdout", "stderr", "all"',176});177test('.duplex() "from" option cannot be a float', testNodeStream, {178 from: 'fd1.5',179 message: 'must be "stdout", "stderr", "all"',180});181test('.iterable() "from" option cannot be a float', testIterable, {182 from: 'fd1.5',183 message: 'must be "stdout", "stderr", "all"',184});185test('.pipe() "to" option cannot be a float', testPipeError, {186 to: 'fd1.5',187 message: 'must be "stdin"',188});189test('.duplex() "to" option cannot be a float', testNodeStream, {190 to: 'fd1.5',191 message: 'must be "stdin"',192});193test('.pipe() "from" option cannot be a negative number', testPipeError, {194 from: 'fd-1',195 message: 'must be "stdout", "stderr", "all"',196});197test('.duplex() "from" option cannot be a negative number', testNodeStream, {198 from: 'fd-1',199 message: 'must be "stdout", "stderr", "all"',200});201test('.iterable() "from" option cannot be a negative number', testIterable, {202 from: 'fd-1',203 message: 'must be "stdout", "stderr", "all"',204});205test('.pipe() "to" option cannot be a negative number', testPipeError, {206 to: 'fd-1',207 message: 'must be "stdin"',208});209test('.duplex() "to" option cannot be a negative number', testNodeStream, {210 to: 'fd-1',211 message: 'must be "stdin"',212});213test('.pipe() "from" option cannot be a non-existing file descriptor', testPipeError, {214 from: 'fd3',215 message: 'file descriptor does not exist',216});217test('.duplex() "from" cannot be a non-existing file descriptor', testNodeStream, {218 from: 'fd3',219 message: 'file descriptor does not exist',220});221test('.iterable() "from" cannot be a non-existing file descriptor', testIterable, {222 from: 'fd3',223 message: 'file descriptor does not exist',224});225test('.pipe() "to" option cannot be a non-existing file descriptor', testPipeError, {226 to: 'fd3',227 message: 'file descriptor does not exist',228});229test('.duplex() "to" cannot be a non-existing file descriptor', testNodeStream, {230 to: 'fd3',231 message: 'file descriptor does not exist',232});233test('.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});238test('.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});243test('.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});248test('.pipe() "to" option cannot be an output file descriptor', testPipeError, {249 destinationOptions: fullStdio,250 to: 'fd3',251 message: 'must be a writable stream',252});253test('.duplex() "to" option cannot be an output file descriptor', testNodeStream, {254 sourceOptions: fullStdio,255 to: 'fd3',256 message: 'must be a writable stream',257});258test('.pipe() "to" option cannot be "all"', testPipeError, {259 destinationOptions: fullStdio,260 to: 'all',261 message: 'must be a writable stream',262});263test('.duplex() "to" option cannot be "all"', testNodeStream, {264 sourceOptions: fullStdio,265 to: 'all',266 message: 'must be a writable stream',267});268test('Cannot set "stdout" option to "ignore" to use .pipe()', testPipeError, {269 sourceOptions: {stdout: 'ignore'},270 message: ['stdout', '\'ignore\''],271});272test('Cannot set "stdout" option to "ignore" to use .duplex()', testNodeStream, {273 sourceOptions: {stdout: 'ignore'},274 message: ['stdout', '\'ignore\''],275});276test('Cannot set "stdout" option to "ignore" to use .iterable()', testIterable, {277 sourceOptions: {stdout: 'ignore'},278 message: ['stdout', '\'ignore\''],279});280test('Cannot set "stdin" option to "ignore" to use .pipe()', testPipeError, {281 destinationOptions: {stdin: 'ignore'},282 message: ['stdin', '\'ignore\''],283});284test('Cannot set "stdin" option to "ignore" to use .duplex()', testNodeStream, {285 sourceOptions: {stdin: 'ignore'},286 message: ['stdin', '\'ignore\''],287 writable: true,288});289test('Cannot set "stdout" option to "ignore" to use .pipe(1)', testPipeError, {290 sourceOptions: {stdout: 'ignore'},291 from: 'fd1',292 message: ['stdout', '\'ignore\''],293});294test('Cannot set "stdout" option to "ignore" to use .duplex(1)', testNodeStream, {295 sourceOptions: {stdout: 'ignore'},296 from: 'fd1',297 message: ['stdout', '\'ignore\''],298});299test('Cannot set "stdout" option to "ignore" to use .iterable(1)', testIterable, {300 sourceOptions: {stdout: 'ignore'},301 from: 'fd1',302 message: ['stdout', '\'ignore\''],303});304test('Cannot set "stdin" option to "ignore" to use .pipe(0)', testPipeError, {305 destinationOptions: {stdin: 'ignore'},306 message: ['stdin', '\'ignore\''],307 to: 'fd0',308});309test('Cannot set "stdin" option to "ignore" to use .duplex(0)', testNodeStream, {310 sourceOptions: {stdin: 'ignore'},311 message: ['stdin', '\'ignore\''],312 to: 'fd0',313});314test('Cannot set "stdout" option to "ignore" to use .pipe("stdout")', testPipeError, {315 sourceOptions: {stdout: 'ignore'},316 from: 'stdout',317 message: ['stdout', '\'ignore\''],318});319test('Cannot set "stdout" option to "ignore" to use .duplex("stdout")', testNodeStream, {320 sourceOptions: {stdout: 'ignore'},321 from: 'stdout',322 message: ['stdout', '\'ignore\''],323});324test('Cannot set "stdout" option to "ignore" to use .iterable("stdout")', testIterable, {325 sourceOptions: {stdout: 'ignore'},326 from: 'stdout',327 message: ['stdout', '\'ignore\''],328});329test('Cannot set "stdin" option to "ignore" to use .pipe("stdin")', testPipeError, {330 destinationOptions: {stdin: 'ignore'},331 message: ['stdin', '\'ignore\''],332 to: 'stdin',333});334test('Cannot set "stdin" option to "ignore" to use .duplex("stdin")', testNodeStream, {335 sourceOptions: {stdin: 'ignore'},336 message: ['stdin', '\'ignore\''],337 to: 'stdin',338});339test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe()', testPipeError, {340 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},341 message: ['stdout', '\'ignore\''],342});343test('Cannot set "stdout" + "stderr" option to "ignore" to use .duplex()', testNodeStream, {344 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},345 message: ['stdout', '\'ignore\''],346});347test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable()', testIterable, {348 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},349 message: ['stdout', '\'ignore\''],350});351test('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});356test('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});361test('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});366test('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});371test('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});376test('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});381test('Cannot set "stdio[1]" option to "ignore" to use .pipe()', testPipeError, {382 sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},383 message: ['stdio[1]', '\'ignore\''],384});385test('Cannot set "stdio[1]" option to "ignore" to use .duplex()', testNodeStream, {386 sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},387 message: ['stdio[1]', '\'ignore\''],388});389test('Cannot set "stdio[1]" option to "ignore" to use .iterable()', testIterable, {390 sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},391 message: ['stdio[1]', '\'ignore\''],392});393test('Cannot set "stdio[0]" option to "ignore" to use .pipe()', testPipeError, {394 destinationOptions: {stdio: ['ignore', 'pipe', 'pipe']},395 message: ['stdio[0]', '\'ignore\''],396});397test('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});402test('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});407test('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});412test('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});417test('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});422test('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});427test('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});432test('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});437test('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});442test('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});447test('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});452test('Cannot set "stderr" option to "ignore" to use .pipe(2)', testPipeError, {453 sourceOptions: {stderr: 'ignore'},454 from: 'fd2',455 message: ['stderr', '\'ignore\''],456});457test('Cannot set "stderr" option to "ignore" to use .duplex(2)', testNodeStream, {458 sourceOptions: {stderr: 'ignore'},459 from: 'fd2',460 message: ['stderr', '\'ignore\''],461});462test('Cannot set "stderr" option to "ignore" to use .iterable(2)', testIterable, {463 sourceOptions: {stderr: 'ignore'},464 from: 'fd2',465 message: ['stderr', '\'ignore\''],466});467test('Cannot set "stderr" option to "ignore" to use .pipe("stderr")', testPipeError, {468 sourceOptions: {stderr: 'ignore'},469 from: 'stderr',470 message: ['stderr', '\'ignore\''],471});472test('Cannot set "stderr" option to "ignore" to use .duplex("stderr")', testNodeStream, {473 sourceOptions: {stderr: 'ignore'},474 from: 'stderr',475 message: ['stderr', '\'ignore\''],476});477test('Cannot set "stderr" option to "ignore" to use .iterable("stderr")', testIterable, {478 sourceOptions: {stderr: 'ignore'},479 from: 'stderr',480 message: ['stderr', '\'ignore\''],481});482test('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});487test('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});492test('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});497test('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});502test('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});507test('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});512test('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});517test('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});522test('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});527test('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});532test('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});537test('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});542test('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});547test('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});552test('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});557test('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});562test('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});567test('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});572test('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});577test('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});582test('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});587test('Cannot set "stdout" option to "inherit" to use .pipe()', testPipeError, {588 sourceOptions: {stdout: 'inherit'},589 message: ['stdout', '\'inherit\''],590});591test('Cannot set "stdout" option to "inherit" to use .duplex()', testNodeStream, {592 sourceOptions: {stdout: 'inherit'},593 message: ['stdout', '\'inherit\''],594});595test('Cannot set "stdout" option to "inherit" to use .iterable()', testIterable, {596 sourceOptions: {stdout: 'inherit'},597 message: ['stdout', '\'inherit\''],598});599test('Cannot set "stdin" option to "inherit" to use .pipe()', testPipeError, {600 destinationOptions: {stdin: 'inherit'},601 message: ['stdin', '\'inherit\''],602});603test('Cannot set "stdin" option to "inherit" to use .duplex()', testNodeStream, {604 sourceOptions: {stdin: 'inherit'},605 message: ['stdin', '\'inherit\''],606 writable: true,607});608test('Cannot set "stdout" option to "ipc" to use .pipe()', testPipeError, {609 sourceOptions: {stdout: 'ipc'},610 message: ['stdout', '\'ipc\''],611});612test('Cannot set "stdout" option to "ipc" to use .duplex()', testNodeStream, {613 sourceOptions: {stdout: 'ipc'},614 message: ['stdout', '\'ipc\''],615});616test('Cannot set "stdout" option to "ipc" to use .iterable()', testIterable, {617 sourceOptions: {stdout: 'ipc'},618 message: ['stdout', '\'ipc\''],619});620test('Cannot set "stdin" option to "ipc" to use .pipe()', testPipeError, {621 destinationOptions: {stdin: 'ipc'},622 message: ['stdin', '\'ipc\''],623});624test('Cannot set "stdin" option to "ipc" to use .duplex()', testNodeStream, {625 sourceOptions: {stdin: 'ipc'},626 message: ['stdin', '\'ipc\''],627 writable: true,628});629test('Cannot set "stdout" option to file descriptors to use .pipe()', testPipeError, {630 sourceOptions: {stdout: 1},631 message: ['stdout', '1'],632});633test('Cannot set "stdout" option to file descriptors to use .duplex()', testNodeStream, {634 sourceOptions: {stdout: 1},635 message: ['stdout', '1'],636});637test('Cannot set "stdout" option to file descriptors to use .iterable()', testIterable, {638 sourceOptions: {stdout: 1},639 message: ['stdout', '1'],640});641test('Cannot set "stdin" option to file descriptors to use .pipe()', testPipeError, {642 destinationOptions: {stdin: 0},643 message: ['stdin', '0'],644});645test('Cannot set "stdin" option to file descriptors to use .duplex()', testNodeStream, {646 sourceOptions: {stdin: 0},647 message: ['stdin', '0'],648 writable: true,649});650test('Cannot set "stdout" option to Node.js streams to use .pipe()', testPipeError, {651 sourceOptions: {stdout: process.stdout},652 message: ['stdout', 'Stream'],653});654test('Cannot set "stdout" option to Node.js streams to use .duplex()', testNodeStream, {655 sourceOptions: {stdout: process.stdout},656 message: ['stdout', 'Stream'],657});658test('Cannot set "stdout" option to Node.js streams to use .iterable()', testIterable, {659 sourceOptions: {stdout: process.stdout},660 message: ['stdout', 'Stream'],661});662test('Cannot set "stdin" option to Node.js streams to use .pipe()', testPipeError, {663 destinationOptions: {stdin: process.stdin},664 message: ['stdin', 'Stream'],665});666test('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});671test('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});676test('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});681test('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});686test('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});691test('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});696697test('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});706707test('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});716717test('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
1import {once} from 'node:events';2import {dirname, relative} from 'node:path';3import process, {version} from 'node:process';4import {pathToFileURL} from 'node:url';5import test from 'ava';6import getNode from 'get-node';7import {pEvent} from 'p-event';8import {execa, execaSync, execaNode} from '../../index.js';9import {FIXTURES_DIR} from '../helpers/fixtures-dir.js';10import {identity, fullStdio} from '../helpers/stdio.js';11import {foobarString} from '../helpers/input.js';1213process.chdir(FIXTURES_DIR);1415const runWithNodeOption = (file, args, options) => Array.isArray(args)16 ? execa(file, args, {...options, node: true})17 : execa(file, {...options, node: true});18const runWithNodeOptionSync = (file, args, options) => Array.isArray(args)19 ? execaSync(file, args, {...options, node: true})20 : execaSync(file, {...options, node: true});21const runWithIpc = (file, options) => execa('node', [file], {...options, ipc: true});2223const testNodeSuccess = async (t, execaMethod) => {24 const {exitCode, stdout} = await execaMethod('noop.js', [foobarString]);25 t.is(exitCode, 0);26 t.is(stdout, foobarString);27};2829test('execaNode() succeeds', testNodeSuccess, execaNode);30test('The "node" option succeeds', testNodeSuccess, runWithNodeOption);31test('The "node" option succeeds - sync', testNodeSuccess, runWithNodeOptionSync);3233test('execaNode(options) succeeds', async t => {34 const {stdout} = await execaNode({stripFinalNewline: false})('noop.js', [foobarString]);35 t.is(stdout, `${foobarString}\n`);36});3738test('execaNode`...` succeeds', async t => {39 const {stdout} = await execaNode`noop.js ${foobarString}`;40 t.is(stdout, foobarString);41});4243test('execaNode().pipe(execaNode()) succeeds', async t => {44 const {stdout} = await execaNode('noop.js').pipe(execaNode('--version'));45 t.is(stdout, version);46});4748test('execaNode().pipe(execa()) requires using "node"', async t => {49 await t.throwsAsync(execaNode('noop.js').pipe(execa('--version')));50});5152test('execaNode().pipe(...) requires using "node"', async t => {53 await t.throwsAsync(execaNode('noop.js').pipe('--version'));54});5556test('execaNode().pipe`...` requires using "node"', async t => {57 await t.throwsAsync(execaNode('noop.js').pipe`--version`);58});5960test('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});6566const testDoubleNode = (t, nodePath, execaMethod) => {67 t.throws(() => {68 execaMethod(nodePath, ['noop.js']);69 }, {message: /does not need to be "node"/});70};7172test('Cannot use "node" as binary - execaNode()', testDoubleNode, 'node', execaNode);73test('Cannot use "node" as binary - "node" option', testDoubleNode, 'node', runWithNodeOption);74test('Cannot use "node" as binary - "node" option sync', testDoubleNode, 'node', runWithNodeOptionSync);75test('Cannot use path to "node" as binary - execaNode()', testDoubleNode, process.execPath, execaNode);76test('Cannot use path to "node" as binary - "node" option', testDoubleNode, process.execPath, runWithNodeOption);77test('Cannot use path to "node" as binary - "node" option sync', testDoubleNode, process.execPath, runWithNodeOptionSync);7879const getNodePath = async () => {80 const {path} = await getNode(TEST_NODE_VERSION);81 return path;82};8384const TEST_NODE_VERSION = '16.0.0';8586const 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};9192test.serial('The "nodePath" option can be used - execaNode()', testNodePath, execaNode, identity);93test.serial('The "nodePath" option can be a file URL - execaNode()', testNodePath, execaNode, pathToFileURL);94test.serial('The "nodePath" option can be used - "node" option', testNodePath, runWithNodeOption, identity);95test.serial('The "nodePath" option can be a file URL - "node" option', testNodePath, runWithNodeOption, pathToFileURL);96test.serial('The "nodePath" option can be used - "node" option sync', testNodePath, runWithNodeOptionSync, identity);97test.serial('The "nodePath" option can be a file URL - "node" option sync', testNodePath, runWithNodeOptionSync, pathToFileURL);9899const testNodePathDefault = async (t, execaMethod) => {100 const {stdout} = await execaMethod('--version');101 t.is(stdout, process.version);102};103104test('The "nodePath" option defaults to the current Node.js binary - execaNode()', testNodePathDefault, execaNode);105test('The "nodePath" option defaults to the current Node.js binary - "node" option', testNodePathDefault, runWithNodeOption);106test('The "nodePath" option defaults to the current Node.js binary - "node" option sync', testNodePathDefault, runWithNodeOptionSync);107108const 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};113114test('The "nodePath" option must be a string or URL - execaNode()', testNodePathInvalid, execaNode);115test('The "nodePath" option must be a string or URL - "node" option', testNodePathInvalid, runWithNodeOption);116test('The "nodePath" option must be a string or URL - "node" option sync', testNodePathInvalid, runWithNodeOptionSync);117118const testFormerNodePath = (t, execaMethod) => {119 t.throws(() => {120 execaMethod('noop.js', [], {execPath: process.execPath});121 }, {message: /The "execPath" option has been removed/});122};123124test('The "execPath" option cannot be used - execaNode()', testFormerNodePath, execaNode);125test('The "execPath" option cannot be used - "node" option', testFormerNodePath, runWithNodeOption);126test('The "execPath" option cannot be used - "node" option sync', testFormerNodePath, runWithNodeOptionSync);127128const nodePathArguments = ['-p', ['process.env.Path || process.env.PATH']];129130const 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};135136test.serial('The "nodePath" option impacts the subprocess - execaNode()', testSubprocessNodePath, execaNode, identity);137test.serial('The "nodePath" option impacts the subprocess - "node" option', testSubprocessNodePath, runWithNodeOption, identity);138test.serial('The "nodePath" option impacts the subprocess - "node" option sync', testSubprocessNodePath, runWithNodeOptionSync, identity);139140const testSubprocessNodePathDefault = async (t, execaMethod) => {141 const {stdout} = await execaMethod(...nodePathArguments);142 t.true(stdout.includes(dirname(process.execPath)));143};144145test('The "nodePath" option defaults to the current Node.js binary in the subprocess - execaNode()', testSubprocessNodePathDefault, execaNode);146test('The "nodePath" option defaults to the current Node.js binary in the subprocess - "node" option', testSubprocessNodePathDefault, runWithNodeOption);147test('The "nodePath" option defaults to the current Node.js binary in the subprocess - "node" option sync', testSubprocessNodePathDefault, runWithNodeOptionSync);148149test.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});154155const 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};162163test.serial('The "nodePath" option is relative to "cwd" when used in the subprocess - execaNode()', testSubprocessNodePathCwd, execaNode);164test.serial('The "nodePath" option is relative to "cwd" when used in the subprocess - "node" option', testSubprocessNodePathCwd, runWithNodeOption);165test.serial('The "nodePath" option is relative to "cwd" when used in the subprocess - "node" option sync', testSubprocessNodePathCwd, runWithNodeOptionSync);166167const 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};174175test.serial('The "nodePath" option is relative to "cwd" - execaNode()', testCwdNodePath, execaNode);176test.serial('The "nodePath" option is relative to "cwd" - "node" option', testCwdNodePath, runWithNodeOption);177test.serial('The "nodePath" option is relative to "cwd" - "node" option sync', testCwdNodePath, runWithNodeOptionSync);178179const testNodeOptions = async (t, execaMethod) => {180 const {stdout} = await execaMethod('empty.js', [], {nodeOptions: ['--version']});181 t.is(stdout, process.version);182};183184test('The "nodeOptions" option can be used - execaNode()', testNodeOptions, execaNode);185test('The "nodeOptions" option can be used - "node" option', testNodeOptions, runWithNodeOption);186test('The "nodeOptions" option can be used - "node" option sync', testNodeOptions, runWithNodeOptionSync);187188const 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);193194const testInspectRemoval = async (t, fakeExecArgv, execaMethod) => {195 const {stdout, stdio} = await spawnNestedExecaNode([], fakeExecArgv, execaMethod, '');196 t.is(stdout, foobarString);197 t.is(stdio[3], '');198};199200test('The "nodeOptions" option removes --inspect without a port when defined by current process - execaNode()', testInspectRemoval, '--inspect', 'execaNode');201test('The "nodeOptions" option removes --inspect without a port when defined by current process - "node" option', testInspectRemoval, '--inspect', 'nodeOption');202test('The "nodeOptions" option removes --inspect with a port when defined by current process - execaNode()', testInspectRemoval, '--inspect=9222', 'execaNode');203test('The "nodeOptions" option removes --inspect with a port when defined by current process - "node" option', testInspectRemoval, '--inspect=9222', 'nodeOption');204test('The "nodeOptions" option removes --inspect-brk without a port when defined by current process - execaNode()', testInspectRemoval, '--inspect-brk', 'execaNode');205test('The "nodeOptions" option removes --inspect-brk without a port when defined by current process - "node" option', testInspectRemoval, '--inspect-brk', 'nodeOption');206test('The "nodeOptions" option removes --inspect-brk with a port when defined by current process - execaNode()', testInspectRemoval, '--inspect-brk=9223', 'execaNode');207test('The "nodeOptions" option removes --inspect-brk with a port when defined by current process - "node" option', testInspectRemoval, '--inspect-brk=9223', 'nodeOption');208209const 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};214215test.serial('The "nodeOptions" option allows --inspect with a different port even when defined by current process - execaNode()', testInspectDifferentPort, 'execaNode');216test.serial('The "nodeOptions" option allows --inspect with a different port even when defined by current process - "node" option', testInspectDifferentPort, 'nodeOption');217218const 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};223224test.serial('The "nodeOptions" option forbids --inspect with the same port when defined by current process - execaNode()', testInspectSamePort, 'execaNode');225test.serial('The "nodeOptions" option forbids --inspect with the same port when defined by current process - "node" option', testInspectSamePort, 'nodeOption');226227const 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};236237test('execaNode() adds an ipc channel', testIpc, execaNode, {});238test('The "node" option adds an ipc channel', testIpc, runWithNodeOption, {});239test('The "ipc" option adds an ipc channel', testIpc, runWithIpc, {});240test('The "ipc" option works with "stdio: \'pipe\'"', testIpc, runWithIpc, {stdio: 'pipe'});241test('The "ipc" option works with "stdio: [\'pipe\', \'pipe\', \'pipe\']"', testIpc, runWithIpc, {stdio: ['pipe', 'pipe', 'pipe']});242test('The "ipc" option works with "stdio: [\'pipe\', \'pipe\', \'pipe\', \'ipc\']"', testIpc, runWithIpc, {stdio: ['pipe', 'pipe', 'pipe', 'ipc']});243test('The "ipc" option works with "stdout: \'pipe\'"', testIpc, runWithIpc, {stdout: 'pipe'});244245test('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});249250const 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};256257test('Can disable "ipc" - execaNode()', testDisableIpc, execaNode);258test('Can disable "ipc" - "node" option', testDisableIpc, runWithNodeOption);259test('Can disable "ipc" - "node" option sync', testDisableIpc, runWithNodeOptionSync);260261const NO_IPC_MESSAGE = /The "ipc: true" option cannot be used/;262263const testNoIpcSync = (t, node) => {264 t.throws(() => {265 execaSync('node', ['send.js'], {ipc: true, node});266 }, {message: NO_IPC_MESSAGE});267};268269test('Cannot use "ipc: true" with execaSync()', testNoIpcSync, undefined);270test('Cannot use "ipc: true" with execaSync() - "node: false"', testNoIpcSync, false);271272test('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});277278const 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};283284test('Cannot use "shell: true" - execaNode()', testNoShell, execaNode);285test('Cannot use "shell: true" - "node" option', testNoShell, runWithNodeOption);286test('Cannot use "shell: true" - "node" option sync', testNoShell, runWithNodeOptionSync);287288test('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});295296test('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
1import test from 'ava';2import {execa, execaSync, execaCommand, execaCommandSync, execaNode, $} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';45setFixtureDir();67const testInvalidArgs = async (t, execaMethod) => {8 t.throws(() => {9 execaMethod('echo', true);10 }, {message: /Second argument must be either/});11};1213test('execa()\'s second argument must be valid', testInvalidArgs, execa);14test('execaSync()\'s second argument must be valid', testInvalidArgs, execaSync);15test('execaCommand()\'s second argument must be valid', testInvalidArgs, execaCommand);16test('execaCommandSync()\'s second argument must be valid', testInvalidArgs, execaCommandSync);17test('execaNode()\'s second argument must be valid', testInvalidArgs, execaNode);18test('$\'s second argument must be valid', testInvalidArgs, $);19test('$.sync\'s second argument must be valid', testInvalidArgs, $.sync);2021const testInvalidArgsItems = async (t, execaMethod) => {22 t.throws(() => {23 execaMethod('echo', [{}]);24 }, {message: 'Second argument must be an array of strings: [object Object]'});25};2627test('execa()\'s second argument must not be objects', testInvalidArgsItems, execa);28test('execaSync()\'s second argument must not be objects', testInvalidArgsItems, execaSync);29test('execaCommand()\'s second argument must not be objects', testInvalidArgsItems, execaCommand);30test('execaCommandSync()\'s second argument must not be objects', testInvalidArgsItems, execaCommandSync);31test('execaNode()\'s second argument must not be objects', testInvalidArgsItems, execaNode);32test('$\'s second argument must not be objects', testInvalidArgsItems, $);33test('$.sync\'s second argument must not be objects', testInvalidArgsItems, $.sync);3435const testNullByteArg = async (t, execaMethod) => {36 t.throws(() => {37 execaMethod('echo', ['a\0b']);38 }, {message: /null bytes/});39};4041test('execa()\'s second argument must not include \\0', testNullByteArg, execa);42test('execaSync()\'s second argument must not include \\0', testNullByteArg, execaSync);43test('execaCommand()\'s second argument must not include \\0', testNullByteArg, execaCommand);44test('execaCommandSync()\'s second argument must not include \\0', testNullByteArg, execaCommandSync);45test('execaNode()\'s second argument must not include \\0', testNullByteArg, execaNode);46test('$\'s second argument must not include \\0', testNullByteArg, $);47test('$.sync\'s second argument must not include \\0', testNullByteArg, $.sync);
deleted:test/arguments/normalize-command.js-80 removed
1import {join, basename} from 'node:path';2import {fileURLToPath} from 'node:url';3import test from 'ava';4import {execa, execaSync, execaCommand, execaCommandSync, execaNode, $} from '../../index.js';5import {setFixtureDir, FIXTURES_DIR_URL} from '../helpers/fixtures-dir.js';6import {foobarString} from '../helpers/input.js';78setFixtureDir();910const 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};1516test('execa()\'s command argument can be a file URL', testFileUrl, execa);17test('execaSync()\'s command argument can be a file URL', testFileUrl, execaSync);18test('execaCommand()\'s command argument can be a file URL', testFileUrl, execaCommand);19test('execaCommandSync()\'s command argument can be a file URL', testFileUrl, execaCommandSync);20test('execaNode()\'s command argument can be a file URL', testFileUrl, execaNode);21test('$\'s command argument can be a file URL', testFileUrl, $);22test('$.sync\'s command argument can be a file URL', testFileUrl, $.sync);2324const 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};3031test('execa()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execa);32test('execaSync()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execaSync);33test('execaCommand()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execaCommand);34test('execaCommandSync()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execaCommandSync);35test('execaNode()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execaNode);36test('$\'s command argument cannot be a non-file URL', testInvalidFileUrl, $);37test('$.sync\'s command argument cannot be a non-file URL', testInvalidFileUrl, $.sync);3839const testInvalidCommand = async (t, arg, execaMethod) => {40 t.throws(() => {41 execaMethod(arg);42 }, {message: /First argument must be a string or a file URL/});43};4445test('execa()\'s first argument must be defined', testInvalidCommand, undefined, execa);46test('execaSync()\'s first argument must be defined', testInvalidCommand, undefined, execaSync);47test('execaCommand()\'s first argument must be defined', testInvalidCommand, undefined, execaCommand);48test('execaCommandSync()\'s first argument must be defined', testInvalidCommand, undefined, execaCommandSync);49test('execaNode()\'s first argument must be defined', testInvalidCommand, undefined, execaNode);50test('$\'s first argument must be defined', testInvalidCommand, undefined, $);51test('$.sync\'s first argument must be defined', testInvalidCommand, undefined, $.sync);52test('execa()\'s first argument must be valid', testInvalidCommand, true, execa);53test('execaSync()\'s first argument must be valid', testInvalidCommand, true, execaSync);54test('execaCommand()\'s first argument must be valid', testInvalidCommand, true, execaCommand);55test('execaCommandSync()\'s first argument must be valid', testInvalidCommand, true, execaCommandSync);56test('execaNode()\'s first argument must be valid', testInvalidCommand, true, execaNode);57test('$\'s first argument must be valid', testInvalidCommand, true, $);58test('$.sync\'s first argument must be valid', testInvalidCommand, true, $.sync);59test('execa()\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], execa);60test('execaSync()\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], execaSync);61test('execaCommand()\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], execaCommand);62test('execaCommandSync()\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], execaCommandSync);63test('execaNode()\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], execaNode);64test('$\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], $);65test('$.sync\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], $.sync);6667const 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};7374test('execa() use relative path with \'..\' chars', testRelativePath, execa);75test('execaSync() use relative path with \'..\' chars', testRelativePath, execaSync);76test('execaCommand() use relative path with \'..\' chars', testRelativePath, execaCommand);77test('execaCommandSync() use relative path with \'..\' chars', testRelativePath, execaCommandSync);78test('execaNode() use relative path with \'..\' chars', testRelativePath, execaNode);79test('$ use relative path with \'..\' chars', testRelativePath, $);80test('$.sync use relative path with \'..\' chars', testRelativePath, $.sync);
deleted:test/arguments/normalize-options.js-68 removed
1import {join} from 'node:path';2import test from 'ava';3import {execa, execaSync, execaCommand, execaCommandSync, execaNode, $} from '../../index.js';4import {setFixtureDir, FIXTURES_DIR} from '../helpers/fixtures-dir.js';56setFixtureDir();78const NOOP_PATH = join(FIXTURES_DIR, 'noop.js');910const testSerializeArg = async (t, arg, execaMethod) => {11 const {stdout} = await execaMethod(NOOP_PATH, [arg]);12 t.is(stdout, String(arg));13};1415test('execa()\'s arguments can be numbers', testSerializeArg, 1, execa);16test('execa()\'s arguments can be booleans', testSerializeArg, true, execa);17test('execa()\'s arguments can be NaN', testSerializeArg, Number.NaN, execa);18test('execa()\'s arguments can be Infinity', testSerializeArg, Number.POSITIVE_INFINITY, execa);19test('execa()\'s arguments can be null', testSerializeArg, null, execa);20test('execa()\'s arguments can be undefined', testSerializeArg, undefined, execa);21test('execa()\'s arguments can be bigints', testSerializeArg, 1n, execa);22test('execa()\'s arguments can be symbols', testSerializeArg, Symbol('test'), execa);23test('execaSync()\'s arguments can be numbers', testSerializeArg, 1, execaSync);24test('execaSync()\'s arguments can be booleans', testSerializeArg, true, execaSync);25test('execaSync()\'s arguments can be NaN', testSerializeArg, Number.NaN, execaSync);26test('execaSync()\'s arguments can be Infinity', testSerializeArg, Number.POSITIVE_INFINITY, execaSync);27test('execaSync()\'s arguments can be null', testSerializeArg, null, execaSync);28test('execaSync()\'s arguments can be undefined', testSerializeArg, undefined, execaSync);29test('execaSync()\'s arguments can be bigints', testSerializeArg, 1n, execaSync);30test('execaSync()\'s arguments can be symbols', testSerializeArg, Symbol('test'), execaSync);31test('execaNode()\'s arguments can be numbers', testSerializeArg, 1, execaNode);32test('execaNode()\'s arguments can be booleans', testSerializeArg, true, execaNode);33test('execaNode()\'s arguments can be NaN', testSerializeArg, Number.NaN, execaNode);34test('execaNode()\'s arguments can be Infinity', testSerializeArg, Number.POSITIVE_INFINITY, execaNode);35test('execaNode()\'s arguments can be null', testSerializeArg, null, execaNode);36test('execaNode()\'s arguments can be undefined', testSerializeArg, undefined, execaNode);37test('execaNode()\'s arguments can be bigints', testSerializeArg, 1n, execaNode);38test('execaNode()\'s arguments can be symbols', testSerializeArg, Symbol('test'), execaNode);39test('$\'s arguments can be numbers', testSerializeArg, 1, $);40test('$\'s arguments can be booleans', testSerializeArg, true, $);41test('$\'s arguments can be NaN', testSerializeArg, Number.NaN, $);42test('$\'s arguments can be Infinity', testSerializeArg, Number.POSITIVE_INFINITY, $);43test('$\'s arguments can be null', testSerializeArg, null, $);44test('$\'s arguments can be undefined', testSerializeArg, undefined, $);45test('$\'s arguments can be bigints', testSerializeArg, 1n, $);46test('$\'s arguments can be symbols', testSerializeArg, Symbol('test'), $);47test('$.sync\'s arguments can be numbers', testSerializeArg, 1, $.sync);48test('$.sync\'s arguments can be booleans', testSerializeArg, true, $.sync);49test('$.sync\'s arguments can be NaN', testSerializeArg, Number.NaN, $.sync);50test('$.sync\'s arguments can be Infinity', testSerializeArg, Number.POSITIVE_INFINITY, $.sync);51test('$.sync\'s arguments can be null', testSerializeArg, null, $.sync);52test('$.sync\'s arguments can be undefined', testSerializeArg, undefined, $.sync);53test('$.sync\'s arguments can be bigints', testSerializeArg, 1n, $.sync);54test('$.sync\'s arguments can be symbols', testSerializeArg, Symbol('test'), $.sync);5556const testInvalidOptions = async (t, execaMethod) => {57 t.throws(() => {58 execaMethod('echo', [], new Map());59 }, {message: /Last argument must be an options object/});60};6162test('execa()\'s third argument must be a plain object', testInvalidOptions, execa);63test('execaSync()\'s third argument must be a plain object', testInvalidOptions, execaSync);64test('execaCommand()\'s third argument must be a plain object', testInvalidOptions, execaCommand);65test('execaCommandSync()\'s third argument must be a plain object', testInvalidOptions, execaCommandSync);66test('execaNode()\'s third argument must be a plain object', testInvalidOptions, execaNode);67test('$\'s third argument must be a plain object', testInvalidOptions, $);68test('$.sync\'s third argument must be a plain object', testInvalidOptions, $.sync);
deleted:test/arguments/template.js-329 removed
1import test from 'ava';2import {$} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';45setFixtureDir();67// Workaround since some text editors or IDEs do not allow inputting \r directly8const escapedCall = string => {9 const templates = [string];10 templates.raw = [string];11 return $(templates);12};1314const testScriptStdout = async (t, getSubprocess, expectedStdout) => {15 const {stdout} = await getSubprocess();16 t.is(stdout, expectedStdout);17};1819test('$ allows number interpolation', testScriptStdout, () => $`echo.js 1 ${2}`, '1\n2');20test('$ can concatenate multiple tokens', testScriptStdout, () => $`echo.js ${'foo'}bar${'foo'}`, 'foobarfoo');21test('$ can use newlines and tab indentations', testScriptStdout, () => $`echo.js foo22 bar`, 'foo\nbar');23test('$ can use newlines and space indentations', testScriptStdout, () => $`echo.js foo24 bar`, 'foo\nbar');25test('$ can use Windows newlines and tab indentations', testScriptStdout, () => escapedCall('echo.js foo\r\n\tbar'), 'foo\nbar');26test('$ can use Windows newlines and space indentations', testScriptStdout, () => escapedCall('echo.js foo\r\n bar'), 'foo\nbar');27test('$ 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');33test('$ allows escaping spaces with interpolation', testScriptStdout, () => $`echo.js ${'foo bar'}`, 'foo bar');34test('$ allows escaping spaces in commands with interpolation', testScriptStdout, () => $`${'command with space.js'} foo bar`, 'foo\nbar');35test('$ trims', testScriptStdout, () => $` echo.js foo bar `, 'foo\nbar');36test('$ allows array interpolation', testScriptStdout, () => $`echo.js ${['foo', 'bar']}`, 'foo\nbar');37test('$ allows empty array interpolation', testScriptStdout, () => $`echo.js foo ${[]} bar`, 'foo\nbar');38test('$ allows space escaped values in array interpolation', testScriptStdout, () => $`echo.js ${['foo', 'bar baz']}`, 'foo\nbar baz');39test('$ can concatenate at the end of tokens followed by an array', testScriptStdout, () => $`echo.js foo${['bar', 'foo']}`, 'foobar\nfoo');40test('$ can concatenate at the start of tokens followed by an array', testScriptStdout, () => $`echo.js ${['foo', 'bar']}foo`, 'foo\nbarfoo');41test('$ can concatenate at the start and end of tokens followed by an array', testScriptStdout, () => $`echo.js foo${['bar', 'foo']}bar`, 'foobar\nfoobar');42test('$ handles escaped newlines', testScriptStdout, () => $`echo.js a\43b`, 'ab');44test('$ handles backslashes at end of lines', testScriptStdout, () => $`echo.js a\\45 b`, 'a\\\nb');46test('$ handles double backslashes at end of lines', testScriptStdout, () => $`echo.js a\\\\47 b`, 'a\\\\\nb');48test('$ handles tokens - a', testScriptStdout, () => $`echo.js a`, 'a');49test('$ handles expressions - a', testScriptStdout, () => $`echo.js ${'a'}`, 'a');50test('$ handles tokens - abc', testScriptStdout, () => $`echo.js abc`, 'abc');51test('$ handles expressions - abc', testScriptStdout, () => $`echo.js ${'abc'}`, 'abc');52test('$ handles tokens - ""', testScriptStdout, () => $`echo.js`, '');53test('$ handles expressions - ""', testScriptStdout, () => $`echo.js a ${''} b`, 'a\n\nb');54test('$ splits tokens - ""', testScriptStdout, () => $`echo.js ab`, 'ab');55test('$ splits expressions - ""', testScriptStdout, () => $`echo.js ${'a'}${'b'}`, 'ab');56test('$ concatenates expressions - ""', testScriptStdout, () => $`echo.js a${'b'}c`, 'abc');57test('$ handles tokens - " "', testScriptStdout, () => $`echo.js `, '');58test('$ handles expressions - " "', testScriptStdout, () => $`echo.js ${' '}`, ' ');59test('$ splits tokens - " "', testScriptStdout, () => $`echo.js a b`, 'a\nb');60test('$ splits expressions - " "', testScriptStdout, () => $`echo.js ${'a'} ${'b'}`, 'a\nb');61test('$ concatenates tokens - " "', testScriptStdout, () => $`echo.js a `, 'a');62test('$ concatenates expressions - " "', testScriptStdout, () => $`echo.js ${'a'} `, 'a');63test('$ handles tokens - " " (2 spaces)', testScriptStdout, () => $`echo.js `, '');64test('$ handles expressions - " " (2 spaces)', testScriptStdout, () => $`echo.js ${' '}`, ' ');65test('$ splits tokens - " " (2 spaces)', testScriptStdout, () => $`echo.js a b`, 'a\nb');66test('$ splits expressions - " " (2 spaces)', testScriptStdout, () => $`echo.js ${'a'} ${'b'}`, 'a\nb');67test('$ concatenates tokens - " " (2 spaces)', testScriptStdout, () => $`echo.js a `, 'a');68test('$ concatenates expressions - " " (2 spaces)', testScriptStdout, () => $`echo.js ${'a'} `, 'a');69test('$ handles tokens - " " (3 spaces)', testScriptStdout, () => $`echo.js `, '');70test('$ handles expressions - " " (3 spaces)', testScriptStdout, () => $`echo.js ${' '}`, ' ');71test('$ splits tokens - " " (3 spaces)', testScriptStdout, () => $`echo.js a b`, 'a\nb');72test('$ splits expressions - " " (3 spaces)', testScriptStdout, () => $`echo.js ${'a'} ${'b'}`, 'a\nb');73test('$ concatenates tokens - " " (3 spaces)', testScriptStdout, () => $`echo.js a `, 'a');74test('$ concatenates expressions - " " (3 spaces)', testScriptStdout, () => $`echo.js ${'a'} `, 'a');75test('$ handles tokens - \\t (no escape)', testScriptStdout, () => $`echo.js `, '');76test('$ handles expressions - \\t (no escape)', testScriptStdout, () => $`echo.js ${' '}`, '\t');77test('$ splits tokens - \\t (no escape)', testScriptStdout, () => $`echo.js a b`, 'a\nb');78test('$ splits expressions - \\t (no escape)', testScriptStdout, () => $`echo.js ${'a'} ${'b'}`, 'a\nb');79test('$ concatenates tokens - \\t (no escape)', testScriptStdout, () => $`echo.js a b`, 'a\nb');80test('$ concatenates expressions - \\t (no escape)', testScriptStdout, () => $`echo.js ${'a'} b`, 'a\nb');81test('$ handles tokens - \\t (escape)', testScriptStdout, () => $`echo.js \t`, '\t');82test('$ handles expressions - \\t (escape)', testScriptStdout, () => $`echo.js ${'\t'}`, '\t');83test('$ splits tokens - \\t (escape)', testScriptStdout, () => $`echo.js a\tb`, 'a\tb');84test('$ splits expressions - \\t (escape)', testScriptStdout, () => $`echo.js ${'a'}\t${'b'}`, 'a\tb');85test('$ concatenates tokens - \\t (escape)', testScriptStdout, () => $`echo.js \ta\t b`, '\ta\t\nb');86test('$ concatenates expressions - \\t (escape)', testScriptStdout, () => $`echo.js \t${'a'}\t b`, '\ta\t\nb');87test('$ handles tokens - \\n (no escape)', testScriptStdout, () => $`echo.js88 `, '');89test('$ handles expressions - \\n (no escape)', testScriptStdout, () => $`echo.js ${`90`} `, '\n');91test('$ splits tokens - \\n (no escape)', testScriptStdout, () => $`echo.js a92 b`, 'a\nb');93test('$ splits expressions - \\n (no escape)', testScriptStdout, () => $`echo.js ${'a'}94 ${'b'}`, 'a\nb');95test('$ concatenates tokens - \\n (no escape)', testScriptStdout, () => $`echo.js96a97 b`, 'a\nb');98test('$ concatenates expressions - \\n (no escape)', testScriptStdout, () => $`echo.js99${'a'}100 b`, 'a\nb');101test('$ handles tokens - \\n (escape)', testScriptStdout, () => $`echo.js \n `, '\n');102test('$ handles expressions - \\n (escape)', testScriptStdout, () => $`echo.js ${'\n'} `, '\n');103test('$ splits tokens - \\n (escape)', testScriptStdout, () => $`echo.js a\n b`, 'a\n\nb');104test('$ splits expressions - \\n (escape)', testScriptStdout, () => $`echo.js ${'a'}\n ${'b'}`, 'a\n\nb');105test('$ concatenates tokens - \\n (escape)', testScriptStdout, () => $`echo.js \na\n b`, '\na\n\nb');106test('$ concatenates expressions - \\n (escape)', testScriptStdout, () => $`echo.js \n${'a'}\n b`, '\na\n\nb');107test('$ handles tokens - \\r (no escape)', testScriptStdout, () => escapedCall('echo.js \r '), '');108test('$ splits tokens - \\r (no escape)', testScriptStdout, () => escapedCall('echo.js a\rb'), 'a\nb');109test('$ splits expressions - \\r (no escape)', testScriptStdout, () => escapedCall(`echo.js ${'a'}\r${'b'}`), 'a\nb');110test('$ concatenates tokens - \\r (no escape)', testScriptStdout, () => escapedCall('echo.js \ra\r b'), 'a\nb');111test('$ concatenates expressions - \\r (no escape)', testScriptStdout, () => escapedCall(`echo.js \r${'a'}\r b`), 'a\nb');112test('$ splits tokens - \\r (escape)', testScriptStdout, () => $`echo.js a\r b`, 'a\r\nb');113test('$ splits expressions - \\r (escape)', testScriptStdout, () => $`echo.js ${'a'}\r ${'b'}`, 'a\r\nb');114test('$ concatenates tokens - \\r (escape)', testScriptStdout, () => $`echo.js \ra\r b`, '\ra\r\nb');115test('$ concatenates expressions - \\r (escape)', testScriptStdout, () => $`echo.js \r${'a'}\r b`, '\ra\r\nb');116test('$ handles tokens - \\r\\n (no escape)', testScriptStdout, () => escapedCall('echo.js \r\n '), '');117test('$ splits tokens - \\r\\n (no escape)', testScriptStdout, () => escapedCall('echo.js a\r\nb'), 'a\nb');118test('$ splits expressions - \\r\\n (no escape)', testScriptStdout, () => escapedCall(`echo.js ${'a'}\r\n${'b'}`), 'a\nb');119test('$ concatenates tokens - \\r\\n (no escape)', testScriptStdout, () => escapedCall('echo.js \r\na\r\n b'), 'a\nb');120test('$ concatenates expressions - \\r\\n (no escape)', testScriptStdout, () => escapedCall(`echo.js \r\n${'a'}\r\n b`), 'a\nb');121test('$ handles tokens - \\r\\n (escape)', testScriptStdout, () => $`echo.js \r\n `, '\r\n');122test('$ handles expressions - \\r\\n (escape)', testScriptStdout, () => $`echo.js ${'\r\n'} `, '\r\n');123test('$ splits tokens - \\r\\n (escape)', testScriptStdout, () => $`echo.js a\r\n b`, 'a\r\n\nb');124test('$ splits expressions - \\r\\n (escape)', testScriptStdout, () => $`echo.js ${'a'}\r\n ${'b'}`, 'a\r\n\nb');125test('$ concatenates tokens - \\r\\n (escape)', testScriptStdout, () => $`echo.js \r\na\r\n b`, '\r\na\r\n\nb');126test('$ 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 */128test('$ handles expressions - \\f (no escape)', testScriptStdout, () => $`echo.js ${' '}`, '\f');129test('$ splits tokens - \\f (no escape)', testScriptStdout, () => $`echo.js a b`, 'a\fb');130test('$ splits expressions - \\f (no escape)', testScriptStdout, () => $`echo.js ${'a'} ${'b'}`, 'a\fb');131test('$ concatenates tokens - \\f (no escape)', testScriptStdout, () => $`echo.js a b`, '\fa\f\nb');132test('$ concatenates expressions - \\f (no escape)', testScriptStdout, () => $`echo.js ${'a'} b`, '\fa\f\nb');133/* eslint-enable no-irregular-whitespace */134test('$ handles tokens - \\f (escape)', testScriptStdout, () => $`echo.js \f`, '\f');135test('$ handles expressions - \\f (escape)', testScriptStdout, () => $`echo.js ${'\f'}`, '\f');136test('$ splits tokens - \\f (escape)', testScriptStdout, () => $`echo.js a\fb`, 'a\fb');137test('$ splits expressions - \\f (escape)', testScriptStdout, () => $`echo.js ${'a'}\f${'b'}`, 'a\fb');138test('$ concatenates tokens - \\f (escape)', testScriptStdout, () => $`echo.js \fa\f b`, '\fa\f\nb');139test('$ concatenates expressions - \\f (escape)', testScriptStdout, () => $`echo.js \f${'a'}\f b`, '\fa\f\nb');140test('$ handles tokens - \\', testScriptStdout, () => $`echo.js \\`, '\\');141test('$ handles expressions - \\', testScriptStdout, () => $`echo.js ${'\\'}`, '\\');142test('$ splits tokens - \\', testScriptStdout, () => $`echo.js a\\b`, 'a\\b');143test('$ splits expressions - \\', testScriptStdout, () => $`echo.js ${'a'}\\${'b'}`, 'a\\b');144test('$ concatenates tokens - \\', testScriptStdout, () => $`echo.js \\a\\ b`, '\\a\\\nb');145test('$ concatenates expressions - \\', testScriptStdout, () => $`echo.js \\${'a'}\\ b`, '\\a\\\nb');146test('$ handles tokens - \\\\', testScriptStdout, () => $`echo.js \\\\`, '\\\\');147test('$ handles expressions - \\\\', testScriptStdout, () => $`echo.js ${'\\\\'}`, '\\\\');148test('$ splits tokens - \\\\', testScriptStdout, () => $`echo.js a\\\\b`, 'a\\\\b');149test('$ splits expressions - \\\\', testScriptStdout, () => $`echo.js ${'a'}\\\\${'b'}`, 'a\\\\b');150test('$ concatenates tokens - \\\\', testScriptStdout, () => $`echo.js \\\\a\\\\ b`, '\\\\a\\\\\nb');151test('$ concatenates expressions - \\\\', testScriptStdout, () => $`echo.js \\\\${'a'}\\\\ b`, '\\\\a\\\\\nb');152test('$ handles tokens - `', testScriptStdout, () => $`echo.js \``, '`');153test('$ handles expressions - `', testScriptStdout, () => $`echo.js ${'`'}`, '`');154test('$ splits tokens - `', testScriptStdout, () => $`echo.js a\`b`, 'a`b');155test('$ splits expressions - `', testScriptStdout, () => $`echo.js ${'a'}\`${'b'}`, 'a`b');156test('$ concatenates tokens - `', testScriptStdout, () => $`echo.js \`a\` b`, '`a`\nb');157test('$ concatenates expressions - `', testScriptStdout, () => $`echo.js \`${'a'}\` b`, '`a`\nb');158test('$ handles tokens - \\v', testScriptStdout, () => $`echo.js \v`, '\v');159test('$ handles expressions - \\v', testScriptStdout, () => $`echo.js ${'\v'}`, '\v');160test('$ splits tokens - \\v', testScriptStdout, () => $`echo.js a\vb`, 'a\vb');161test('$ splits expressions - \\v', testScriptStdout, () => $`echo.js ${'a'}\v${'b'}`, 'a\vb');162test('$ concatenates tokens - \\v', testScriptStdout, () => $`echo.js \va\v b`, '\va\v\nb');163test('$ concatenates expressions - \\v', testScriptStdout, () => $`echo.js \v${'a'}\v b`, '\va\v\nb');164test('$ handles tokens - \\u2028', testScriptStdout, () => $`echo.js \u2028`, '\u2028');165test('$ handles expressions - \\u2028', testScriptStdout, () => $`echo.js ${'\u2028'}`, '\u2028');166test('$ splits tokens - \\u2028', testScriptStdout, () => $`echo.js a\u2028b`, 'a\u2028b');167test('$ splits expressions - \\u2028', testScriptStdout, () => $`echo.js ${'a'}\u2028${'b'}`, 'a\u2028b');168test('$ concatenates tokens - \\u2028', testScriptStdout, () => $`echo.js \u2028a\u2028 b`, '\u2028a\u2028\nb');169test('$ concatenates expressions - \\u2028', testScriptStdout, () => $`echo.js \u2028${'a'}\u2028 b`, '\u2028a\u2028\nb');170test('$ handles tokens - \\a', testScriptStdout, () => $`echo.js \a`, 'a');171test('$ splits tokens - \\a', testScriptStdout, () => $`echo.js a\ab`, 'aab');172test('$ splits expressions - \\a', testScriptStdout, () => $`echo.js ${'a'}\a${'b'}`, 'aab');173test('$ concatenates tokens - \\a', testScriptStdout, () => $`echo.js \aa\a b`, 'aaa\nb');174test('$ concatenates expressions - \\a', testScriptStdout, () => $`echo.js \a${'a'}\a b`, 'aaa\nb');175test('$ handles tokens - \\cJ', testScriptStdout, () => $`echo.js \cJ`, 'cJ');176test('$ splits tokens - \\cJ', testScriptStdout, () => $`echo.js a\cJb`, 'acJb');177test('$ splits expressions - \\cJ', testScriptStdout, () => $`echo.js ${'a'}\cJ${'b'}`, 'acJb');178test('$ concatenates tokens - \\cJ', testScriptStdout, () => $`echo.js \cJa\cJ b`, 'cJacJ\nb');179test('$ concatenates expressions - \\cJ', testScriptStdout, () => $`echo.js \cJ${'a'}\cJ b`, 'cJacJ\nb');180test('$ handles tokens - \\.', testScriptStdout, () => $`echo.js \.`, '.');181test('$ splits tokens - \\.', testScriptStdout, () => $`echo.js a\.b`, 'a.b');182test('$ splits expressions - \\.', testScriptStdout, () => $`echo.js ${'a'}\.${'b'}`, 'a.b');183test('$ concatenates tokens - \\.', testScriptStdout, () => $`echo.js \.a\. b`, '.a.\nb');184test('$ concatenates expressions - \\.', testScriptStdout, () => $`echo.js \.${'a'}\. b`, '.a.\nb');185/* eslint-disable unicorn/no-hex-escape */186test('$ handles tokens - \\x63', testScriptStdout, () => $`echo.js \x63`, 'c');187test('$ splits tokens - \\x63', testScriptStdout, () => $`echo.js a\x63b`, 'acb');188test('$ splits expressions - \\x63', testScriptStdout, () => $`echo.js ${'a'}\x63${'b'}`, 'acb');189test('$ concatenates tokens - \\x63', testScriptStdout, () => $`echo.js \x63a\x63 b`, 'cac\nb');190test('$ concatenates expressions - \\x63', testScriptStdout, () => $`echo.js \x63${'a'}\x63 b`, 'cac\nb');191/* eslint-enable unicorn/no-hex-escape */192test('$ handles tokens - \\u0063', testScriptStdout, () => $`echo.js \u0063`, 'c');193test('$ splits tokens - \\u0063', testScriptStdout, () => $`echo.js a\u0063b`, 'acb');194test('$ splits expressions - \\u0063', testScriptStdout, () => $`echo.js ${'a'}\u0063${'b'}`, 'acb');195test('$ concatenates tokens - \\u0063', testScriptStdout, () => $`echo.js \u0063a\u0063 b`, 'cac\nb');196test('$ concatenates expressions - \\u0063', testScriptStdout, () => $`echo.js \u0063${'a'}\u0063 b`, 'cac\nb');197test('$ handles tokens - \\u{1}', testScriptStdout, () => $`echo.js \u{1}`, '\u0001');198test('$ splits tokens - \\u{1}', testScriptStdout, () => $`echo.js a\u{1}b`, 'a\u0001b');199test('$ splits expressions - \\u{1}', testScriptStdout, () => $`echo.js ${'a'}\u{1}${'b'}`, 'a\u0001b');200test('$ concatenates tokens - \\u{1}', testScriptStdout, () => $`echo.js \u{1}a\u{1} b`, '\u0001a\u0001\nb');201test('$ concatenates expressions - \\u{1}', testScriptStdout, () => $`echo.js \u{1}${'a'}\u{1} b`, '\u0001a\u0001\nb');202test('$ handles tokens - \\u{63}', testScriptStdout, () => $`echo.js \u{63}`, 'c');203test('$ splits tokens - \\u{63}', testScriptStdout, () => $`echo.js a\u{63}b`, 'acb');204test('$ splits expressions - \\u{63}', testScriptStdout, () => $`echo.js ${'a'}\u{63}${'b'}`, 'acb');205test('$ concatenates tokens - \\u{63}', testScriptStdout, () => $`echo.js \u{63}a\u{63} b`, 'cac\nb');206test('$ concatenates expressions - \\u{63}', testScriptStdout, () => $`echo.js \u{63}${'a'}\u{63} b`, 'cac\nb');207test('$ handles tokens - \\u{063}', testScriptStdout, () => $`echo.js \u{063}`, 'c');208test('$ splits tokens - \\u{063}', testScriptStdout, () => $`echo.js a\u{063}b`, 'acb');209test('$ splits expressions - \\u{063}', testScriptStdout, () => $`echo.js ${'a'}\u{063}${'b'}`, 'acb');210test('$ concatenates tokens - \\u{063}', testScriptStdout, () => $`echo.js \u{063}a\u{063} b`, 'cac\nb');211test('$ concatenates expressions - \\u{063}', testScriptStdout, () => $`echo.js \u{063}${'a'}\u{063} b`, 'cac\nb');212test('$ handles tokens - \\u{0063}', testScriptStdout, () => $`echo.js \u{0063}`, 'c');213test('$ splits tokens - \\u{0063}', testScriptStdout, () => $`echo.js a\u{0063}b`, 'acb');214test('$ splits expressions - \\u{0063}', testScriptStdout, () => $`echo.js ${'a'}\u{0063}${'b'}`, 'acb');215test('$ concatenates tokens - \\u{0063}', testScriptStdout, () => $`echo.js \u{0063}a\u{0063} b`, 'cac\nb');216test('$ concatenates expressions - \\u{0063}', testScriptStdout, () => $`echo.js \u{0063}${'a'}\u{0063} b`, 'cac\nb');217test('$ handles tokens - \\u{00063}', testScriptStdout, () => $`echo.js \u{00063}`, 'c');218test('$ splits tokens - \\u{00063}', testScriptStdout, () => $`echo.js a\u{00063}b`, 'acb');219test('$ splits expressions - \\u{00063}', testScriptStdout, () => $`echo.js ${'a'}\u{00063}${'b'}`, 'acb');220test('$ concatenates tokens - \\u{00063}', testScriptStdout, () => $`echo.js \u{00063}a\u{00063} b`, 'cac\nb');221test('$ concatenates expressions - \\u{00063}', testScriptStdout, () => $`echo.js \u{00063}${'a'}\u{00063} b`, 'cac\nb');222test('$ handles tokens - \\u{000063}', testScriptStdout, () => $`echo.js \u{000063}`, 'c');223test('$ splits tokens - \\u{000063}', testScriptStdout, () => $`echo.js a\u{000063}b`, 'acb');224test('$ splits expressions - \\u{000063}', testScriptStdout, () => $`echo.js ${'a'}\u{000063}${'b'}`, 'acb');225test('$ concatenates tokens - \\u{000063}', testScriptStdout, () => $`echo.js \u{000063}a\u{000063} b`, 'cac\nb');226test('$ concatenates expressions - \\u{000063}', testScriptStdout, () => $`echo.js \u{000063}${'a'}\u{000063} b`, 'cac\nb');227test('$ handles tokens - \\u{0000063}', testScriptStdout, () => $`echo.js \u{0000063}`, 'c');228test('$ splits tokens - \\u{0000063}', testScriptStdout, () => $`echo.js a\u{0000063}b`, 'acb');229test('$ splits expressions - \\u{0000063}', testScriptStdout, () => $`echo.js ${'a'}\u{0000063}${'b'}`, 'acb');230test('$ concatenates tokens - \\u{0000063}', testScriptStdout, () => $`echo.js \u{0000063}a\u{0000063} b`, 'cac\nb');231test('$ concatenates expressions - \\u{0000063}', testScriptStdout, () => $`echo.js \u{0000063}${'a'}\u{0000063} b`, 'cac\nb');232test('$ handles tokens - \\u{0063}}', testScriptStdout, () => $`echo.js \u{0063}}`, 'c}');233test('$ splits tokens - \\u{0063}}', testScriptStdout, () => $`echo.js a\u{0063}}b`, 'ac}b');234test('$ splits expressions - \\u{0063}}', testScriptStdout, () => $`echo.js ${'a'}\u{0063}}${'b'}`, 'ac}b');235test('$ concatenates tokens - \\u{0063}}', testScriptStdout, () => $`echo.js \u{0063}}a\u{0063}} b`, 'c}ac}\nb');236test('$ concatenates expressions - \\u{0063}}', testScriptStdout, () => $`echo.js \u{0063}}${'a'}\u{0063}} b`, 'c}ac}\nb');237238const testScriptErrorStdout = async (t, getSubprocess) => {239 t.throws(getSubprocess, {message: /null bytes/});240};241242test('$ handles tokens - \\0', testScriptErrorStdout, () => $`echo.js \0`);243test('$ splits tokens - \\0', testScriptErrorStdout, () => $`echo.js a\0b`);244test('$ splits expressions - \\0', testScriptErrorStdout, () => $`echo.js ${'a'}\0${'b'}`);245test('$ concatenates tokens - \\0', testScriptErrorStdout, () => $`echo.js \0a\0 b`);246test('$ concatenates expressions - \\0', testScriptErrorStdout, () => $`echo.js \0${'a'}\0 b`);247248const 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};253254test('$ allows execa return value interpolation', testReturnInterpolate, foo => $`echo.js ${foo} bar`, 'foo\nbar');255test('$ allows execa return value buffer interpolation', testReturnInterpolate, foo => $`echo.js ${foo} bar`, 'foo\nbar', {encoding: 'buffer'});256test('$ allows execa return value array interpolation', testReturnInterpolate, foo => $`echo.js ${[foo, 'bar']}`, 'foo\nbar');257test('$ allows execa return value buffer array interpolation', testReturnInterpolate, foo => $`echo.js ${[foo, 'bar']}`, 'foo\nbar', {encoding: 'buffer'});258259const testReturnInterpolateSync = (t, getSubprocess, expectedStdout, options = {}) => {260 const foo = $(options).sync`echo.js foo`;261 const {stdout} = getSubprocess(foo);262 t.is(stdout, expectedStdout);263};264265test('$.sync allows execa return value interpolation', testReturnInterpolateSync, foo => $.sync`echo.js ${foo} bar`, 'foo\nbar');266test('$.sync allows execa return value buffer interpolation', testReturnInterpolateSync, foo => $.sync`echo.js ${foo} bar`, 'foo\nbar', {encoding: 'buffer'});267test('$.sync allows execa return value array interpolation', testReturnInterpolateSync, foo => $.sync`echo.js ${[foo, 'bar']}`, 'foo\nbar');268test('$.sync allows execa return value buffer array interpolation', testReturnInterpolateSync, foo => $.sync`echo.js ${[foo, 'bar']}`, 'foo\nbar', {encoding: 'buffer'});269270const testInvalidSequence = (t, getSubprocess) => {271 t.throws(getSubprocess, {message: /Invalid backslash sequence/});272};273274test('$ handles invalid escape sequence - \\1', testInvalidSequence, () => $`echo.js \1`);275test('$ handles invalid escape sequence - \\u', testInvalidSequence, () => $`echo.js \u`);276test('$ handles invalid escape sequence - \\u0', testInvalidSequence, () => $`echo.js \u0`);277test('$ handles invalid escape sequence - \\u00', testInvalidSequence, () => $`echo.js \u00`);278test('$ handles invalid escape sequence - \\u000', testInvalidSequence, () => $`echo.js \u000`);279test('$ handles invalid escape sequence - \\ug', testInvalidSequence, () => $`echo.js \ug`);280test('$ handles invalid escape sequence - \\u{', testInvalidSequence, () => $`echo.js \u{`);281test('$ handles invalid escape sequence - \\u{0000', testInvalidSequence, () => $`echo.js \u{0000`);282test('$ handles invalid escape sequence - \\u{g}', testInvalidSequence, () => $`echo.js \u{g}`);283/* eslint-disable unicorn/no-hex-escape */284test('$ handles invalid escape sequence - \\x', testInvalidSequence, () => $`echo.js \x`);285test('$ handles invalid escape sequence - \\x0', testInvalidSequence, () => $`echo.js \x0`);286test('$ handles invalid escape sequence - \\xgg', testInvalidSequence, () => $`echo.js \xgg`);287/* eslint-enable unicorn/no-hex-escape */288289const testEmptyScript = (t, getSubprocess) => {290 t.throws(getSubprocess, {message: /Template script must not be empty/});291};292293test('$``', testEmptyScript, () => $``);294test('$` `', testEmptyScript, () => $` `);295test('$` ` (2 spaces)', testEmptyScript, () => $` `);296test('$`\\t`', testEmptyScript, () => $` `);297test('$`\\n`', testEmptyScript, () => $`298`);299300const 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};307308test('$ throws on invalid expression - undefined', testInvalidExpression, undefined, $);309test('$ throws on invalid expression - null', testInvalidExpression, null, $);310test('$ throws on invalid expression - true', testInvalidExpression, true, $);311test('$ throws on invalid expression - {}', testInvalidExpression, {}, $);312test('$ throws on invalid expression - {foo: "bar"}', testInvalidExpression, {foo: 'bar'}, $);313test('$ throws on invalid expression - {stdout: undefined}', testInvalidExpression, {stdout: undefined}, $);314test('$ throws on invalid expression - {stdout: 1}', testInvalidExpression, {stdout: 1}, $);315test('$ throws on invalid expression - Promise.resolve()', testInvalidExpression, Promise.resolve(), $);316test('$ throws on invalid expression - Promise.resolve({stdout: "foo"})', testInvalidExpression, Promise.resolve({foo: 'bar'}), $);317test('$ throws on invalid expression - $', testInvalidExpression, () => $`noop.js`, $);318test('$ throws on invalid expression - $(options).sync', testInvalidExpression, () => $({stdio: 'ignore'}).sync`noop.js`, $);319test('$ throws on invalid expression - [undefined]', testInvalidExpression, [undefined], $);320test('$ throws on invalid expression - [null]', testInvalidExpression, [null], $);321test('$ throws on invalid expression - [true]', testInvalidExpression, [true], $);322test('$ throws on invalid expression - [{}]', testInvalidExpression, [{}], $);323test('$ throws on invalid expression - [{foo: "bar"}]', testInvalidExpression, [{foo: 'bar'}], $);324test('$ throws on invalid expression - [{stdout: undefined}]', testInvalidExpression, [{stdout: undefined}], $);325test('$ throws on invalid expression - [{stdout: 1}]', testInvalidExpression, [{stdout: 1}], $);326test('$ throws on invalid expression - [Promise.resolve()]', testInvalidExpression, [Promise.resolve()], $);327test('$ throws on invalid expression - [Promise.resolve({stdout: "foo"})]', testInvalidExpression, [Promise.resolve({stdout: 'foo'})], $);328test('$ throws on invalid expression - [$]', testInvalidExpression, () => [$`noop.js`], $);329test('$ throws on invalid expression - [$(options).sync]', testInvalidExpression, () => [$({stdio: 'ignore'}).sync`noop.js`], $);
deleted:test/convert/fd-options.js-725 removed
1import {PassThrough} from 'node:stream';2import {spawn} from 'node:child_process';3import process from 'node:process';4import test from 'ava';5import {execa} from '../../index.js';6import {setFixtureDir} from '../helpers/fixtures-dir.js';7import {fullStdio, getStdio} from '../helpers/stdio.js';8import {getEarlyErrorSubprocess} from '../helpers/early-error.js';9import {assertPipeError} from '../helpers/pipe.js';1011setFixtureDir();1213const getMessage = message => Array.isArray(message)14 ? `"${message[0]}: ${message[1]}" option is incompatible`15 : message;1617const 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};3132const 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};4344const 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};5051const 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};6263test('Must set "all" option to "true" to use .pipe("all")', testPipeError, {64 from: 'all',65 message: '"all" option must be true',66});67test('Must set "all" option to "true" to use .duplex("all")', testNodeStream, {68 from: 'all',69 message: '"all" option must be true',70});71test('Must set "all" option to "true" to use .iterable("all")', testIterable, {72 from: 'all',73 message: '"all" option must be true',74});75test('.pipe() cannot pipe to non-subprocesses', testPipeError, {76 getDestination: () => new PassThrough(),77 message: 'an Execa subprocess',78});79test('.pipe() cannot pipe to non-Execa subprocesses', testPipeError, {80 getDestination: () => spawn('node', ['--version']),81 message: 'an Execa subprocess',82});83test('.pipe() "from" option cannot be "stdin"', testPipeError, {84 from: 'stdin',85 message: '"from" must not be',86});87test('.duplex() "from" option cannot be "stdin"', testNodeStream, {88 from: 'stdin',89 message: '"from" must not be',90});91test('.iterable() "from" option cannot be "stdin"', testIterable, {92 from: 'stdin',93 message: '"from" must not be',94});95test('$.pipe() "from" option cannot be "stdin"', testPipeError, {96 from: 'stdin',97 isScript: true,98 message: '"from" must not be',99});100test('.pipe() "to" option cannot be "stdout"', testPipeError, {101 to: 'stdout',102 message: '"to" must not be',103});104test('.duplex() "to" option cannot be "stdout"', testNodeStream, {105 to: 'stdout',106 message: '"to" must not be',107});108test('$.pipe() "to" option cannot be "stdout"', testPipeError, {109 to: 'stdout',110 isScript: true,111 message: '"to" must not be',112});113test('.pipe() "from" option cannot be any string', testPipeError, {114 from: 'other',115 message: 'must be "stdout", "stderr", "all"',116});117test('.duplex() "from" option cannot be any string', testNodeStream, {118 from: 'other',119 message: 'must be "stdout", "stderr", "all"',120});121test('.iterable() "from" option cannot be any string', testIterable, {122 from: 'other',123 message: 'must be "stdout", "stderr", "all"',124});125test('.pipe() "to" option cannot be any string', testPipeError, {126 to: 'other',127 message: 'must be "stdin"',128});129test('.duplex() "to" option cannot be any string', testNodeStream, {130 to: 'other',131 message: 'must be "stdin"',132});133test('.pipe() "from" option cannot be a number without "fd"', testPipeError, {134 from: '1',135 message: 'must be "stdout", "stderr", "all"',136});137test('.duplex() "from" option cannot be a number without "fd"', testNodeStream, {138 from: '1',139 message: 'must be "stdout", "stderr", "all"',140});141test('.iterable() "from" option cannot be a number without "fd"', testIterable, {142 from: '1',143 message: 'must be "stdout", "stderr", "all"',144});145test('.pipe() "to" option cannot be a number without "fd"', testPipeError, {146 to: '0',147 message: 'must be "stdin"',148});149test('.duplex() "to" option cannot be a number without "fd"', testNodeStream, {150 to: '0',151 message: 'must be "stdin"',152});153test('.pipe() "from" option cannot be just "fd"', testPipeError, {154 from: 'fd',155 message: 'must be "stdout", "stderr", "all"',156});157test('.duplex() "from" option cannot be just "fd"', testNodeStream, {158 from: 'fd',159 message: 'must be "stdout", "stderr", "all"',160});161test('.iterable() "from" option cannot be just "fd"', testIterable, {162 from: 'fd',163 message: 'must be "stdout", "stderr", "all"',164});165test('.pipe() "to" option cannot be just "fd"', testPipeError, {166 to: 'fd',167 message: 'must be "stdin"',168});169test('.duplex() "to" option cannot be just "fd"', testNodeStream, {170 to: 'fd',171 message: 'must be "stdin"',172});173test('.pipe() "from" option cannot be a float', testPipeError, {174 from: 'fd1.5',175 message: 'must be "stdout", "stderr", "all"',176});177test('.duplex() "from" option cannot be a float', testNodeStream, {178 from: 'fd1.5',179 message: 'must be "stdout", "stderr", "all"',180});181test('.iterable() "from" option cannot be a float', testIterable, {182 from: 'fd1.5',183 message: 'must be "stdout", "stderr", "all"',184});185test('.pipe() "to" option cannot be a float', testPipeError, {186 to: 'fd1.5',187 message: 'must be "stdin"',188});189test('.duplex() "to" option cannot be a float', testNodeStream, {190 to: 'fd1.5',191 message: 'must be "stdin"',192});193test('.pipe() "from" option cannot be a negative number', testPipeError, {194 from: 'fd-1',195 message: 'must be "stdout", "stderr", "all"',196});197test('.duplex() "from" option cannot be a negative number', testNodeStream, {198 from: 'fd-1',199 message: 'must be "stdout", "stderr", "all"',200});201test('.iterable() "from" option cannot be a negative number', testIterable, {202 from: 'fd-1',203 message: 'must be "stdout", "stderr", "all"',204});205test('.pipe() "to" option cannot be a negative number', testPipeError, {206 to: 'fd-1',207 message: 'must be "stdin"',208});209test('.duplex() "to" option cannot be a negative number', testNodeStream, {210 to: 'fd-1',211 message: 'must be "stdin"',212});213test('.pipe() "from" option cannot be a non-existing file descriptor', testPipeError, {214 from: 'fd3',215 message: 'file descriptor does not exist',216});217test('.duplex() "from" cannot be a non-existing file descriptor', testNodeStream, {218 from: 'fd3',219 message: 'file descriptor does not exist',220});221test('.iterable() "from" cannot be a non-existing file descriptor', testIterable, {222 from: 'fd3',223 message: 'file descriptor does not exist',224});225test('.pipe() "to" option cannot be a non-existing file descriptor', testPipeError, {226 to: 'fd3',227 message: 'file descriptor does not exist',228});229test('.duplex() "to" cannot be a non-existing file descriptor', testNodeStream, {230 to: 'fd3',231 message: 'file descriptor does not exist',232});233test('.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});238test('.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});243test('.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});248test('.pipe() "to" option cannot be an output file descriptor', testPipeError, {249 destinationOptions: fullStdio,250 to: 'fd3',251 message: 'must be a writable stream',252});253test('.duplex() "to" option cannot be an output file descriptor', testNodeStream, {254 sourceOptions: fullStdio,255 to: 'fd3',256 message: 'must be a writable stream',257});258test('.pipe() "to" option cannot be "all"', testPipeError, {259 destinationOptions: fullStdio,260 to: 'all',261 message: 'must be a writable stream',262});263test('.duplex() "to" option cannot be "all"', testNodeStream, {264 sourceOptions: fullStdio,265 to: 'all',266 message: 'must be a writable stream',267});268test('Cannot set "stdout" option to "ignore" to use .pipe()', testPipeError, {269 sourceOptions: {stdout: 'ignore'},270 message: ['stdout', '\'ignore\''],271});272test('Cannot set "stdout" option to "ignore" to use .duplex()', testNodeStream, {273 sourceOptions: {stdout: 'ignore'},274 message: ['stdout', '\'ignore\''],275});276test('Cannot set "stdout" option to "ignore" to use .iterable()', testIterable, {277 sourceOptions: {stdout: 'ignore'},278 message: ['stdout', '\'ignore\''],279});280test('Cannot set "stdin" option to "ignore" to use .pipe()', testPipeError, {281 destinationOptions: {stdin: 'ignore'},282 message: ['stdin', '\'ignore\''],283});284test('Cannot set "stdin" option to "ignore" to use .duplex()', testNodeStream, {285 sourceOptions: {stdin: 'ignore'},286 message: ['stdin', '\'ignore\''],287 writable: true,288});289test('Cannot set "stdout" option to "ignore" to use .pipe(1)', testPipeError, {290 sourceOptions: {stdout: 'ignore'},291 from: 'fd1',292 message: ['stdout', '\'ignore\''],293});294test('Cannot set "stdout" option to "ignore" to use .duplex(1)', testNodeStream, {295 sourceOptions: {stdout: 'ignore'},296 from: 'fd1',297 message: ['stdout', '\'ignore\''],298});299test('Cannot set "stdout" option to "ignore" to use .iterable(1)', testIterable, {300 sourceOptions: {stdout: 'ignore'},301 from: 'fd1',302 message: ['stdout', '\'ignore\''],303});304test('Cannot set "stdin" option to "ignore" to use .pipe(0)', testPipeError, {305 destinationOptions: {stdin: 'ignore'},306 message: ['stdin', '\'ignore\''],307 to: 'fd0',308});309test('Cannot set "stdin" option to "ignore" to use .duplex(0)', testNodeStream, {310 sourceOptions: {stdin: 'ignore'},311 message: ['stdin', '\'ignore\''],312 to: 'fd0',313});314test('Cannot set "stdout" option to "ignore" to use .pipe("stdout")', testPipeError, {315 sourceOptions: {stdout: 'ignore'},316 from: 'stdout',317 message: ['stdout', '\'ignore\''],318});319test('Cannot set "stdout" option to "ignore" to use .duplex("stdout")', testNodeStream, {320 sourceOptions: {stdout: 'ignore'},321 from: 'stdout',322 message: ['stdout', '\'ignore\''],323});324test('Cannot set "stdout" option to "ignore" to use .iterable("stdout")', testIterable, {325 sourceOptions: {stdout: 'ignore'},326 from: 'stdout',327 message: ['stdout', '\'ignore\''],328});329test('Cannot set "stdin" option to "ignore" to use .pipe("stdin")', testPipeError, {330 destinationOptions: {stdin: 'ignore'},331 message: ['stdin', '\'ignore\''],332 to: 'stdin',333});334test('Cannot set "stdin" option to "ignore" to use .duplex("stdin")', testNodeStream, {335 sourceOptions: {stdin: 'ignore'},336 message: ['stdin', '\'ignore\''],337 to: 'stdin',338});339test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe()', testPipeError, {340 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},341 message: ['stdout', '\'ignore\''],342});343test('Cannot set "stdout" + "stderr" option to "ignore" to use .duplex()', testNodeStream, {344 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},345 message: ['stdout', '\'ignore\''],346});347test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable()', testIterable, {348 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},349 message: ['stdout', '\'ignore\''],350});351test('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});356test('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});361test('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});366test('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});371test('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});376test('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});381test('Cannot set "stdio[1]" option to "ignore" to use .pipe()', testPipeError, {382 sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},383 message: ['stdio[1]', '\'ignore\''],384});385test('Cannot set "stdio[1]" option to "ignore" to use .duplex()', testNodeStream, {386 sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},387 message: ['stdio[1]', '\'ignore\''],388});389test('Cannot set "stdio[1]" option to "ignore" to use .iterable()', testIterable, {390 sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},391 message: ['stdio[1]', '\'ignore\''],392});393test('Cannot set "stdio[0]" option to "ignore" to use .pipe()', testPipeError, {394 destinationOptions: {stdio: ['ignore', 'pipe', 'pipe']},395 message: ['stdio[0]', '\'ignore\''],396});397test('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});402test('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});407test('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});412test('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});417test('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});422test('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});427test('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});432test('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});437test('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});442test('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});447test('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});452test('Cannot set "stderr" option to "ignore" to use .pipe(2)', testPipeError, {453 sourceOptions: {stderr: 'ignore'},454 from: 'fd2',455 message: ['stderr', '\'ignore\''],456});457test('Cannot set "stderr" option to "ignore" to use .duplex(2)', testNodeStream, {458 sourceOptions: {stderr: 'ignore'},459 from: 'fd2',460 message: ['stderr', '\'ignore\''],461});462test('Cannot set "stderr" option to "ignore" to use .iterable(2)', testIterable, {463 sourceOptions: {stderr: 'ignore'},464 from: 'fd2',465 message: ['stderr', '\'ignore\''],466});467test('Cannot set "stderr" option to "ignore" to use .pipe("stderr")', testPipeError, {468 sourceOptions: {stderr: 'ignore'},469 from: 'stderr',470 message: ['stderr', '\'ignore\''],471});472test('Cannot set "stderr" option to "ignore" to use .duplex("stderr")', testNodeStream, {473 sourceOptions: {stderr: 'ignore'},474 from: 'stderr',475 message: ['stderr', '\'ignore\''],476});477test('Cannot set "stderr" option to "ignore" to use .iterable("stderr")', testIterable, {478 sourceOptions: {stderr: 'ignore'},479 from: 'stderr',480 message: ['stderr', '\'ignore\''],481});482test('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});487test('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});492test('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});497test('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});502test('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});507test('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});512test('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});517test('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});522test('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});527test('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});532test('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});537test('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});542test('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});547test('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});552test('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});557test('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});562test('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});567test('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});572test('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});577test('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});582test('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});587test('Cannot set "stdout" option to "inherit" to use .pipe()', testPipeError, {588 sourceOptions: {stdout: 'inherit'},589 message: ['stdout', '\'inherit\''],590});591test('Cannot set "stdout" option to "inherit" to use .duplex()', testNodeStream, {592 sourceOptions: {stdout: 'inherit'},593 message: ['stdout', '\'inherit\''],594});595test('Cannot set "stdout" option to "inherit" to use .iterable()', testIterable, {596 sourceOptions: {stdout: 'inherit'},597 message: ['stdout', '\'inherit\''],598});599test('Cannot set "stdin" option to "inherit" to use .pipe()', testPipeError, {600 destinationOptions: {stdin: 'inherit'},601 message: ['stdin', '\'inherit\''],602});603test('Cannot set "stdin" option to "inherit" to use .duplex()', testNodeStream, {604 sourceOptions: {stdin: 'inherit'},605 message: ['stdin', '\'inherit\''],606 writable: true,607});608test('Cannot set "stdout" option to "ipc" to use .pipe()', testPipeError, {609 sourceOptions: {stdout: 'ipc'},610 message: ['stdout', '\'ipc\''],611});612test('Cannot set "stdout" option to "ipc" to use .duplex()', testNodeStream, {613 sourceOptions: {stdout: 'ipc'},614 message: ['stdout', '\'ipc\''],615});616test('Cannot set "stdout" option to "ipc" to use .iterable()', testIterable, {617 sourceOptions: {stdout: 'ipc'},618 message: ['stdout', '\'ipc\''],619});620test('Cannot set "stdin" option to "ipc" to use .pipe()', testPipeError, {621 destinationOptions: {stdin: 'ipc'},622 message: ['stdin', '\'ipc\''],623});624test('Cannot set "stdin" option to "ipc" to use .duplex()', testNodeStream, {625 sourceOptions: {stdin: 'ipc'},626 message: ['stdin', '\'ipc\''],627 writable: true,628});629test('Cannot set "stdout" option to file descriptors to use .pipe()', testPipeError, {630 sourceOptions: {stdout: 1},631 message: ['stdout', '1'],632});633test('Cannot set "stdout" option to file descriptors to use .duplex()', testNodeStream, {634 sourceOptions: {stdout: 1},635 message: ['stdout', '1'],636});637test('Cannot set "stdout" option to file descriptors to use .iterable()', testIterable, {638 sourceOptions: {stdout: 1},639 message: ['stdout', '1'],640});641test('Cannot set "stdin" option to file descriptors to use .pipe()', testPipeError, {642 destinationOptions: {stdin: 0},643 message: ['stdin', '0'],644});645test('Cannot set "stdin" option to file descriptors to use .duplex()', testNodeStream, {646 sourceOptions: {stdin: 0},647 message: ['stdin', '0'],648 writable: true,649});650test('Cannot set "stdout" option to Node.js streams to use .pipe()', testPipeError, {651 sourceOptions: {stdout: process.stdout},652 message: ['stdout', 'Stream'],653});654test('Cannot set "stdout" option to Node.js streams to use .duplex()', testNodeStream, {655 sourceOptions: {stdout: process.stdout},656 message: ['stdout', 'Stream'],657});658test('Cannot set "stdout" option to Node.js streams to use .iterable()', testIterable, {659 sourceOptions: {stdout: process.stdout},660 message: ['stdout', 'Stream'],661});662test('Cannot set "stdin" option to Node.js streams to use .pipe()', testPipeError, {663 destinationOptions: {stdin: process.stdin},664 message: ['stdin', 'Stream'],665});666test('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});671test('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});676test('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});681test('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});686test('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});691test('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});696697test('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});706707test('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});716717test('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
1import {once} from 'node:events';2import {getDefaultHighWaterMark} from 'node:stream';3import test from 'ava';4import {setFixtureDir} from '../helpers/fixtures-dir.js';5import {6 assertStreamOutput,7 assertIterableChunks,8 assertStreamChunks,9 assertSubprocessOutput,10 getReadableSubprocess,11 getReadWriteSubprocess,12} from '../helpers/convert.js';13import {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';31import {outputObjectGenerator, getOutputGenerator} from '../helpers/generator.js';32import {foobarString, foobarObject} from '../helpers/input.js';33import {multibyteChar, multibyteUint8Array, breakingLength, brokenSymbol} from '../helpers/encoding.js';3435setFixtureDir();3637const foobarObjectChunks = [foobarObject, foobarObject, foobarObject];3839const getSubprocess = (methodName, output, options) => {40 if (methodName !== 'duplex') {41 return getReadableSubprocess(output, options);42 }4344 const subprocess = getReadWriteSubprocess(options);45 subprocess.stdin.end(output);46 return subprocess;47};4849const assertChunks = async (t, streamOrIterable, expectedChunks, methodName) => {50 const assertMethod = methodName === 'iterable' ? assertIterableChunks : assertStreamChunks;51 await assertMethod(t, streamOrIterable, expectedChunks);52};5354// eslint-disable-next-line max-params55const 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});6061 await assertChunks(t, stream, expectedChunks, methodName);62 const expectedOutput = encoding === 'hex'63 ? singleComplexHex64 : stringToUint8Arrays(complexFull, encoding === 'buffer');65 await assertSubprocessOutput(t, subprocess, expectedOutput);66};6768test('.iterable() can use "binary: true"', testText, [singleComplexUint8Array], 'iterable', true, undefined, 'utf8');69test('.iterable() can use "binary: true" + "encoding: utf16le"', testText, [complexFullUtf16Uint8Array], 'iterable', true, undefined, 'utf16le');70test('.iterable() can use "binary: true" + "encoding: "buffer"', testText, [singleComplexUint8Array], 'iterable', true, undefined, 'buffer');71test('.iterable() can use "binary: true" + "encoding: "hex"', testText, [singleComplexUint8Array], 'iterable', true, undefined, 'hex');72test('.iterable() can use "binary: undefined"', testText, complexChunks, 'iterable', undefined, undefined, 'utf8');73test('.iterable() can use "binary: undefined" + "encoding: utf16le"', testText, complexChunks, 'iterable', undefined, undefined, 'utf16le');74test('.iterable() can use "binary: undefined" + "encoding: buffer"', testText, [singleComplexUint8Array], 'iterable', undefined, undefined, 'buffer');75test('.iterable() can use "binary: undefined" + "encoding: hex"', testText, [singleComplexUint8Array], 'iterable', undefined, undefined, 'hex');76test('.iterable() can use "binary: false"', testText, complexChunks, 'iterable', false, undefined, 'utf8');77test('.iterable() can use "binary: false" + "encoding: utf16le"', testText, complexChunks, 'iterable', false, undefined, 'utf16le');78test('.iterable() can use "binary: false" + "encoding: buffer"', testText, [singleComplexUint8Array], 'iterable', false, undefined, 'buffer');79test('.iterable() can use "binary: false" + "encoding: hex"', testText, [singleComplexUint8Array], 'iterable', false, undefined, 'hex');80test('.iterable() can use "binary: false" + "preserveNewlines: true"', testText, complexChunksEnd, 'iterable', false, true, 'utf8');81test('.iterable() can use "binary: false" + "preserveNewlines: false"', testText, complexChunks, 'iterable', false, false, 'utf8');82test('.readable() can use "binary: true"', testText, singleComplexBuffer, 'readable', true, undefined, 'utf8');83test('.readable() can use "binary: true" + "encoding: utf16le"', testText, singleComplexUtf16Buffer, 'readable', true, undefined, 'utf16le');84test('.readable() can use "binary: true" + "encoding: buffer"', testText, singleComplexBuffer, 'readable', true, undefined, 'buffer');85test('.readable() can use "binary: true" + "encoding: hex"', testText, singleComplexBuffer, 'readable', true, undefined, 'hex');86test('.readable() can use "binary: undefined"', testText, singleComplexBuffer, 'readable', undefined, undefined, 'utf8');87test('.readable() can use "binary: undefined" + "encoding: utf16le"', testText, singleComplexUtf16Buffer, 'readable', undefined, undefined, 'utf16le');88test('.readable() can use "binary: undefined" + "encoding: buffer"', testText, singleComplexBuffer, 'readable', undefined, undefined, 'buffer');89test('.readable() can use "binary: undefined" + "encoding: hex"', testText, singleComplexBuffer, 'readable', undefined, undefined, 'hex');90test('.readable() can use "binary: false"', testText, complexChunksEnd, 'readable', false, undefined, 'utf8');91test('.readable() can use "binary: false" + "encoding: utf16le"', testText, complexChunksEnd, 'readable', false, undefined, 'utf16le');92test('.readable() can use "binary: false" + "encoding: buffer"', testText, singleComplexBuffer, 'readable', false, undefined, 'buffer');93test('.readable() can use "binary: false" + "encoding: hex"', testText, singleComplexBuffer, 'readable', false, undefined, 'hex');94test('.readable() can use "binary: false" + "preserveNewlines: true"', testText, complexChunksEnd, 'readable', false, true, 'utf8');95test('.readable() can use "binary: false" + "preserveNewlines: false"', testText, complexChunks, 'readable', false, false, 'utf8');96test('.duplex() can use "binary: true"', testText, singleComplexBuffer, 'duplex', true, undefined, 'utf8');97test('.duplex() can use "binary: true" + "encoding: utf16le"', testText, singleComplexUtf16Buffer, 'duplex', true, undefined, 'utf16le');98test('.duplex() can use "binary: true" + "encoding: buffer"', testText, singleComplexBuffer, 'duplex', true, undefined, 'buffer');99test('.duplex() can use "binary: true" + "encoding: hex"', testText, singleComplexBuffer, 'duplex', true, undefined, 'hex');100test('.duplex() can use "binary: undefined"', testText, singleComplexBuffer, 'duplex', undefined, undefined, 'utf8');101test('.duplex() can use "binary: undefined" + "encoding: utf16le"', testText, singleComplexUtf16Buffer, 'duplex', undefined, undefined, 'utf16le');102test('.duplex() can use "binary: undefined" + "encoding: "buffer"', testText, singleComplexBuffer, 'duplex', undefined, undefined, 'buffer');103test('.duplex() can use "binary: undefined" + "encoding: "hex"', testText, singleComplexBuffer, 'duplex', undefined, undefined, 'hex');104test('.duplex() can use "binary: false"', testText, complexChunksEnd, 'duplex', false, undefined, 'utf8');105test('.duplex() can use "binary: false" + "encoding: utf16le"', testText, complexChunksEnd, 'duplex', false, undefined, 'utf16le');106test('.duplex() can use "binary: false" + "encoding: buffer"', testText, singleComplexBuffer, 'duplex', false, undefined, 'buffer');107test('.duplex() can use "binary: false" + "encoding: hex"', testText, singleComplexBuffer, 'duplex', false, undefined, 'hex');108test('.duplex() can use "binary: false" + "preserveNewlines: true"', testText, complexChunksEnd, 'duplex', false, true, 'utf8');109test('.duplex() can use "binary: false" + "preserveNewlines: false"', testText, complexChunks, 'duplex', false, false, 'utf8');110111const testTextOutput = async (t, expectedOutput, methodName, preserveNewlines) => {112 const subprocess = getSubprocess(methodName, complexFull);113 const stream = subprocess[methodName]({binary: false, preserveNewlines});114115 await assertStreamOutput(t, stream, expectedOutput);116 await assertSubprocessOutput(t, subprocess, complexFull);117};118119test('.readable() "binary: false" keeps output as is', testTextOutput, complexFull, 'readable', undefined);120test('.readable() "binary: false" + "preserveNewlines: true" keeps output as is', testTextOutput, complexFull, 'readable', true);121test('.readable() "binary: false" + "preserveNewlines: false" removes all newlines', testTextOutput, noNewlinesFull, 'readable', false);122test('.duplex() "binary: false" keeps output as is', testTextOutput, complexFull, 'duplex', undefined);123test('.duplex() "binary: false" + "preserveNewlines: true" keeps output as is', testTextOutput, complexFull, 'duplex', true);124test('.duplex() "binary: false" + "preserveNewlines: false" removes all newlines', testTextOutput, noNewlinesFull, 'duplex', false);125126// eslint-disable-next-line max-params127const 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 }132133 t.is(subprocess.stdout.readableEncoding, encoding);134 t.is(subprocess.stdout.readableObjectMode, initialObjectMode);135 t.is(subprocess.stdout.readableHighWaterMark, getDefaultHighWaterMark(initialObjectMode));136137 const stream = subprocess[methodName]({binary, preserveNewlines: true});138139 if (methodName !== 'iterable') {140 t.is(stream.readableEncoding, encoding);141 t.is(stream.readableObjectMode, finalObjectMode);142 t.is(stream.readableHighWaterMark, getDefaultHighWaterMark(finalObjectMode));143 }144145 t.is(subprocess.stdout.readableEncoding, encoding);146 t.is(subprocess.stdout.readableObjectMode, initialObjectMode);147 t.is(subprocess.stdout.readableHighWaterMark, getDefaultHighWaterMark(initialObjectMode));148149 await assertChunks(t, stream, expectedChunks, methodName);150 await subprocess;151};152153test('.iterable() uses Uint8Arrays with "binary: true"', testObjectMode, simpleChunksUint8Array, 'iterable', null, false, false, true);154test('.iterable() uses Uint8Arrays with "binary: true" and .setEncoding("utf8")', testObjectMode, simpleChunksUint8Array, 'iterable', 'utf8', false, false, true);155test('.iterable() uses Uint8Arrays with "binary: true", .setEncoding("utf8") and "encoding: buffer"', testObjectMode, simpleChunksUint8Array, 'iterable', 'utf8', false, false, true, {encoding: 'buffer'});156test('.iterable() uses strings in objectMode with "binary: true" and object transforms', testObjectMode, foobarObjectChunks, 'iterable', null, true, true, true, {stdout: outputObjectGenerator()});157test('.iterable() uses strings in objectMode with "binary: false"', testObjectMode, simpleLines, 'iterable', null, false, true, false);158test('.iterable() uses strings in objectMode with "binary: false" and .setEncoding("utf8")', testObjectMode, simpleLines, 'iterable', 'utf8', false, true, false);159test('.iterable() uses Uint8Arrays in objectMode with "binary: false", .setEncoding("utf8") and "encoding: buffer"', testObjectMode, simpleChunksUint8Array, 'iterable', 'utf8', false, true, false, {encoding: 'buffer'});160test('.iterable() uses strings in objectMode with "binary: false" and object transforms', testObjectMode, foobarObjectChunks, 'iterable', null, true, true, false, {stdout: outputObjectGenerator()});161test('.readable() uses Buffers with "binary: true"', testObjectMode, simpleChunksBuffer, 'readable', null, false, false, true);162test('.readable() uses strings with "binary: true" and .setEncoding("utf8")', testObjectMode, simpleChunks, 'readable', 'utf8', false, false, true);163test('.readable() uses strings with "binary: true", .setEncoding("utf8") and "encoding: buffer"', testObjectMode, simpleChunks, 'readable', 'utf8', false, false, true, {encoding: 'buffer'});164test('.readable() uses strings in objectMode with "binary: true" and object transforms', testObjectMode, foobarObjectChunks, 'readable', null, true, true, true, {stdout: outputObjectGenerator()});165test('.readable() uses strings in objectMode with "binary: false"', testObjectMode, simpleLines, 'readable', null, false, true, false);166test('.readable() uses strings in objectMode with "binary: false" and .setEncoding("utf8")', testObjectMode, simpleLines, 'readable', 'utf8', false, true, false);167test('.readable() uses strings in objectMode with "binary: false", .setEncoding("utf8") and "encoding: buffer"', testObjectMode, simpleChunks, 'readable', 'utf8', false, false, false, {encoding: 'buffer'});168test('.readable() uses strings in objectMode with "binary: false" and object transforms', testObjectMode, foobarObjectChunks, 'readable', null, true, true, false, {stdout: outputObjectGenerator()});169test('.duplex() uses Buffers with "binary: true"', testObjectMode, simpleChunksBuffer, 'duplex', null, false, false, true);170test('.duplex() uses strings with "binary: true" and .setEncoding("utf8")', testObjectMode, simpleChunks, 'duplex', 'utf8', false, false, true);171test('.duplex() uses strings with "binary: true", .setEncoding("utf8") and "encoding: buffer"', testObjectMode, simpleChunks, 'duplex', 'utf8', false, false, true, {encoding: 'buffer'});172test('.duplex() uses strings in objectMode with "binary: true" and object transforms', testObjectMode, foobarObjectChunks, 'duplex', null, true, true, true, {stdout: outputObjectGenerator()});173test('.duplex() uses strings in objectMode with "binary: false"', testObjectMode, simpleLines, 'duplex', null, false, true, false);174test('.duplex() uses strings in objectMode with "binary: false" and .setEncoding("utf8")', testObjectMode, simpleLines, 'duplex', 'utf8', false, true, false);175test('.duplex() uses strings in objectMode with "binary: false", .setEncoding("utf8") and "encoding: buffer"', testObjectMode, simpleChunks, 'duplex', 'utf8', false, false, false, {encoding: 'buffer'});176test('.duplex() uses strings in objectMode with "binary: false" and object transforms', testObjectMode, foobarObjectChunks, 'duplex', null, true, true, false, {stdout: outputObjectGenerator()});177178const 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};184185test('.iterable() "binary: false" does not split lines of strings produced by object transforms', testObjectSplit, 'iterable');186test('.readable() "binary: false" does not split lines of strings produced by object transforms', testObjectSplit, 'readable');187test('.duplex() "binary: false" does not split lines of strings produced by object transforms', testObjectSplit, 'duplex');188189const 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};198199test('.iterable() "binary: false" handles partial multibyte characters', testMultibyteCharacters, 'iterable');200test('.readable() "binary: false" handles partial multibyte characters', testMultibyteCharacters, 'readable');201test('.duplex() "binary: false" handles partial multibyte characters', testMultibyteCharacters, 'duplex');
deleted:test/exit/cancel.js-92 removed
1import {once} from 'node:events';2import test from 'ava';3import {execa, execaSync} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';56setFixtureDir();78test('result.isCanceled is false when abort isn\'t called (success)', async t => {9 const {isCanceled} = await execa('noop.js');10 t.false(isCanceled);11});1213test('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});1718test('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});2223test('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});2930test('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});3738test('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});4546test('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});5556test('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});6263test('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});7172test('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});7980test('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});8687test('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
1import process from 'node:process';2import {setTimeout} from 'node:timers/promises';3import test from 'ava';4import {pEvent} from 'p-event';5import isRunning from 'is-running';6import {execa, execaSync} from '../../index.js';7import {setFixtureDir} from '../helpers/fixtures-dir.js';8import {nestedExecaAsync, nestedWorker} from '../helpers/nested.js';9import {foobarString} from '../helpers/input.js';1011setFixtureDir();1213const isWindows = process.platform === 'win32';1415// When subprocess exits before current process16const spawnAndExit = async (t, execaMethod, cleanup, detached) => {17 const {stdout} = await execaMethod('noop-fd.js', ['1', foobarString], {cleanup, detached});18 t.is(stdout, foobarString);19};2021test('spawnAndExit', spawnAndExit, nestedExecaAsync, false, false);22test('spawnAndExit cleanup', spawnAndExit, nestedExecaAsync, true, false);23test('spawnAndExit detached', spawnAndExit, nestedExecaAsync, false, true);24test('spawnAndExit cleanup detached', spawnAndExit, nestedExecaAsync, true, true);25test('spawnAndExit, worker', spawnAndExit, nestedWorker, false, false);26test('spawnAndExit cleanup, worker', spawnAndExit, nestedWorker, true, false);27test('spawnAndExit detached, worker', spawnAndExit, nestedWorker, false, true);28test('spawnAndExit cleanup detached, worker', spawnAndExit, nestedWorker, true, true);2930// When current process exits before subprocess31const spawnAndKill = async (t, [signal, cleanup, detached, isKilled]) => {32 const subprocess = execa('subprocess.js', [cleanup, detached], {stdio: 'ignore', ipc: true});3334 const pid = await pEvent(subprocess, 'message');35 t.true(Number.isInteger(pid));36 t.true(isRunning(pid));3738 process.kill(subprocess.pid, signal);3940 await t.throwsAsync(subprocess);41 t.false(isRunning(subprocess.pid));4243 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};5455const pollForSubprocessExit = async pid => {56 while (isRunning(pid)) {57 // eslint-disable-next-line no-await-in-loop58 await setTimeout(100);59 }60};6162// 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 handled68test('spawnAndKill SIGTERM', spawnAndKill, ['SIGTERM', false, false, isWindows]);69test('spawnAndKill SIGKILL', spawnAndKill, ['SIGKILL', false, false, isWindows]);70test('spawnAndKill cleanup SIGTERM', spawnAndKill, ['SIGTERM', true, false, true]);71test('spawnAndKill cleanup SIGKILL', spawnAndKill, ['SIGKILL', true, false, isWindows]);72test('spawnAndKill detached SIGTERM', spawnAndKill, ['SIGTERM', false, true, false]);73test('spawnAndKill detached SIGKILL', spawnAndKill, ['SIGKILL', false, true, false]);74test('spawnAndKill cleanup detached SIGTERM', spawnAndKill, ['SIGTERM', true, true, false]);75test('spawnAndKill cleanup detached SIGKILL', spawnAndKill, ['SIGKILL', true, true, false]);7677// See #12878test('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;8182 const subprocess = execa('noop.js');83 const listener = exitListeners.at(-1);8485 await subprocess;86 t.false(exitListeners.includes(listener));87});8889test('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));9495 process.kill(pid, 'SIGKILL');96});9798test('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
1import {once} from 'node:events';2import {setImmediate} from 'node:timers/promises';3import test from 'ava';4import isRunning from 'is-running';5import {execa} from '../../index.js';6import {setFixtureDir} from '../helpers/fixtures-dir.js';78setFixtureDir();910test('.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});2526test('.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});3435test('.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});4344test('.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});5051test('.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});6566test('.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});7677test('.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
1import process from 'node:process';2import {once, defaultMaxListeners} from 'node:events';3import {constants} from 'node:os';4import {setTimeout} from 'node:timers/promises';5import test from 'ava';6import {pEvent} from 'p-event';7import isRunning from 'is-running';8import {execa} from '../../index.js';9import {setFixtureDir} from '../helpers/fixtures-dir.js';10import {assertMaxListeners} from '../helpers/listeners.js';1112setFixtureDir();1314const isWindows = process.platform === 'win32';1516const 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};2526const spawnNoKillableSimple = options => execa('forever.js', {killSignal: 'SIGWINCH', forceKillAfterDelay: 1, ...options});2728test('kill("SIGKILL") should terminate cleanly', async t => {29 const {subprocess} = await spawnNoKillable();3031 subprocess.kill('SIGKILL');3233 const {isTerminated, signal} = await t.throwsAsync(subprocess);34 t.true(isTerminated);35 t.is(signal, 'SIGKILL');36});3738const testInvalidForceKill = async (t, forceKillAfterDelay) => {39 t.throws(() => {40 execa('empty.js', {forceKillAfterDelay});41 }, {instanceOf: TypeError, message: /non-negative integer/});42};4344test('`forceKillAfterDelay` should not be NaN', testInvalidForceKill, Number.NaN);45test('`forceKillAfterDelay` should not be negative', testInvalidForceKill, -1);4647// `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.49if (isWindows) {50 test('Can call `.kill()` with `forceKillAfterDelay` on Windows', async t => {51 const {subprocess} = await spawnNoKillable(1);52 subprocess.kill();5354 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);6162 subprocess.kill(killArgument);6364 await setTimeout(6e3);65 t.true(isRunning(subprocess.pid));66 subprocess.kill('SIGKILL');6768 const {isTerminated, signal} = await t.throwsAsync(subprocess);69 t.true(isTerminated);70 t.is(signal, 'SIGKILL');71 };7273 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});7778 const testForceKill = async (t, forceKillAfterDelay, killArgument, options) => {79 const {subprocess} = await spawnNoKillable(forceKillAfterDelay, options);8081 subprocess.kill(killArgument);8283 const {isTerminated, signal} = await t.throwsAsync(subprocess);84 t.true(isTerminated);85 t.is(signal, 'SIGKILL');86 };8788 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'});9697 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 });107108 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 });115116 test.serial('Can call `.kill()` with `forceKillAfterDelay` many times without triggering the maxListeners warning', async t => {117 const checkMaxListeners = assertMaxListeners(t);118119 const subprocess = spawnNoKillableSimple();120 for (let index = 0; index < defaultMaxListeners + 1; index += 1) {121 subprocess.kill();122 }123124 const {isTerminated, signal} = await t.throwsAsync(subprocess);125 t.true(isTerminated);126 t.is(signal, 'SIGKILL');127128 checkMaxListeners();129 });130131 test('Can call `.kill()` with `forceKillAfterDelay` multiple times', async t => {132 const subprocess = spawnNoKillableSimple();133 subprocess.kill();134 subprocess.kill();135136 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
1import {once} from 'node:events';2import {setImmediate} from 'node:timers/promises';3import test from 'ava';4import {execa} from '../../index.js';5import {setFixtureDir} from '../helpers/fixtures-dir.js';67setFixtureDir();89test('Can call `.kill()` multiple times', async t => {10 const subprocess = execa('forever.js');11 subprocess.kill();12 subprocess.kill();1314 const {isTerminated, signal} = await t.throwsAsync(subprocess);15 t.true(isTerminated);16 t.is(signal, 'SIGTERM');17});1819test('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});2425const 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};3536test('Cannot call .kill(null)', testInvalidKillArgument, null);37test('Cannot call .kill(0n)', testInvalidKillArgument, 0n);38test('Cannot call .kill(true)', testInvalidKillArgument, true);39test('Cannot call .kill(errorObject)', testInvalidKillArgument, {name: '', message: '', stack: ''});40test('Cannot call .kill(errorArray)', testInvalidKillArgument, [new Error('test')]);41test('Cannot call .kill(undefined, true)', testInvalidKillArgument, undefined, true);42test('Cannot call .kill("SIGTERM", true)', testInvalidKillArgument, 'SIGTERM', true);43test('Cannot call .kill(true, error)', testInvalidKillArgument, true, new Error('test'));4445test('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});5657test('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});6970test('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});8485test('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
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDir, FIXTURES_DIR} from '../helpers/fixtures-dir.js';45setFixtureDir();67test('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});1617test('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});2829test('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});3334test('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});4041const INVALID_TIMEOUT_REGEXP = /`timeout` option to be a non-negative integer/;4243const testTimeoutValidation = (t, timeout, execaMethod) => {44 t.throws(() => {45 execaMethod('empty.js', {timeout});46 }, {message: INVALID_TIMEOUT_REGEXP});47};4849test('timeout must not be negative', testTimeoutValidation, -1, execa);50test('timeout must be an integer', testTimeoutValidation, false, execa);51test('timeout must not be negative - sync', testTimeoutValidation, -1, execaSync);52test('timeout must be an integer - sync', testTimeoutValidation, false, execaSync);5354test('timedOut is false if timeout is undefined', async t => {55 const {timedOut} = await execa('noop.js');56 t.false(timedOut);57});5859test('timedOut is false if timeout is 0', async t => {60 const {timedOut} = await execa('noop.js', {timeout: 0});61 t.false(timedOut);62});6364test('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});6869test('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
1import {Writable} from 'node:stream';2import test from 'ava';3import {execa, execaSync} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';5import {runExeca, runExecaSync, runScript, runScriptSync} from '../helpers/run.js';6import {foobarUint8Array, foobarBuffer, foobarArrayBuffer, foobarUint16Array, foobarDataView} from '../helpers/input.js';78setFixtureDir();910const testInput = async (t, input, execaMethod) => {11 const {stdout} = await execaMethod('stdin.js', {input});12 t.is(stdout, 'foobar');13};1415test('input option can be a String', testInput, 'foobar', runExeca);16test('input option can be a Uint8Array', testInput, foobarUint8Array, runExeca);17test('input option can be a String - sync', testInput, 'foobar', runExecaSync);18test('input option can be a Uint8Array - sync', testInput, foobarUint8Array, runExecaSync);19test('input option can be used with $', testInput, 'foobar', runScript);20test('input option can be used with $.sync', testInput, 'foobar', runScriptSync);2122const testInvalidInput = async (t, input, execaMethod) => {23 t.throws(() => {24 execaMethod('empty.js', {input});25 }, {message: /a string, a Uint8Array/});26};2728test('input option cannot be a Buffer', testInvalidInput, foobarBuffer, execa);29test('input option cannot be an ArrayBuffer', testInvalidInput, foobarArrayBuffer, execa);30test('input option cannot be a DataView', testInvalidInput, foobarDataView, execa);31test('input option cannot be a Uint16Array', testInvalidInput, foobarUint16Array, execa);32test('input option cannot be 0', testInvalidInput, 0, execa);33test('input option cannot be false', testInvalidInput, false, execa);34test('input option cannot be null', testInvalidInput, null, execa);35test('input option cannot be a non-Readable stream', testInvalidInput, new Writable(), execa);36test('input option cannot be a Buffer - sync', testInvalidInput, foobarBuffer, execaSync);37test('input option cannot be an ArrayBuffer - sync', testInvalidInput, foobarArrayBuffer, execaSync);38test('input option cannot be a DataView - sync', testInvalidInput, foobarDataView, execaSync);39test('input option cannot be a Uint16Array - sync', testInvalidInput, foobarUint16Array, execaSync);40test('input option cannot be 0 - sync', testInvalidInput, 0, execaSync);41test('input option cannot be false - sync', testInvalidInput, false, execaSync);42test('input option cannot be null - sync', testInvalidInput, null, execaSync);43test('input option cannot be a non-Readable stream - sync', testInvalidInput, new Writable(), execaSync);
added:test/io/input-sync.js+18 added
1import test from 'ava';2import {execaSync} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {getStdio} from '../helpers/stdio.js';56setFixtureDir();78const getFd3InputMessage = type => `not \`stdio[3]\`, can be ${type}`;910const testFd3InputSync = (t, stdioOption, expectedMessage) => {11 const {message} = t.throws(() => {12 execaSync('empty.js', getStdio(3, stdioOption));13 });14 t.true(message.includes(expectedMessage));15};1617test('Cannot use Uint8Array with stdio[*], sync', testFd3InputSync, new Uint8Array(), getFd3InputMessage('a Uint8Array'));18test('Cannot use iterable with stdio[*], sync', testFd3InputSync, [[]], getFd3InputMessage('an iterable'));
added:test/io/iterate.js+201 added
1import {once} from 'node:events';2import {getDefaultHighWaterMark} from 'node:stream';3import test from 'ava';4import {setFixtureDir} from '../helpers/fixtures-dir.js';5import {6 assertStreamOutput,7 assertIterableChunks,8 assertStreamChunks,9 assertSubprocessOutput,10 getReadableSubprocess,11 getReadWriteSubprocess,12} from '../helpers/convert.js';13import {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';31import {outputObjectGenerator, getOutputGenerator} from '../helpers/generator.js';32import {foobarString, foobarObject} from '../helpers/input.js';33import {multibyteChar, multibyteUint8Array, breakingLength, brokenSymbol} from '../helpers/encoding.js';3435setFixtureDir();3637const foobarObjectChunks = [foobarObject, foobarObject, foobarObject];3839const getSubprocess = (methodName, output, options) => {40 if (methodName !== 'duplex') {41 return getReadableSubprocess(output, options);42 }4344 const subprocess = getReadWriteSubprocess(options);45 subprocess.stdin.end(output);46 return subprocess;47};4849const assertChunks = async (t, streamOrIterable, expectedChunks, methodName) => {50 const assertMethod = methodName === 'iterable' ? assertIterableChunks : assertStreamChunks;51 await assertMethod(t, streamOrIterable, expectedChunks);52};5354// eslint-disable-next-line max-params55const 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});6061 await assertChunks(t, stream, expectedChunks, methodName);62 const expectedOutput = encoding === 'hex'63 ? singleComplexHex64 : stringToUint8Arrays(complexFull, encoding === 'buffer');65 await assertSubprocessOutput(t, subprocess, expectedOutput);66};6768test('.iterable() can use "binary: true"', testText, [singleComplexUint8Array], 'iterable', true, undefined, 'utf8');69test('.iterable() can use "binary: true" + "encoding: utf16le"', testText, [complexFullUtf16Uint8Array], 'iterable', true, undefined, 'utf16le');70test('.iterable() can use "binary: true" + "encoding: "buffer"', testText, [singleComplexUint8Array], 'iterable', true, undefined, 'buffer');71test('.iterable() can use "binary: true" + "encoding: "hex"', testText, [singleComplexUint8Array], 'iterable', true, undefined, 'hex');72test('.iterable() can use "binary: undefined"', testText, complexChunks, 'iterable', undefined, undefined, 'utf8');73test('.iterable() can use "binary: undefined" + "encoding: utf16le"', testText, complexChunks, 'iterable', undefined, undefined, 'utf16le');74test('.iterable() can use "binary: undefined" + "encoding: buffer"', testText, [singleComplexUint8Array], 'iterable', undefined, undefined, 'buffer');75test('.iterable() can use "binary: undefined" + "encoding: hex"', testText, [singleComplexUint8Array], 'iterable', undefined, undefined, 'hex');76test('.iterable() can use "binary: false"', testText, complexChunks, 'iterable', false, undefined, 'utf8');77test('.iterable() can use "binary: false" + "encoding: utf16le"', testText, complexChunks, 'iterable', false, undefined, 'utf16le');78test('.iterable() can use "binary: false" + "encoding: buffer"', testText, [singleComplexUint8Array], 'iterable', false, undefined, 'buffer');79test('.iterable() can use "binary: false" + "encoding: hex"', testText, [singleComplexUint8Array], 'iterable', false, undefined, 'hex');80test('.iterable() can use "binary: false" + "preserveNewlines: true"', testText, complexChunksEnd, 'iterable', false, true, 'utf8');81test('.iterable() can use "binary: false" + "preserveNewlines: false"', testText, complexChunks, 'iterable', false, false, 'utf8');82test('.readable() can use "binary: true"', testText, singleComplexBuffer, 'readable', true, undefined, 'utf8');83test('.readable() can use "binary: true" + "encoding: utf16le"', testText, singleComplexUtf16Buffer, 'readable', true, undefined, 'utf16le');84test('.readable() can use "binary: true" + "encoding: buffer"', testText, singleComplexBuffer, 'readable', true, undefined, 'buffer');85test('.readable() can use "binary: true" + "encoding: hex"', testText, singleComplexBuffer, 'readable', true, undefined, 'hex');86test('.readable() can use "binary: undefined"', testText, singleComplexBuffer, 'readable', undefined, undefined, 'utf8');87test('.readable() can use "binary: undefined" + "encoding: utf16le"', testText, singleComplexUtf16Buffer, 'readable', undefined, undefined, 'utf16le');88test('.readable() can use "binary: undefined" + "encoding: buffer"', testText, singleComplexBuffer, 'readable', undefined, undefined, 'buffer');89test('.readable() can use "binary: undefined" + "encoding: hex"', testText, singleComplexBuffer, 'readable', undefined, undefined, 'hex');90test('.readable() can use "binary: false"', testText, complexChunksEnd, 'readable', false, undefined, 'utf8');91test('.readable() can use "binary: false" + "encoding: utf16le"', testText, complexChunksEnd, 'readable', false, undefined, 'utf16le');92test('.readable() can use "binary: false" + "encoding: buffer"', testText, singleComplexBuffer, 'readable', false, undefined, 'buffer');93test('.readable() can use "binary: false" + "encoding: hex"', testText, singleComplexBuffer, 'readable', false, undefined, 'hex');94test('.readable() can use "binary: false" + "preserveNewlines: true"', testText, complexChunksEnd, 'readable', false, true, 'utf8');95test('.readable() can use "binary: false" + "preserveNewlines: false"', testText, complexChunks, 'readable', false, false, 'utf8');96test('.duplex() can use "binary: true"', testText, singleComplexBuffer, 'duplex', true, undefined, 'utf8');97test('.duplex() can use "binary: true" + "encoding: utf16le"', testText, singleComplexUtf16Buffer, 'duplex', true, undefined, 'utf16le');98test('.duplex() can use "binary: true" + "encoding: buffer"', testText, singleComplexBuffer, 'duplex', true, undefined, 'buffer');99test('.duplex() can use "binary: true" + "encoding: hex"', testText, singleComplexBuffer, 'duplex', true, undefined, 'hex');100test('.duplex() can use "binary: undefined"', testText, singleComplexBuffer, 'duplex', undefined, undefined, 'utf8');101test('.duplex() can use "binary: undefined" + "encoding: utf16le"', testText, singleComplexUtf16Buffer, 'duplex', undefined, undefined, 'utf16le');102test('.duplex() can use "binary: undefined" + "encoding: "buffer"', testText, singleComplexBuffer, 'duplex', undefined, undefined, 'buffer');103test('.duplex() can use "binary: undefined" + "encoding: "hex"', testText, singleComplexBuffer, 'duplex', undefined, undefined, 'hex');104test('.duplex() can use "binary: false"', testText, complexChunksEnd, 'duplex', false, undefined, 'utf8');105test('.duplex() can use "binary: false" + "encoding: utf16le"', testText, complexChunksEnd, 'duplex', false, undefined, 'utf16le');106test('.duplex() can use "binary: false" + "encoding: buffer"', testText, singleComplexBuffer, 'duplex', false, undefined, 'buffer');107test('.duplex() can use "binary: false" + "encoding: hex"', testText, singleComplexBuffer, 'duplex', false, undefined, 'hex');108test('.duplex() can use "binary: false" + "preserveNewlines: true"', testText, complexChunksEnd, 'duplex', false, true, 'utf8');109test('.duplex() can use "binary: false" + "preserveNewlines: false"', testText, complexChunks, 'duplex', false, false, 'utf8');110111const testTextOutput = async (t, expectedOutput, methodName, preserveNewlines) => {112 const subprocess = getSubprocess(methodName, complexFull);113 const stream = subprocess[methodName]({binary: false, preserveNewlines});114115 await assertStreamOutput(t, stream, expectedOutput);116 await assertSubprocessOutput(t, subprocess, complexFull);117};118119test('.readable() "binary: false" keeps output as is', testTextOutput, complexFull, 'readable', undefined);120test('.readable() "binary: false" + "preserveNewlines: true" keeps output as is', testTextOutput, complexFull, 'readable', true);121test('.readable() "binary: false" + "preserveNewlines: false" removes all newlines', testTextOutput, noNewlinesFull, 'readable', false);122test('.duplex() "binary: false" keeps output as is', testTextOutput, complexFull, 'duplex', undefined);123test('.duplex() "binary: false" + "preserveNewlines: true" keeps output as is', testTextOutput, complexFull, 'duplex', true);124test('.duplex() "binary: false" + "preserveNewlines: false" removes all newlines', testTextOutput, noNewlinesFull, 'duplex', false);125126// eslint-disable-next-line max-params127const 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 }132133 t.is(subprocess.stdout.readableEncoding, encoding);134 t.is(subprocess.stdout.readableObjectMode, initialObjectMode);135 t.is(subprocess.stdout.readableHighWaterMark, getDefaultHighWaterMark(initialObjectMode));136137 const stream = subprocess[methodName]({binary, preserveNewlines: true});138139 if (methodName !== 'iterable') {140 t.is(stream.readableEncoding, encoding);141 t.is(stream.readableObjectMode, finalObjectMode);142 t.is(stream.readableHighWaterMark, getDefaultHighWaterMark(finalObjectMode));143 }144145 t.is(subprocess.stdout.readableEncoding, encoding);146 t.is(subprocess.stdout.readableObjectMode, initialObjectMode);147 t.is(subprocess.stdout.readableHighWaterMark, getDefaultHighWaterMark(initialObjectMode));148149 await assertChunks(t, stream, expectedChunks, methodName);150 await subprocess;151};152153test('.iterable() uses Uint8Arrays with "binary: true"', testObjectMode, simpleChunksUint8Array, 'iterable', null, false, false, true);154test('.iterable() uses Uint8Arrays with "binary: true" and .setEncoding("utf8")', testObjectMode, simpleChunksUint8Array, 'iterable', 'utf8', false, false, true);155test('.iterable() uses Uint8Arrays with "binary: true", .setEncoding("utf8") and "encoding: buffer"', testObjectMode, simpleChunksUint8Array, 'iterable', 'utf8', false, false, true, {encoding: 'buffer'});156test('.iterable() uses strings in objectMode with "binary: true" and object transforms', testObjectMode, foobarObjectChunks, 'iterable', null, true, true, true, {stdout: outputObjectGenerator()});157test('.iterable() uses strings in objectMode with "binary: false"', testObjectMode, simpleLines, 'iterable', null, false, true, false);158test('.iterable() uses strings in objectMode with "binary: false" and .setEncoding("utf8")', testObjectMode, simpleLines, 'iterable', 'utf8', false, true, false);159test('.iterable() uses Uint8Arrays in objectMode with "binary: false", .setEncoding("utf8") and "encoding: buffer"', testObjectMode, simpleChunksUint8Array, 'iterable', 'utf8', false, true, false, {encoding: 'buffer'});160test('.iterable() uses strings in objectMode with "binary: false" and object transforms', testObjectMode, foobarObjectChunks, 'iterable', null, true, true, false, {stdout: outputObjectGenerator()});161test('.readable() uses Buffers with "binary: true"', testObjectMode, simpleChunksBuffer, 'readable', null, false, false, true);162test('.readable() uses strings with "binary: true" and .setEncoding("utf8")', testObjectMode, simpleChunks, 'readable', 'utf8', false, false, true);163test('.readable() uses strings with "binary: true", .setEncoding("utf8") and "encoding: buffer"', testObjectMode, simpleChunks, 'readable', 'utf8', false, false, true, {encoding: 'buffer'});164test('.readable() uses strings in objectMode with "binary: true" and object transforms', testObjectMode, foobarObjectChunks, 'readable', null, true, true, true, {stdout: outputObjectGenerator()});165test('.readable() uses strings in objectMode with "binary: false"', testObjectMode, simpleLines, 'readable', null, false, true, false);166test('.readable() uses strings in objectMode with "binary: false" and .setEncoding("utf8")', testObjectMode, simpleLines, 'readable', 'utf8', false, true, false);167test('.readable() uses strings in objectMode with "binary: false", .setEncoding("utf8") and "encoding: buffer"', testObjectMode, simpleChunks, 'readable', 'utf8', false, false, false, {encoding: 'buffer'});168test('.readable() uses strings in objectMode with "binary: false" and object transforms', testObjectMode, foobarObjectChunks, 'readable', null, true, true, false, {stdout: outputObjectGenerator()});169test('.duplex() uses Buffers with "binary: true"', testObjectMode, simpleChunksBuffer, 'duplex', null, false, false, true);170test('.duplex() uses strings with "binary: true" and .setEncoding("utf8")', testObjectMode, simpleChunks, 'duplex', 'utf8', false, false, true);171test('.duplex() uses strings with "binary: true", .setEncoding("utf8") and "encoding: buffer"', testObjectMode, simpleChunks, 'duplex', 'utf8', false, false, true, {encoding: 'buffer'});172test('.duplex() uses strings in objectMode with "binary: true" and object transforms', testObjectMode, foobarObjectChunks, 'duplex', null, true, true, true, {stdout: outputObjectGenerator()});173test('.duplex() uses strings in objectMode with "binary: false"', testObjectMode, simpleLines, 'duplex', null, false, true, false);174test('.duplex() uses strings in objectMode with "binary: false" and .setEncoding("utf8")', testObjectMode, simpleLines, 'duplex', 'utf8', false, true, false);175test('.duplex() uses strings in objectMode with "binary: false", .setEncoding("utf8") and "encoding: buffer"', testObjectMode, simpleChunks, 'duplex', 'utf8', false, false, false, {encoding: 'buffer'});176test('.duplex() uses strings in objectMode with "binary: false" and object transforms', testObjectMode, foobarObjectChunks, 'duplex', null, true, true, false, {stdout: outputObjectGenerator()});177178const 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};184185test('.iterable() "binary: false" does not split lines of strings produced by object transforms', testObjectSplit, 'iterable');186test('.readable() "binary: false" does not split lines of strings produced by object transforms', testObjectSplit, 'readable');187test('.duplex() "binary: false" does not split lines of strings produced by object transforms', testObjectSplit, 'duplex');188189const 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};198199test('.iterable() "binary: false" handles partial multibyte characters', testMultibyteCharacters, 'iterable');200test('.readable() "binary: false" handles partial multibyte characters', testMultibyteCharacters, 'readable');201test('.duplex() "binary: false" handles partial multibyte characters', testMultibyteCharacters, 'duplex');
added:test/io/max-buffer.js+265 added
1import {Buffer} from 'node:buffer';2import test from 'ava';3import getStream from 'get-stream';4import {execa, execaSync} from '../../index.js';5import {setFixtureDir} from '../helpers/fixtures-dir.js';6import {fullStdio} from '../helpers/stdio.js';7import {getEarlyErrorSubprocess, getEarlyErrorSubprocessSync} from '../helpers/early-error.js';8import {maxBuffer, assertErrorMessage} from '../helpers/max-buffer.js';910setFixtureDir();1112const maxBufferMessage = {message: /maxBuffer exceeded/};13const maxBufferCodeSync = {code: 'ENOBUFS'};1415const 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};2526const getMaxBufferSubprocess = (execaMethod, fdNumber, {length = maxBuffer, ...options} = {}) =>27 execaMethod('max-buffer.js', [`${fdNumber}`, `${length + 1}`], {...fullStdio, maxBuffer, ...options});2829const getExpectedOutput = (length = maxBuffer) => '.'.repeat(length);3031const testMaxBufferSuccess = async (t, execaMethod, fdNumber, all) => {32 const {isMaxBuffer} = await getMaxBufferSubprocess(execaMethod, fdNumber, {all, length: maxBuffer - 1});33 t.false(isMaxBuffer);34};3536test('maxBuffer does not affect stdout if too high', testMaxBufferSuccess, execa, 1, false);37test('maxBuffer does not affect stderr if too high', testMaxBufferSuccess, execa, 2, false);38test('maxBuffer does not affect stdio[*] if too high', testMaxBufferSuccess, execa, 3, false);39test('maxBuffer does not affect all if too high', testMaxBufferSuccess, execa, 1, true);40test('maxBuffer does not affect stdout if too high, sync', testMaxBufferSuccess, execaSync, 1, false);41test('maxBuffer does not affect stderr if too high, sync', testMaxBufferSuccess, execaSync, 2, false);42test('maxBuffer does not affect stdio[*] if too high, sync', testMaxBufferSuccess, execaSync, 3, false);43test('maxBuffer does not affect all if too high, sync', testMaxBufferSuccess, execaSync, 1, true);4445const 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};5657test('maxBuffer terminates stream gracefully, more writes', testGracefulExit, 'noop-repeat.js', 1);58test('maxBuffer terminates stream gracefully, no more writes', testGracefulExit, 'noop-fd.js', 0);5960const 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};7071test('maxBuffer terminate stream with killSignal, more writes, sync', testGracefulExitSync, 'noop-repeat.js');72test('maxBuffer terminate stream with killSignal, no more writes, sync', testGracefulExitSync, 'noop-fd.js');7374const 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};8081test('maxBuffer truncates stdout', testMaxBufferLimit, execa, 1, false);82test('maxBuffer truncates stderr', testMaxBufferLimit, execa, 2, false);83test('maxBuffer truncates stdio[*]', testMaxBufferLimit, execa, 3, false);84test('maxBuffer truncates all', testMaxBufferLimit, execa, 1, true);85test('maxBuffer truncates stdout, sync', testMaxBufferLimit, execaSync, 1, false);86test('maxBuffer truncates stderr, sync', testMaxBufferLimit, execaSync, 2, false);87test('maxBuffer truncates stdio[*], sync', testMaxBufferLimit, execaSync, 3, false);88test('maxBuffer truncates all, sync', testMaxBufferLimit, execaSync, 1, true);8990const MAX_BUFFER_DEFAULT = 1e8;9192const 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};9899test('maxBuffer has a default value with stdout', testMaxBufferDefault, execa, 1, undefined);100test('maxBuffer has a default value with stderr', testMaxBufferDefault, execa, 2, undefined);101test('maxBuffer has a default value with stdio[*]', testMaxBufferDefault, execa, 3, undefined);102test('maxBuffer has a default value with stdout, sync', testMaxBufferDefault, execaSync, 1, undefined);103test('maxBuffer has a default value with stderr, sync', testMaxBufferDefault, execaSync, 2, undefined);104test('maxBuffer has a default value with stdio[*], sync', testMaxBufferDefault, execaSync, 3, undefined);105test('maxBuffer has a default value with stdout with fd-specific options', testMaxBufferDefault, execa, 1, {stderr: 1e9});106test('maxBuffer has a default value with stderr with fd-specific options', testMaxBufferDefault, execa, 2, {stdout: 1e9});107test('maxBuffer has a default value with stdio[*] with fd-specific options', testMaxBufferDefault, execa, 3, {stdout: 1e9});108test('maxBuffer has a default value with stdout with empty fd-specific options', testMaxBufferDefault, execa, 1, {});109110const 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};116117test('maxBuffer truncates file descriptors with fd-specific options, stdout', testFdSpecific, 1, 'stdout', execa);118test('maxBuffer truncates file descriptors with fd-specific options, fd1', testFdSpecific, 1, 'fd1', execa);119test('maxBuffer truncates file descriptors with fd-specific options, stderr', testFdSpecific, 2, 'stderr', execa);120test('maxBuffer truncates file descriptors with fd-specific options, fd2', testFdSpecific, 2, 'fd2', execa);121test('maxBuffer truncates file descriptors with fd-specific options, stdout, all', testFdSpecific, 1, 'all', execa);122test('maxBuffer truncates file descriptors with fd-specific options, stderr, all', testFdSpecific, 2, 'all', execa);123test('maxBuffer truncates file descriptors with fd-specific options, fd3', testFdSpecific, 3, 'fd3', execa);124test('maxBuffer.stdout is used for stdout with fd-specific options, stdout, sync', testFdSpecific, 1, 'stdout', execaSync);125126test('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});130131test('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});137138const 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 }151152 t.is(stdout, '\n'.repeat(maxBufferStdout));153 t.is(stderr, '\n'.repeat(maxBufferStderr));154 t.is(all, '\n'.repeat(maxBufferStdout + maxBufferStderr));155};156157test('maxBuffer.stdout can differ from maxBuffer.stderr, combined with all, below threshold', testAll, false);158test('maxBuffer.stdout can differ from maxBuffer.stderr, combined with all, above threshold', testAll, true);159160const 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};166167test('maxBuffer.stdin is invalid', testInvalidFd, 'stdin', execa);168test('maxBuffer.fd0 is invalid', testInvalidFd, 'fd0', execa);169test('maxBuffer.other is invalid', testInvalidFd, 'other', execa);170test('maxBuffer.fd10 is invalid', testInvalidFd, 'fd10', execa);171test('maxBuffer.stdin is invalid, sync', testInvalidFd, 'stdin', execaSync);172test('maxBuffer.fd0 is invalid, sync', testInvalidFd, 'fd0', execaSync);173test('maxBuffer.other is invalid, sync', testInvalidFd, 'other', execaSync);174test('maxBuffer.fd10 is invalid, sync', testInvalidFd, 'fd10', execaSync);175176const 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};183184test('maxBuffer works with encoding buffer and stdout', testMaxBufferEncoding, execa, 1);185test('maxBuffer works with encoding buffer and stderr', testMaxBufferEncoding, execa, 2);186test('maxBuffer works with encoding buffer and stdio[*]', testMaxBufferEncoding, execa, 3);187test('maxBuffer works with encoding buffer and stdout, sync', testMaxBufferEncoding, execaSync, 1);188test('maxBuffer works with encoding buffer and stderr, sync', testMaxBufferEncoding, execaSync, 2);189test('maxBuffer works with encoding buffer and stdio[*], sync', testMaxBufferEncoding, execaSync, 3);190191const 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};197198test('maxBuffer works with other encodings and stdout', testMaxBufferHex, 1);199test('maxBuffer works with other encodings and stderr', testMaxBufferHex, 2);200test('maxBuffer works with other encodings and stdio[*]', testMaxBufferHex, 3);201202const 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};208209test('maxBuffer ignores other encodings and stdout, sync', testMaxBufferHexSync, 1);210test('maxBuffer ignores other encodings and stderr, sync', testMaxBufferHexSync, 2);211test('maxBuffer ignores other encodings and stdio[*], sync', testMaxBufferHexSync, 3);212213const 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};223224test('do not buffer stdout when `buffer` set to `false`', testNoMaxBuffer, 1, false);225test('do not buffer stdout when `buffer` set to `false`, fd-specific', testNoMaxBuffer, 1, {stdout: false});226test('do not buffer stderr when `buffer` set to `false`', testNoMaxBuffer, 2, false);227test('do not buffer stderr when `buffer` set to `false`, fd-specific', testNoMaxBuffer, 2, {stderr: false});228test('do not buffer stdio[*] when `buffer` set to `false`', testNoMaxBuffer, 3, false);229test('do not buffer stdio[*] when `buffer` set to `false`, fd-specific', testNoMaxBuffer, 3, {fd3: false});230231const testNoMaxBufferSync = (t, fdNumber, buffer) => {232 const {isMaxBuffer, stdio} = getMaxBufferSubprocess(execaSync, fdNumber, {buffer});233 t.false(isMaxBuffer);234 t.is(stdio[fdNumber], undefined);235};236237// @todo: add tests for fd3 once the following Node.js bug is fixed.238// https://github.com/nodejs/node/issues/52422239test('do not buffer stdout when `buffer` set to `false`, sync', testNoMaxBufferSync, 1, false);240test('do not buffer stdout when `buffer` set to `false`, fd-specific, sync', testNoMaxBufferSync, 1, {stdout: false});241test('do not buffer stderr when `buffer` set to `false`, sync', testNoMaxBufferSync, 2, false);242test('do not buffer stderr when `buffer` set to `false`, fd-specific, sync', testNoMaxBufferSync, 2, {stderr: false});243244const 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};253254test('abort stream when hitting maxBuffer with stdout', testMaxBufferAbort, 1);255test('abort stream when hitting maxBuffer with stderr', testMaxBufferAbort, 2);256test('abort stream when hitting maxBuffer with stdio[*]', testMaxBufferAbort, 3);257258const testEarlyError = async (t, getSubprocess) => {259 const {failed, isMaxBuffer} = await getSubprocess({reject: false, maxBuffer: 1});260 t.true(failed);261 t.false(isMaxBuffer);262};263264test('error.isMaxBuffer is false on early errors', testEarlyError, getEarlyErrorSubprocess);265test('error.isMaxBuffer is false on early errors, sync', testEarlyError, getEarlyErrorSubprocessSync);
added:test/io/output-async.js+84 added
1import {once, defaultMaxListeners} from 'node:events';2import process from 'node:process';3import {setImmediate} from 'node:timers/promises';4import test from 'ava';5import {execa} from '../../index.js';6import {STANDARD_STREAMS} from '../helpers/stdio.js';7import {foobarString} from '../helpers/input.js';8import {setFixtureDir} from '../helpers/fixtures-dir.js';9import {assertMaxListeners} from '../helpers/listeners.js';1011setFixtureDir();1213const getStandardStreamListeners = stream => Object.fromEntries(stream.eventNames().map(eventName => [eventName, stream.listeners(eventName)]));14const getStandardStreamsListeners = () => STANDARD_STREAMS.map(stream => getStandardStreamListeners(stream));1516const 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});2122const onStdinRemoveListener = () => once(process.stdin, 'removeListener');2324const 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 }3233 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};3839test.serial('process.std* listeners are cleaned up on success with a single input', testListenersCleanup, false);40test.serial('process.std* listeners are cleaned up on success with multiple inputs', testListenersCleanup, true);4142const subprocessesCount = 100;4344test.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});5051const testMaxListeners = async (t, isMultiple, maxListenersCount) => {52 const checkMaxListeners = assertMaxListeners(t);5354 for (const standardStream of STANDARD_STREAMS) {55 standardStream.setMaxListeners(maxListenersCount);56 }5758 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();6768 for (const standardStream of STANDARD_STREAMS) {69 t.is(standardStream.getMaxListeners(), maxListenersCount);70 standardStream.setMaxListeners(defaultMaxListeners);71 }72 }73};7475test.serial('No warning with maxListeners 1 and ["pipe", "inherit"]', testMaxListeners, false, 1);76test.serial('No warning with maxListeners default and ["pipe", "inherit"]', testMaxListeners, false, defaultMaxListeners);77test.serial('No warning with maxListeners 100 and ["pipe", "inherit"]', testMaxListeners, false, 100);78test.serial('No warning with maxListeners Infinity and ["pipe", "inherit"]', testMaxListeners, false, Number.POSITIVE_INFINITY);79test.serial('No warning with maxListeners 0 and ["pipe", "inherit"]', testMaxListeners, false, 0);80test.serial('No warning with maxListeners 1 and ["pipe", "inherit"], multiple inputs', testMaxListeners, true, 1);81test.serial('No warning with maxListeners default and ["pipe", "inherit"], multiple inputs', testMaxListeners, true, defaultMaxListeners);82test.serial('No warning with maxListeners 100 and ["pipe", "inherit"], multiple inputs', testMaxListeners, true, 100);83test.serial('No warning with maxListeners Infinity and ["pipe", "inherit"], multiple inputs', testMaxListeners, true, Number.POSITIVE_INFINITY);84test.serial('No warning with maxListeners 0 and ["pipe", "inherit"], multiple inputs', testMaxListeners, true, 0);
added:test/io/output-sync.js+33 added
1import test from 'ava';2import {execaSync} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {throwingGenerator} from '../helpers/generator.js';5import {foobarString} from '../helpers/input.js';67setFixtureDir();89test('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});1617test('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});2526test('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
1import test from 'ava';2import {execa} from '../../index.js';3import {getStdio, STANDARD_STREAMS} from '../helpers/stdio.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';56setFixtureDir();78const 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};1314test('Does not destroy process.stdin on subprocess errors', testDestroyStandard, 0);15test('Does not destroy process.stdout on subprocess errors', testDestroyStandard, 1);16test('Does not destroy process.stderr on subprocess errors', testDestroyStandard, 2);1718const 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};2223test('Does not destroy process.stdin on subprocess early errors', testDestroyStandardSpawn, 0);24test('Does not destroy process.stdout on subprocess early errors', testDestroyStandardSpawn, 1);25test('Does not destroy process.stderr on subprocess early errors', testDestroyStandardSpawn, 2);2627const 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};3536test('Does not destroy process.stdin on stream subprocess errors', testDestroyStandardStream, 0);37test('Does not destroy process.stdout on stream subprocess errors', testDestroyStandardStream, 1);38test('Does not destroy process.stderr on stream subprocess errors', testDestroyStandardStream, 2);
added:test/io/strip-newline.js+56 added
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {fullStdio} from '../helpers/stdio.js';5import {noopGenerator} from '../helpers/generator.js';6import {foobarString} from '../helpers/input.js';78setFixtureDir();910// eslint-disable-next-line max-params11const 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};1516test('stripFinalNewline: default with stdout', testStripFinalNewline, 1, undefined, true, execa);17test('stripFinalNewline: true with stdout', testStripFinalNewline, 1, true, true, execa);18test('stripFinalNewline: false with stdout', testStripFinalNewline, 1, false, false, execa);19test('stripFinalNewline: default with stderr', testStripFinalNewline, 2, undefined, true, execa);20test('stripFinalNewline: true with stderr', testStripFinalNewline, 2, true, true, execa);21test('stripFinalNewline: false with stderr', testStripFinalNewline, 2, false, false, execa);22test('stripFinalNewline: default with stdio[*]', testStripFinalNewline, 3, undefined, true, execa);23test('stripFinalNewline: true with stdio[*]', testStripFinalNewline, 3, true, true, execa);24test('stripFinalNewline: false with stdio[*]', testStripFinalNewline, 3, false, false, execa);25test('stripFinalNewline: default with stdout, fd-specific', testStripFinalNewline, 1, {}, true, execa);26test('stripFinalNewline: true with stdout, fd-specific', testStripFinalNewline, 1, {stdout: true}, true, execa);27test('stripFinalNewline: false with stdout, fd-specific', testStripFinalNewline, 1, {stdout: false}, false, execa);28test('stripFinalNewline: default with stderr, fd-specific', testStripFinalNewline, 2, {}, true, execa);29test('stripFinalNewline: true with stderr, fd-specific', testStripFinalNewline, 2, {stderr: true}, true, execa);30test('stripFinalNewline: false with stderr, fd-specific', testStripFinalNewline, 2, {stderr: false}, false, execa);31test('stripFinalNewline: default with stdio[*], fd-specific', testStripFinalNewline, 3, {}, true, execa);32test('stripFinalNewline: true with stdio[*], fd-specific', testStripFinalNewline, 3, {fd3: true}, true, execa);33test('stripFinalNewline: false with stdio[*], fd-specific', testStripFinalNewline, 3, {fd3: false}, false, execa);34test('stripFinalNewline: default with stdout, sync', testStripFinalNewline, 1, undefined, true, execaSync);35test('stripFinalNewline: true with stdout, sync', testStripFinalNewline, 1, true, true, execaSync);36test('stripFinalNewline: false with stdout, sync', testStripFinalNewline, 1, false, false, execaSync);37test('stripFinalNewline: default with stderr, sync', testStripFinalNewline, 2, undefined, true, execaSync);38test('stripFinalNewline: true with stderr, sync', testStripFinalNewline, 2, true, true, execaSync);39test('stripFinalNewline: false with stderr, sync', testStripFinalNewline, 2, false, false, execaSync);40test('stripFinalNewline: default with stdio[*], sync', testStripFinalNewline, 3, undefined, true, execaSync);41test('stripFinalNewline: true with stdio[*], sync', testStripFinalNewline, 3, true, true, execaSync);42test('stripFinalNewline: false with stdio[*], sync', testStripFinalNewline, 3, false, false, execaSync);43test('stripFinalNewline: default with stdout, fd-specific, sync', testStripFinalNewline, 1, {}, true, execaSync);44test('stripFinalNewline: true with stdout, fd-specific, sync', testStripFinalNewline, 1, {stdout: true}, true, execaSync);45test('stripFinalNewline: false with stdout, fd-specific, sync', testStripFinalNewline, 1, {stdout: false}, false, execaSync);46test('stripFinalNewline: default with stderr, fd-specific, sync', testStripFinalNewline, 2, {}, true, execaSync);47test('stripFinalNewline: true with stderr, fd-specific, sync', testStripFinalNewline, 2, {stderr: true}, true, execaSync);48test('stripFinalNewline: false with stderr, fd-specific, sync', testStripFinalNewline, 2, {stderr: false}, false, execaSync);49test('stripFinalNewline: default with stdio[*], fd-specific, sync', testStripFinalNewline, 3, {}, true, execaSync);50test('stripFinalNewline: true with stdio[*], fd-specific, sync', testStripFinalNewline, 3, {fd3: true}, true, execaSync);51test('stripFinalNewline: false with stdio[*], fd-specific, sync', testStripFinalNewline, 3, {fd3: false}, false, execaSync);5253test('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
1import {join} from 'node:path';2import test from 'ava';3import {execaCommand, execaCommandSync} from '../../index.js';4import {setFixtureDir, FIXTURES_DIR} from '../helpers/fixtures-dir.js';5import {QUOTE} from '../helpers/verbose.js';67setFixtureDir();8const STDIN_FIXTURE = join(FIXTURES_DIR, 'stdin.js');910test('execaCommand()', async t => {11 const {stdout} = await execaCommand('echo.js foo bar');12 t.is(stdout, 'foo\nbar');13});1415test('execaCommandSync()', t => {16 const {stdout} = execaCommandSync('echo.js foo bar');17 t.is(stdout, 'foo\nbar');18});1920test('execaCommand`...`', async t => {21 const {stdout} = await execaCommand`${'echo.js foo bar'}`;22 t.is(stdout, 'foo\nbar');23});2425test('execaCommandSync`...`', t => {26 const {stdout} = execaCommandSync`${'echo.js foo bar'}`;27 t.is(stdout, 'foo\nbar');28});2930test('execaCommand(options)`...`', async t => {31 const {stdout} = await execaCommand({stripFinalNewline: false})`${'echo.js foo bar'}`;32 t.is(stdout, 'foo\nbar\n');33});3435test('execaCommandSync(options)`...`', t => {36 const {stdout} = execaCommandSync({stripFinalNewline: false})`${'echo.js foo bar'}`;37 t.is(stdout, 'foo\nbar\n');38});3940test('execaCommand(options)()', async t => {41 const {stdout} = await execaCommand({stripFinalNewline: false})('echo.js foo bar');42 t.is(stdout, 'foo\nbar\n');43});4445test('execaCommandSync(options)()', t => {46 const {stdout} = execaCommandSync({stripFinalNewline: false})('echo.js foo bar');47 t.is(stdout, 'foo\nbar\n');48});4950test('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});5455test('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});5960test('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});6465test('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});6970test('execaCommand() ignores consecutive spaces', async t => {71 const {stdout} = await execaCommand('echo.js foo bar');72 t.is(stdout, 'foo\nbar');73});7475test('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});7980test('execaCommand() allows escaping spaces in arguments', async t => {81 const {stdout} = await execaCommand('echo.js foo\\ bar');82 t.is(stdout, 'foo bar');83});8485test('execaCommand() escapes other whitespaces', async t => {86 const {stdout} = await execaCommand('echo.js foo\tbar');87 t.is(stdout, 'foo\tbar');88});8990test('execaCommand() trims', async t => {91 const {stdout} = await execaCommand(' echo.js foo bar ');92 t.is(stdout, 'foo\nbar');93});9495const 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};100101test('execaCommand() must not pass an array of arguments', testInvalidArgsArray, execaCommand);102test('execaCommandSync() must not pass an array of arguments', testInvalidArgsArray, execaCommandSync);103104const 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};110111test('execaCommand() must not pass an array of arguments with a template string', testInvalidArgsTemplate, execaCommand);112test('execaCommandSync() must not pass an array of arguments with a template string', testInvalidArgsTemplate, execaCommandSync);
added:test/methods/create-bind.js+104 added
1import {join} from 'node:path';2import test from 'ava';3import {execa, execaSync, execaNode, $} from '../../index.js';4import {foobarString, foobarUppercase} from '../helpers/input.js';5import {uppercaseGenerator} from '../helpers/generator.js';6import {setFixtureDir, FIXTURES_DIR} from '../helpers/fixtures-dir.js';78setFixtureDir();910const NOOP_PATH = join(FIXTURES_DIR, 'noop.js');11const PRINT_ENV_PATH = join(FIXTURES_DIR, 'environment.js');1213const testBindOptions = async (t, execaMethod) => {14 const {stdout} = await execaMethod({stripFinalNewline: false})(NOOP_PATH, [foobarString]);15 t.is(stdout, `${foobarString}\n`);16};1718test('execa() can bind options', testBindOptions, execa);19test('execaNode() can bind options', testBindOptions, execaNode);20test('$ can bind options', testBindOptions, $);2122const testBindOptionsSync = (t, execaMethod) => {23 const {stdout} = execaMethod({stripFinalNewline: false})(NOOP_PATH, [foobarString]);24 t.is(stdout, `${foobarString}\n`);25};2627test('execaSync() can bind options', testBindOptionsSync, execaSync);28test('$.sync can bind options', testBindOptionsSync, $.sync);2930const testBindPriority = async (t, execaMethod) => {31 const {stdout} = await execaMethod({stripFinalNewline: false})(NOOP_PATH, [foobarString], {stripFinalNewline: true});32 t.is(stdout, foobarString);33};3435test('execa() bound options have lower priority', testBindPriority, execa);36test('execaSync() bound options have lower priority', testBindPriority, execaSync);37test('execaNode() bound options have lower priority', testBindPriority, execaNode);38test('$ bound options have lower priority', testBindPriority, $);39test('$.sync bound options have lower priority', testBindPriority, $.sync);4041const testBindUndefined = async (t, execaMethod) => {42 const {stdout} = await execaMethod({stripFinalNewline: false})(NOOP_PATH, [foobarString], {stripFinalNewline: undefined});43 t.is(stdout, foobarString);44};4546test('execa() undefined options use default value', testBindUndefined, execa);47test('execaSync() undefined options use default value', testBindUndefined, execaSync);48test('execaNode() undefined options use default value', testBindUndefined, execaNode);49test('$ undefined options use default value', testBindUndefined, $);50test('$.sync undefined options use default value', testBindUndefined, $.sync);5152const 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};5657test('execa() bound options are merged', testMergeEnv, execa);58test('execaSync() bound options are merged', testMergeEnv, execaSync);59test('execaNode() bound options are merged', testMergeEnv, execaNode);60test('$ bound options are merged', testMergeEnv, $);61test('$.sync bound options are merged', testMergeEnv, $.sync);6263const 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};6768test('execa() bound options are merged multiple times', testMergeMultiple, execa);69test('execaSync() bound options are merged multiple times', testMergeMultiple, execaSync);70test('execaNode() bound options are merged multiple times', testMergeMultiple, execaNode);71test('$ bound options are merged multiple times', testMergeMultiple, $);72test('$.sync bound options are merged multiple times', testMergeMultiple, $.sync);7374const 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};7980test('execa() bound options merge fd-specific ones', testMergeFdSpecific, execa);81test('execaNode() bound options merge fd-specific ones', testMergeFdSpecific, execaNode);82test('$ bound options merge fd-specific ones', testMergeFdSpecific, $);8384const 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};8889test('execa() bound options are merged even if undefined', testMergeEnvUndefined, execa);90test('execaSync() bound options are merged even if undefined', testMergeEnvUndefined, execaSync);91test('execaNode() bound options are merged even if undefined', testMergeEnvUndefined, execaNode);92test('$ bound options are merged even if undefined', testMergeEnvUndefined, $);93test('$.sync bound options are merged even if undefined', testMergeEnvUndefined, $.sync);9495const 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};99100test('execa() bound options only merge specific ones', testMergeSpecific, execa);101test('execaSync() bound options only merge specific ones', testMergeSpecific, execaSync);102test('execaNode() bound options only merge specific ones', testMergeSpecific, execaNode);103test('$ bound options only merge specific ones', testMergeSpecific, $);104test('$.sync bound options only merge specific ones', testMergeSpecific, $.sync);
added:test/methods/create-main.js+58 added
1import {join} from 'node:path';2import test from 'ava';3import {execa, execaSync, execaNode, $} from '../../index.js';4import {foobarString, foobarArray} from '../helpers/input.js';5import {setFixtureDir, FIXTURES_DIR} from '../helpers/fixtures-dir.js';67setFixtureDir();89const NOOP_PATH = join(FIXTURES_DIR, 'noop.js');1011const testTemplate = async (t, execaMethod) => {12 const {stdout} = await execaMethod`${NOOP_PATH} ${foobarString}`;13 t.is(stdout, foobarString);14};1516test('execa() can use template strings', testTemplate, execa);17test('execaNode() can use template strings', testTemplate, execaNode);18test('$ can use template strings', testTemplate, $);1920const testTemplateSync = (t, execaMethod) => {21 const {stdout} = execaMethod`${NOOP_PATH} ${foobarString}`;22 t.is(stdout, foobarString);23};2425test('execaSync() can use template strings', testTemplateSync, execaSync);26test('$.sync can use template strings', testTemplateSync, $.sync);2728const testTemplateOptions = async (t, execaMethod) => {29 const {stdout} = await execaMethod({stripFinalNewline: false})`${NOOP_PATH} ${foobarString}`;30 t.is(stdout, `${foobarString}\n`);31};3233test('execa() can use template strings with options', testTemplateOptions, execa);34test('execaNode() can use template strings with options', testTemplateOptions, execaNode);35test('$ can use template strings with options', testTemplateOptions, $);3637const testTemplateOptionsSync = (t, execaMethod) => {38 const {stdout} = execaMethod({stripFinalNewline: false})`${NOOP_PATH} ${foobarString}`;39 t.is(stdout, `${foobarString}\n`);40};4142test('execaSync() can use template strings with options', testTemplateOptionsSync, execaSync);43test('$.sync can use template strings with options', testTemplateOptionsSync, $.sync);4445const 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};5051test('allow commands with spaces and no array arguments', testSpacedCommand, undefined, execa);52test('allow commands with spaces and array arguments', testSpacedCommand, foobarArray, execa);53test('allow commands with spaces and no array arguments, execaSync', testSpacedCommand, undefined, execaSync);54test('allow commands with spaces and array arguments, execaSync', testSpacedCommand, foobarArray, execaSync);55test('allow commands with spaces and no array arguments, $', testSpacedCommand, undefined, $);56test('allow commands with spaces and array arguments, $', testSpacedCommand, foobarArray, $);57test('allow commands with spaces and no array arguments, $.sync', testSpacedCommand, undefined, $.sync);58test('allow commands with spaces and array arguments, $.sync', testSpacedCommand, foobarArray, $.sync);
added:test/methods/main-async.js+26 added
1import process from 'node:process';2import test from 'ava';3import {execa} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';56setFixtureDir();78const isWindows = process.platform === 'win32';910if (isWindows) {11 test('execa() - cmd file', async t => {12 const {stdout} = await execa('hello.cmd');13 t.is(stdout, 'Hello World');14 });1516 test('execa() - run cmd command', async t => {17 const {stdout} = await execa('cmd', ['/c', 'hello.cmd']);18 t.is(stdout, 'Hello World');19 });20}2122test('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
1import {once} from 'node:events';2import {dirname, relative} from 'node:path';3import process, {version} from 'node:process';4import {pathToFileURL} from 'node:url';5import test from 'ava';6import getNode from 'get-node';7import {pEvent} from 'p-event';8import {execa, execaSync, execaNode} from '../../index.js';9import {FIXTURES_DIR} from '../helpers/fixtures-dir.js';10import {identity, fullStdio} from '../helpers/stdio.js';11import {foobarString} from '../helpers/input.js';1213process.chdir(FIXTURES_DIR);1415const runWithNodeOption = (file, args, options) => Array.isArray(args)16 ? execa(file, args, {...options, node: true})17 : execa(file, {...options, node: true});18const runWithNodeOptionSync = (file, args, options) => Array.isArray(args)19 ? execaSync(file, args, {...options, node: true})20 : execaSync(file, {...options, node: true});21const runWithIpc = (file, options) => execa('node', [file], {...options, ipc: true});2223const testNodeSuccess = async (t, execaMethod) => {24 const {exitCode, stdout} = await execaMethod('noop.js', [foobarString]);25 t.is(exitCode, 0);26 t.is(stdout, foobarString);27};2829test('execaNode() succeeds', testNodeSuccess, execaNode);30test('The "node" option succeeds', testNodeSuccess, runWithNodeOption);31test('The "node" option succeeds - sync', testNodeSuccess, runWithNodeOptionSync);3233test('execaNode(options) succeeds', async t => {34 const {stdout} = await execaNode({stripFinalNewline: false})('noop.js', [foobarString]);35 t.is(stdout, `${foobarString}\n`);36});3738test('execaNode`...` succeeds', async t => {39 const {stdout} = await execaNode`noop.js ${foobarString}`;40 t.is(stdout, foobarString);41});4243test('execaNode().pipe(execaNode()) succeeds', async t => {44 const {stdout} = await execaNode('noop.js').pipe(execaNode('--version'));45 t.is(stdout, version);46});4748test('execaNode().pipe(execa()) requires using "node"', async t => {49 await t.throwsAsync(execaNode('noop.js').pipe(execa('--version')));50});5152test('execaNode().pipe(...) requires using "node"', async t => {53 await t.throwsAsync(execaNode('noop.js').pipe('--version'));54});5556test('execaNode().pipe`...` requires using "node"', async t => {57 await t.throwsAsync(execaNode('noop.js').pipe`--version`);58});5960test('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});6566const testDoubleNode = (t, nodePath, execaMethod) => {67 t.throws(() => {68 execaMethod(nodePath, ['noop.js']);69 }, {message: /does not need to be "node"/});70};7172test('Cannot use "node" as binary - execaNode()', testDoubleNode, 'node', execaNode);73test('Cannot use "node" as binary - "node" option', testDoubleNode, 'node', runWithNodeOption);74test('Cannot use "node" as binary - "node" option sync', testDoubleNode, 'node', runWithNodeOptionSync);75test('Cannot use path to "node" as binary - execaNode()', testDoubleNode, process.execPath, execaNode);76test('Cannot use path to "node" as binary - "node" option', testDoubleNode, process.execPath, runWithNodeOption);77test('Cannot use path to "node" as binary - "node" option sync', testDoubleNode, process.execPath, runWithNodeOptionSync);7879const getNodePath = async () => {80 const {path} = await getNode(TEST_NODE_VERSION);81 return path;82};8384const TEST_NODE_VERSION = '16.0.0';8586const 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};9192test.serial('The "nodePath" option can be used - execaNode()', testNodePath, execaNode, identity);93test.serial('The "nodePath" option can be a file URL - execaNode()', testNodePath, execaNode, pathToFileURL);94test.serial('The "nodePath" option can be used - "node" option', testNodePath, runWithNodeOption, identity);95test.serial('The "nodePath" option can be a file URL - "node" option', testNodePath, runWithNodeOption, pathToFileURL);96test.serial('The "nodePath" option can be used - "node" option sync', testNodePath, runWithNodeOptionSync, identity);97test.serial('The "nodePath" option can be a file URL - "node" option sync', testNodePath, runWithNodeOptionSync, pathToFileURL);9899const testNodePathDefault = async (t, execaMethod) => {100 const {stdout} = await execaMethod('--version');101 t.is(stdout, process.version);102};103104test('The "nodePath" option defaults to the current Node.js binary - execaNode()', testNodePathDefault, execaNode);105test('The "nodePath" option defaults to the current Node.js binary - "node" option', testNodePathDefault, runWithNodeOption);106test('The "nodePath" option defaults to the current Node.js binary - "node" option sync', testNodePathDefault, runWithNodeOptionSync);107108const 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};113114test('The "nodePath" option must be a string or URL - execaNode()', testNodePathInvalid, execaNode);115test('The "nodePath" option must be a string or URL - "node" option', testNodePathInvalid, runWithNodeOption);116test('The "nodePath" option must be a string or URL - "node" option sync', testNodePathInvalid, runWithNodeOptionSync);117118const testFormerNodePath = (t, execaMethod) => {119 t.throws(() => {120 execaMethod('noop.js', [], {execPath: process.execPath});121 }, {message: /The "execPath" option has been removed/});122};123124test('The "execPath" option cannot be used - execaNode()', testFormerNodePath, execaNode);125test('The "execPath" option cannot be used - "node" option', testFormerNodePath, runWithNodeOption);126test('The "execPath" option cannot be used - "node" option sync', testFormerNodePath, runWithNodeOptionSync);127128const nodePathArguments = ['-p', ['process.env.Path || process.env.PATH']];129130const 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};135136test.serial('The "nodePath" option impacts the subprocess - execaNode()', testSubprocessNodePath, execaNode, identity);137test.serial('The "nodePath" option impacts the subprocess - "node" option', testSubprocessNodePath, runWithNodeOption, identity);138test.serial('The "nodePath" option impacts the subprocess - "node" option sync', testSubprocessNodePath, runWithNodeOptionSync, identity);139140const testSubprocessNodePathDefault = async (t, execaMethod) => {141 const {stdout} = await execaMethod(...nodePathArguments);142 t.true(stdout.includes(dirname(process.execPath)));143};144145test('The "nodePath" option defaults to the current Node.js binary in the subprocess - execaNode()', testSubprocessNodePathDefault, execaNode);146test('The "nodePath" option defaults to the current Node.js binary in the subprocess - "node" option', testSubprocessNodePathDefault, runWithNodeOption);147test('The "nodePath" option defaults to the current Node.js binary in the subprocess - "node" option sync', testSubprocessNodePathDefault, runWithNodeOptionSync);148149test.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});154155const 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};162163test.serial('The "nodePath" option is relative to "cwd" when used in the subprocess - execaNode()', testSubprocessNodePathCwd, execaNode);164test.serial('The "nodePath" option is relative to "cwd" when used in the subprocess - "node" option', testSubprocessNodePathCwd, runWithNodeOption);165test.serial('The "nodePath" option is relative to "cwd" when used in the subprocess - "node" option sync', testSubprocessNodePathCwd, runWithNodeOptionSync);166167const 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};174175test.serial('The "nodePath" option is relative to "cwd" - execaNode()', testCwdNodePath, execaNode);176test.serial('The "nodePath" option is relative to "cwd" - "node" option', testCwdNodePath, runWithNodeOption);177test.serial('The "nodePath" option is relative to "cwd" - "node" option sync', testCwdNodePath, runWithNodeOptionSync);178179const testNodeOptions = async (t, execaMethod) => {180 const {stdout} = await execaMethod('empty.js', [], {nodeOptions: ['--version']});181 t.is(stdout, process.version);182};183184test('The "nodeOptions" option can be used - execaNode()', testNodeOptions, execaNode);185test('The "nodeOptions" option can be used - "node" option', testNodeOptions, runWithNodeOption);186test('The "nodeOptions" option can be used - "node" option sync', testNodeOptions, runWithNodeOptionSync);187188const 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);193194const testInspectRemoval = async (t, fakeExecArgv, execaMethod) => {195 const {stdout, stdio} = await spawnNestedExecaNode([], fakeExecArgv, execaMethod, '');196 t.is(stdout, foobarString);197 t.is(stdio[3], '');198};199200test('The "nodeOptions" option removes --inspect without a port when defined by current process - execaNode()', testInspectRemoval, '--inspect', 'execaNode');201test('The "nodeOptions" option removes --inspect without a port when defined by current process - "node" option', testInspectRemoval, '--inspect', 'nodeOption');202test('The "nodeOptions" option removes --inspect with a port when defined by current process - execaNode()', testInspectRemoval, '--inspect=9222', 'execaNode');203test('The "nodeOptions" option removes --inspect with a port when defined by current process - "node" option', testInspectRemoval, '--inspect=9222', 'nodeOption');204test('The "nodeOptions" option removes --inspect-brk without a port when defined by current process - execaNode()', testInspectRemoval, '--inspect-brk', 'execaNode');205test('The "nodeOptions" option removes --inspect-brk without a port when defined by current process - "node" option', testInspectRemoval, '--inspect-brk', 'nodeOption');206test('The "nodeOptions" option removes --inspect-brk with a port when defined by current process - execaNode()', testInspectRemoval, '--inspect-brk=9223', 'execaNode');207test('The "nodeOptions" option removes --inspect-brk with a port when defined by current process - "node" option', testInspectRemoval, '--inspect-brk=9223', 'nodeOption');208209const 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};214215test.serial('The "nodeOptions" option allows --inspect with a different port even when defined by current process - execaNode()', testInspectDifferentPort, 'execaNode');216test.serial('The "nodeOptions" option allows --inspect with a different port even when defined by current process - "node" option', testInspectDifferentPort, 'nodeOption');217218const 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};223224test.serial('The "nodeOptions" option forbids --inspect with the same port when defined by current process - execaNode()', testInspectSamePort, 'execaNode');225test.serial('The "nodeOptions" option forbids --inspect with the same port when defined by current process - "node" option', testInspectSamePort, 'nodeOption');226227const 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};236237test('execaNode() adds an ipc channel', testIpc, execaNode, {});238test('The "node" option adds an ipc channel', testIpc, runWithNodeOption, {});239test('The "ipc" option adds an ipc channel', testIpc, runWithIpc, {});240test('The "ipc" option works with "stdio: \'pipe\'"', testIpc, runWithIpc, {stdio: 'pipe'});241test('The "ipc" option works with "stdio: [\'pipe\', \'pipe\', \'pipe\']"', testIpc, runWithIpc, {stdio: ['pipe', 'pipe', 'pipe']});242test('The "ipc" option works with "stdio: [\'pipe\', \'pipe\', \'pipe\', \'ipc\']"', testIpc, runWithIpc, {stdio: ['pipe', 'pipe', 'pipe', 'ipc']});243test('The "ipc" option works with "stdout: \'pipe\'"', testIpc, runWithIpc, {stdout: 'pipe'});244245test('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});249250const 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};256257test('Can disable "ipc" - execaNode()', testDisableIpc, execaNode);258test('Can disable "ipc" - "node" option', testDisableIpc, runWithNodeOption);259test('Can disable "ipc" - "node" option sync', testDisableIpc, runWithNodeOptionSync);260261const NO_IPC_MESSAGE = /The "ipc: true" option cannot be used/;262263const testNoIpcSync = (t, node) => {264 t.throws(() => {265 execaSync('node', ['send.js'], {ipc: true, node});266 }, {message: NO_IPC_MESSAGE});267};268269test('Cannot use "ipc: true" with execaSync()', testNoIpcSync, undefined);270test('Cannot use "ipc: true" with execaSync() - "node: false"', testNoIpcSync, false);271272test('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});277278const 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};283284test('Cannot use "shell: true" - execaNode()', testNoShell, execaNode);285test('Cannot use "shell: true" - "node" option', testNoShell, runWithNodeOption);286test('Cannot use "shell: true" - "node" option sync', testNoShell, runWithNodeOptionSync);287288test('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});295296test('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
1import test from 'ava';2// The helper module overrides Promise on import so has to be imported before `execa`.3import {restorePromise} from '../helpers/override-promise.js';4import {execa} from '../../index.js';5import {setFixtureDir} from '../helpers/fixtures-dir.js';67restorePromise();8setFixtureDir();910test('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
1import test from 'ava';2import {execa, execaSync, execaCommand, execaCommandSync, execaNode, $} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';45setFixtureDir();67const testInvalidArgs = async (t, execaMethod) => {8 t.throws(() => {9 execaMethod('echo', true);10 }, {message: /Second argument must be either/});11};1213test('execa()\'s second argument must be valid', testInvalidArgs, execa);14test('execaSync()\'s second argument must be valid', testInvalidArgs, execaSync);15test('execaCommand()\'s second argument must be valid', testInvalidArgs, execaCommand);16test('execaCommandSync()\'s second argument must be valid', testInvalidArgs, execaCommandSync);17test('execaNode()\'s second argument must be valid', testInvalidArgs, execaNode);18test('$\'s second argument must be valid', testInvalidArgs, $);19test('$.sync\'s second argument must be valid', testInvalidArgs, $.sync);2021const testInvalidArgsItems = async (t, execaMethod) => {22 t.throws(() => {23 execaMethod('echo', [{}]);24 }, {message: 'Second argument must be an array of strings: [object Object]'});25};2627test('execa()\'s second argument must not be objects', testInvalidArgsItems, execa);28test('execaSync()\'s second argument must not be objects', testInvalidArgsItems, execaSync);29test('execaCommand()\'s second argument must not be objects', testInvalidArgsItems, execaCommand);30test('execaCommandSync()\'s second argument must not be objects', testInvalidArgsItems, execaCommandSync);31test('execaNode()\'s second argument must not be objects', testInvalidArgsItems, execaNode);32test('$\'s second argument must not be objects', testInvalidArgsItems, $);33test('$.sync\'s second argument must not be objects', testInvalidArgsItems, $.sync);3435const testNullByteArg = async (t, execaMethod) => {36 t.throws(() => {37 execaMethod('echo', ['a\0b']);38 }, {message: /null bytes/});39};4041test('execa()\'s second argument must not include \\0', testNullByteArg, execa);42test('execaSync()\'s second argument must not include \\0', testNullByteArg, execaSync);43test('execaCommand()\'s second argument must not include \\0', testNullByteArg, execaCommand);44test('execaCommandSync()\'s second argument must not include \\0', testNullByteArg, execaCommandSync);45test('execaNode()\'s second argument must not include \\0', testNullByteArg, execaNode);46test('$\'s second argument must not include \\0', testNullByteArg, $);47test('$.sync\'s second argument must not include \\0', testNullByteArg, $.sync);
added:test/methods/parameters-command.js+80 added
1import {join, basename} from 'node:path';2import {fileURLToPath} from 'node:url';3import test from 'ava';4import {execa, execaSync, execaCommand, execaCommandSync, execaNode, $} from '../../index.js';5import {setFixtureDir, FIXTURES_DIR_URL} from '../helpers/fixtures-dir.js';6import {foobarString} from '../helpers/input.js';78setFixtureDir();910const 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};1516test('execa()\'s command argument can be a file URL', testFileUrl, execa);17test('execaSync()\'s command argument can be a file URL', testFileUrl, execaSync);18test('execaCommand()\'s command argument can be a file URL', testFileUrl, execaCommand);19test('execaCommandSync()\'s command argument can be a file URL', testFileUrl, execaCommandSync);20test('execaNode()\'s command argument can be a file URL', testFileUrl, execaNode);21test('$\'s command argument can be a file URL', testFileUrl, $);22test('$.sync\'s command argument can be a file URL', testFileUrl, $.sync);2324const 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};3031test('execa()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execa);32test('execaSync()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execaSync);33test('execaCommand()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execaCommand);34test('execaCommandSync()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execaCommandSync);35test('execaNode()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execaNode);36test('$\'s command argument cannot be a non-file URL', testInvalidFileUrl, $);37test('$.sync\'s command argument cannot be a non-file URL', testInvalidFileUrl, $.sync);3839const testInvalidCommand = async (t, arg, execaMethod) => {40 t.throws(() => {41 execaMethod(arg);42 }, {message: /First argument must be a string or a file URL/});43};4445test('execa()\'s first argument must be defined', testInvalidCommand, undefined, execa);46test('execaSync()\'s first argument must be defined', testInvalidCommand, undefined, execaSync);47test('execaCommand()\'s first argument must be defined', testInvalidCommand, undefined, execaCommand);48test('execaCommandSync()\'s first argument must be defined', testInvalidCommand, undefined, execaCommandSync);49test('execaNode()\'s first argument must be defined', testInvalidCommand, undefined, execaNode);50test('$\'s first argument must be defined', testInvalidCommand, undefined, $);51test('$.sync\'s first argument must be defined', testInvalidCommand, undefined, $.sync);52test('execa()\'s first argument must be valid', testInvalidCommand, true, execa);53test('execaSync()\'s first argument must be valid', testInvalidCommand, true, execaSync);54test('execaCommand()\'s first argument must be valid', testInvalidCommand, true, execaCommand);55test('execaCommandSync()\'s first argument must be valid', testInvalidCommand, true, execaCommandSync);56test('execaNode()\'s first argument must be valid', testInvalidCommand, true, execaNode);57test('$\'s first argument must be valid', testInvalidCommand, true, $);58test('$.sync\'s first argument must be valid', testInvalidCommand, true, $.sync);59test('execa()\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], execa);60test('execaSync()\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], execaSync);61test('execaCommand()\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], execaCommand);62test('execaCommandSync()\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], execaCommandSync);63test('execaNode()\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], execaNode);64test('$\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], $);65test('$.sync\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], $.sync);6667const 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};7374test('execa() use relative path with \'..\' chars', testRelativePath, execa);75test('execaSync() use relative path with \'..\' chars', testRelativePath, execaSync);76test('execaCommand() use relative path with \'..\' chars', testRelativePath, execaCommand);77test('execaCommandSync() use relative path with \'..\' chars', testRelativePath, execaCommandSync);78test('execaNode() use relative path with \'..\' chars', testRelativePath, execaNode);79test('$ use relative path with \'..\' chars', testRelativePath, $);80test('$.sync use relative path with \'..\' chars', testRelativePath, $.sync);
added:test/methods/parameters-options.js+68 added
1import {join} from 'node:path';2import test from 'ava';3import {execa, execaSync, execaCommand, execaCommandSync, execaNode, $} from '../../index.js';4import {setFixtureDir, FIXTURES_DIR} from '../helpers/fixtures-dir.js';56setFixtureDir();78const NOOP_PATH = join(FIXTURES_DIR, 'noop.js');910const testSerializeArg = async (t, arg, execaMethod) => {11 const {stdout} = await execaMethod(NOOP_PATH, [arg]);12 t.is(stdout, String(arg));13};1415test('execa()\'s arguments can be numbers', testSerializeArg, 1, execa);16test('execa()\'s arguments can be booleans', testSerializeArg, true, execa);17test('execa()\'s arguments can be NaN', testSerializeArg, Number.NaN, execa);18test('execa()\'s arguments can be Infinity', testSerializeArg, Number.POSITIVE_INFINITY, execa);19test('execa()\'s arguments can be null', testSerializeArg, null, execa);20test('execa()\'s arguments can be undefined', testSerializeArg, undefined, execa);21test('execa()\'s arguments can be bigints', testSerializeArg, 1n, execa);22test('execa()\'s arguments can be symbols', testSerializeArg, Symbol('test'), execa);23test('execaSync()\'s arguments can be numbers', testSerializeArg, 1, execaSync);24test('execaSync()\'s arguments can be booleans', testSerializeArg, true, execaSync);25test('execaSync()\'s arguments can be NaN', testSerializeArg, Number.NaN, execaSync);26test('execaSync()\'s arguments can be Infinity', testSerializeArg, Number.POSITIVE_INFINITY, execaSync);27test('execaSync()\'s arguments can be null', testSerializeArg, null, execaSync);28test('execaSync()\'s arguments can be undefined', testSerializeArg, undefined, execaSync);29test('execaSync()\'s arguments can be bigints', testSerializeArg, 1n, execaSync);30test('execaSync()\'s arguments can be symbols', testSerializeArg, Symbol('test'), execaSync);31test('execaNode()\'s arguments can be numbers', testSerializeArg, 1, execaNode);32test('execaNode()\'s arguments can be booleans', testSerializeArg, true, execaNode);33test('execaNode()\'s arguments can be NaN', testSerializeArg, Number.NaN, execaNode);34test('execaNode()\'s arguments can be Infinity', testSerializeArg, Number.POSITIVE_INFINITY, execaNode);35test('execaNode()\'s arguments can be null', testSerializeArg, null, execaNode);36test('execaNode()\'s arguments can be undefined', testSerializeArg, undefined, execaNode);37test('execaNode()\'s arguments can be bigints', testSerializeArg, 1n, execaNode);38test('execaNode()\'s arguments can be symbols', testSerializeArg, Symbol('test'), execaNode);39test('$\'s arguments can be numbers', testSerializeArg, 1, $);40test('$\'s arguments can be booleans', testSerializeArg, true, $);41test('$\'s arguments can be NaN', testSerializeArg, Number.NaN, $);42test('$\'s arguments can be Infinity', testSerializeArg, Number.POSITIVE_INFINITY, $);43test('$\'s arguments can be null', testSerializeArg, null, $);44test('$\'s arguments can be undefined', testSerializeArg, undefined, $);45test('$\'s arguments can be bigints', testSerializeArg, 1n, $);46test('$\'s arguments can be symbols', testSerializeArg, Symbol('test'), $);47test('$.sync\'s arguments can be numbers', testSerializeArg, 1, $.sync);48test('$.sync\'s arguments can be booleans', testSerializeArg, true, $.sync);49test('$.sync\'s arguments can be NaN', testSerializeArg, Number.NaN, $.sync);50test('$.sync\'s arguments can be Infinity', testSerializeArg, Number.POSITIVE_INFINITY, $.sync);51test('$.sync\'s arguments can be null', testSerializeArg, null, $.sync);52test('$.sync\'s arguments can be undefined', testSerializeArg, undefined, $.sync);53test('$.sync\'s arguments can be bigints', testSerializeArg, 1n, $.sync);54test('$.sync\'s arguments can be symbols', testSerializeArg, Symbol('test'), $.sync);5556const testInvalidOptions = async (t, execaMethod) => {57 t.throws(() => {58 execaMethod('echo', [], new Map());59 }, {message: /Last argument must be an options object/});60};6162test('execa()\'s third argument must be a plain object', testInvalidOptions, execa);63test('execaSync()\'s third argument must be a plain object', testInvalidOptions, execaSync);64test('execaCommand()\'s third argument must be a plain object', testInvalidOptions, execaCommand);65test('execaCommandSync()\'s third argument must be a plain object', testInvalidOptions, execaCommandSync);66test('execaNode()\'s third argument must be a plain object', testInvalidOptions, execaNode);67test('$\'s third argument must be a plain object', testInvalidOptions, $);68test('$.sync\'s third argument must be a plain object', testInvalidOptions, $.sync);
added:test/methods/promise.js+53 added
1import test from 'ava';2import {execa} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';45setFixtureDir();67test('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});1314test('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});2223test('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});3233test('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});3940test('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});4647const 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};5152test('Throws if promise is not awaited and subprocess fails', testNoAwait, 'fail.js', {}, 'exit code 2');53test('Throws if promise is not awaited and subprocess times out', testNoAwait, 'forever.js', {timeout: 1}, 'timed out');
added:test/methods/script.js+59 added
1import test from 'ava';2import {isStream} from 'is-stream';3import {$} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';5import {foobarString} from '../helpers/input.js';67setFixtureDir();89const testScriptStdoutSync = (t, getSubprocess, expectedStdout) => {10 const {stdout} = getSubprocess();11 t.is(stdout, expectedStdout);12};1314test('$.sync`...`', testScriptStdoutSync, () => $.sync`echo.js foo bar`, 'foo\nbar');15test('$.s`...`', testScriptStdoutSync, () => $.s`echo.js foo bar`, 'foo\nbar');16test('$(options).sync`...`', testScriptStdoutSync, () => $({stripFinalNewline: false}).sync`echo.js ${foobarString}`, `${foobarString}\n`);17test('$.sync(options)`...`', testScriptStdoutSync, () => $.sync({stripFinalNewline: false})`echo.js ${foobarString}`, `${foobarString}\n`);1819test('Cannot call $.sync.sync', t => {20 t.false('sync' in $.sync);21});2223test('Cannot call $.sync(options).sync', t => {24 t.false('sync' in $.sync({}));25});2627test('$(options)() stdin defaults to "inherit"', async t => {28 const {stdout} = await $({input: foobarString})('stdin-script.js');29 t.is(stdout, foobarString);30});3132test('$.sync(options)() stdin defaults to "inherit"', t => {33 const {stdout} = $.sync({input: foobarString})('stdin-script.js');34 t.is(stdout, foobarString);35});3637test('$(options).sync() stdin defaults to "inherit"', t => {38 const {stdout} = $({input: foobarString}).sync('stdin-script.js');39 t.is(stdout, foobarString);40});4142test('$(options)`...` stdin defaults to "inherit"', async t => {43 const {stdout} = await $({input: foobarString})`stdin-script.js`;44 t.is(stdout, foobarString);45});4647test('$.sync(options)`...` stdin defaults to "inherit"', t => {48 const {stdout} = $.sync({input: foobarString})`stdin-script.js`;49 t.is(stdout, foobarString);50});5152test('$(options).sync`...` stdin defaults to "inherit"', t => {53 const {stdout} = $({input: foobarString}).sync`stdin-script.js`;54 t.is(stdout, foobarString);55});5657test('$ 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
1import test from 'ava';2import {$} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';45setFixtureDir();67// Workaround since some text editors or IDEs do not allow inputting \r directly8const escapedCall = string => {9 const templates = [string];10 templates.raw = [string];11 return $(templates);12};1314const testScriptStdout = async (t, getSubprocess, expectedStdout) => {15 const {stdout} = await getSubprocess();16 t.is(stdout, expectedStdout);17};1819test('$ allows number interpolation', testScriptStdout, () => $`echo.js 1 ${2}`, '1\n2');20test('$ can concatenate multiple tokens', testScriptStdout, () => $`echo.js ${'foo'}bar${'foo'}`, 'foobarfoo');21test('$ can use newlines and tab indentations', testScriptStdout, () => $`echo.js foo22 bar`, 'foo\nbar');23test('$ can use newlines and space indentations', testScriptStdout, () => $`echo.js foo24 bar`, 'foo\nbar');25test('$ can use Windows newlines and tab indentations', testScriptStdout, () => escapedCall('echo.js foo\r\n\tbar'), 'foo\nbar');26test('$ can use Windows newlines and space indentations', testScriptStdout, () => escapedCall('echo.js foo\r\n bar'), 'foo\nbar');27test('$ 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');33test('$ allows escaping spaces with interpolation', testScriptStdout, () => $`echo.js ${'foo bar'}`, 'foo bar');34test('$ allows escaping spaces in commands with interpolation', testScriptStdout, () => $`${'command with space.js'} foo bar`, 'foo\nbar');35test('$ trims', testScriptStdout, () => $` echo.js foo bar `, 'foo\nbar');36test('$ allows array interpolation', testScriptStdout, () => $`echo.js ${['foo', 'bar']}`, 'foo\nbar');37test('$ allows empty array interpolation', testScriptStdout, () => $`echo.js foo ${[]} bar`, 'foo\nbar');38test('$ allows space escaped values in array interpolation', testScriptStdout, () => $`echo.js ${['foo', 'bar baz']}`, 'foo\nbar baz');39test('$ can concatenate at the end of tokens followed by an array', testScriptStdout, () => $`echo.js foo${['bar', 'foo']}`, 'foobar\nfoo');40test('$ can concatenate at the start of tokens followed by an array', testScriptStdout, () => $`echo.js ${['foo', 'bar']}foo`, 'foo\nbarfoo');41test('$ can concatenate at the start and end of tokens followed by an array', testScriptStdout, () => $`echo.js foo${['bar', 'foo']}bar`, 'foobar\nfoobar');42test('$ handles escaped newlines', testScriptStdout, () => $`echo.js a\43b`, 'ab');44test('$ handles backslashes at end of lines', testScriptStdout, () => $`echo.js a\\45 b`, 'a\\\nb');46test('$ handles double backslashes at end of lines', testScriptStdout, () => $`echo.js a\\\\47 b`, 'a\\\\\nb');48test('$ handles tokens - a', testScriptStdout, () => $`echo.js a`, 'a');49test('$ handles expressions - a', testScriptStdout, () => $`echo.js ${'a'}`, 'a');50test('$ handles tokens - abc', testScriptStdout, () => $`echo.js abc`, 'abc');51test('$ handles expressions - abc', testScriptStdout, () => $`echo.js ${'abc'}`, 'abc');52test('$ handles tokens - ""', testScriptStdout, () => $`echo.js`, '');53test('$ handles expressions - ""', testScriptStdout, () => $`echo.js a ${''} b`, 'a\n\nb');54test('$ splits tokens - ""', testScriptStdout, () => $`echo.js ab`, 'ab');55test('$ splits expressions - ""', testScriptStdout, () => $`echo.js ${'a'}${'b'}`, 'ab');56test('$ concatenates expressions - ""', testScriptStdout, () => $`echo.js a${'b'}c`, 'abc');57test('$ handles tokens - " "', testScriptStdout, () => $`echo.js `, '');58test('$ handles expressions - " "', testScriptStdout, () => $`echo.js ${' '}`, ' ');59test('$ splits tokens - " "', testScriptStdout, () => $`echo.js a b`, 'a\nb');60test('$ splits expressions - " "', testScriptStdout, () => $`echo.js ${'a'} ${'b'}`, 'a\nb');61test('$ concatenates tokens - " "', testScriptStdout, () => $`echo.js a `, 'a');62test('$ concatenates expressions - " "', testScriptStdout, () => $`echo.js ${'a'} `, 'a');63test('$ handles tokens - " " (2 spaces)', testScriptStdout, () => $`echo.js `, '');64test('$ handles expressions - " " (2 spaces)', testScriptStdout, () => $`echo.js ${' '}`, ' ');65test('$ splits tokens - " " (2 spaces)', testScriptStdout, () => $`echo.js a b`, 'a\nb');66test('$ splits expressions - " " (2 spaces)', testScriptStdout, () => $`echo.js ${'a'} ${'b'}`, 'a\nb');67test('$ concatenates tokens - " " (2 spaces)', testScriptStdout, () => $`echo.js a `, 'a');68test('$ concatenates expressions - " " (2 spaces)', testScriptStdout, () => $`echo.js ${'a'} `, 'a');69test('$ handles tokens - " " (3 spaces)', testScriptStdout, () => $`echo.js `, '');70test('$ handles expressions - " " (3 spaces)', testScriptStdout, () => $`echo.js ${' '}`, ' ');71test('$ splits tokens - " " (3 spaces)', testScriptStdout, () => $`echo.js a b`, 'a\nb');72test('$ splits expressions - " " (3 spaces)', testScriptStdout, () => $`echo.js ${'a'} ${'b'}`, 'a\nb');73test('$ concatenates tokens - " " (3 spaces)', testScriptStdout, () => $`echo.js a `, 'a');74test('$ concatenates expressions - " " (3 spaces)', testScriptStdout, () => $`echo.js ${'a'} `, 'a');75test('$ handles tokens - \\t (no escape)', testScriptStdout, () => $`echo.js `, '');76test('$ handles expressions - \\t (no escape)', testScriptStdout, () => $`echo.js ${' '}`, '\t');77test('$ splits tokens - \\t (no escape)', testScriptStdout, () => $`echo.js a b`, 'a\nb');78test('$ splits expressions - \\t (no escape)', testScriptStdout, () => $`echo.js ${'a'} ${'b'}`, 'a\nb');79test('$ concatenates tokens - \\t (no escape)', testScriptStdout, () => $`echo.js a b`, 'a\nb');80test('$ concatenates expressions - \\t (no escape)', testScriptStdout, () => $`echo.js ${'a'} b`, 'a\nb');81test('$ handles tokens - \\t (escape)', testScriptStdout, () => $`echo.js \t`, '\t');82test('$ handles expressions - \\t (escape)', testScriptStdout, () => $`echo.js ${'\t'}`, '\t');83test('$ splits tokens - \\t (escape)', testScriptStdout, () => $`echo.js a\tb`, 'a\tb');84test('$ splits expressions - \\t (escape)', testScriptStdout, () => $`echo.js ${'a'}\t${'b'}`, 'a\tb');85test('$ concatenates tokens - \\t (escape)', testScriptStdout, () => $`echo.js \ta\t b`, '\ta\t\nb');86test('$ concatenates expressions - \\t (escape)', testScriptStdout, () => $`echo.js \t${'a'}\t b`, '\ta\t\nb');87test('$ handles tokens - \\n (no escape)', testScriptStdout, () => $`echo.js88 `, '');89test('$ handles expressions - \\n (no escape)', testScriptStdout, () => $`echo.js ${`90`} `, '\n');91test('$ splits tokens - \\n (no escape)', testScriptStdout, () => $`echo.js a92 b`, 'a\nb');93test('$ splits expressions - \\n (no escape)', testScriptStdout, () => $`echo.js ${'a'}94 ${'b'}`, 'a\nb');95test('$ concatenates tokens - \\n (no escape)', testScriptStdout, () => $`echo.js96a97 b`, 'a\nb');98test('$ concatenates expressions - \\n (no escape)', testScriptStdout, () => $`echo.js99${'a'}100 b`, 'a\nb');101test('$ handles tokens - \\n (escape)', testScriptStdout, () => $`echo.js \n `, '\n');102test('$ handles expressions - \\n (escape)', testScriptStdout, () => $`echo.js ${'\n'} `, '\n');103test('$ splits tokens - \\n (escape)', testScriptStdout, () => $`echo.js a\n b`, 'a\n\nb');104test('$ splits expressions - \\n (escape)', testScriptStdout, () => $`echo.js ${'a'}\n ${'b'}`, 'a\n\nb');105test('$ concatenates tokens - \\n (escape)', testScriptStdout, () => $`echo.js \na\n b`, '\na\n\nb');106test('$ concatenates expressions - \\n (escape)', testScriptStdout, () => $`echo.js \n${'a'}\n b`, '\na\n\nb');107test('$ handles tokens - \\r (no escape)', testScriptStdout, () => escapedCall('echo.js \r '), '');108test('$ splits tokens - \\r (no escape)', testScriptStdout, () => escapedCall('echo.js a\rb'), 'a\nb');109test('$ splits expressions - \\r (no escape)', testScriptStdout, () => escapedCall(`echo.js ${'a'}\r${'b'}`), 'a\nb');110test('$ concatenates tokens - \\r (no escape)', testScriptStdout, () => escapedCall('echo.js \ra\r b'), 'a\nb');111test('$ concatenates expressions - \\r (no escape)', testScriptStdout, () => escapedCall(`echo.js \r${'a'}\r b`), 'a\nb');112test('$ splits tokens - \\r (escape)', testScriptStdout, () => $`echo.js a\r b`, 'a\r\nb');113test('$ splits expressions - \\r (escape)', testScriptStdout, () => $`echo.js ${'a'}\r ${'b'}`, 'a\r\nb');114test('$ concatenates tokens - \\r (escape)', testScriptStdout, () => $`echo.js \ra\r b`, '\ra\r\nb');115test('$ concatenates expressions - \\r (escape)', testScriptStdout, () => $`echo.js \r${'a'}\r b`, '\ra\r\nb');116test('$ handles tokens - \\r\\n (no escape)', testScriptStdout, () => escapedCall('echo.js \r\n '), '');117test('$ splits tokens - \\r\\n (no escape)', testScriptStdout, () => escapedCall('echo.js a\r\nb'), 'a\nb');118test('$ splits expressions - \\r\\n (no escape)', testScriptStdout, () => escapedCall(`echo.js ${'a'}\r\n${'b'}`), 'a\nb');119test('$ concatenates tokens - \\r\\n (no escape)', testScriptStdout, () => escapedCall('echo.js \r\na\r\n b'), 'a\nb');120test('$ concatenates expressions - \\r\\n (no escape)', testScriptStdout, () => escapedCall(`echo.js \r\n${'a'}\r\n b`), 'a\nb');121test('$ handles tokens - \\r\\n (escape)', testScriptStdout, () => $`echo.js \r\n `, '\r\n');122test('$ handles expressions - \\r\\n (escape)', testScriptStdout, () => $`echo.js ${'\r\n'} `, '\r\n');123test('$ splits tokens - \\r\\n (escape)', testScriptStdout, () => $`echo.js a\r\n b`, 'a\r\n\nb');124test('$ splits expressions - \\r\\n (escape)', testScriptStdout, () => $`echo.js ${'a'}\r\n ${'b'}`, 'a\r\n\nb');125test('$ concatenates tokens - \\r\\n (escape)', testScriptStdout, () => $`echo.js \r\na\r\n b`, '\r\na\r\n\nb');126test('$ 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 */128test('$ handles expressions - \\f (no escape)', testScriptStdout, () => $`echo.js ${' '}`, '\f');129test('$ splits tokens - \\f (no escape)', testScriptStdout, () => $`echo.js a b`, 'a\fb');130test('$ splits expressions - \\f (no escape)', testScriptStdout, () => $`echo.js ${'a'} ${'b'}`, 'a\fb');131test('$ concatenates tokens - \\f (no escape)', testScriptStdout, () => $`echo.js a b`, '\fa\f\nb');132test('$ concatenates expressions - \\f (no escape)', testScriptStdout, () => $`echo.js ${'a'} b`, '\fa\f\nb');133/* eslint-enable no-irregular-whitespace */134test('$ handles tokens - \\f (escape)', testScriptStdout, () => $`echo.js \f`, '\f');135test('$ handles expressions - \\f (escape)', testScriptStdout, () => $`echo.js ${'\f'}`, '\f');136test('$ splits tokens - \\f (escape)', testScriptStdout, () => $`echo.js a\fb`, 'a\fb');137test('$ splits expressions - \\f (escape)', testScriptStdout, () => $`echo.js ${'a'}\f${'b'}`, 'a\fb');138test('$ concatenates tokens - \\f (escape)', testScriptStdout, () => $`echo.js \fa\f b`, '\fa\f\nb');139test('$ concatenates expressions - \\f (escape)', testScriptStdout, () => $`echo.js \f${'a'}\f b`, '\fa\f\nb');140test('$ handles tokens - \\', testScriptStdout, () => $`echo.js \\`, '\\');141test('$ handles expressions - \\', testScriptStdout, () => $`echo.js ${'\\'}`, '\\');142test('$ splits tokens - \\', testScriptStdout, () => $`echo.js a\\b`, 'a\\b');143test('$ splits expressions - \\', testScriptStdout, () => $`echo.js ${'a'}\\${'b'}`, 'a\\b');144test('$ concatenates tokens - \\', testScriptStdout, () => $`echo.js \\a\\ b`, '\\a\\\nb');145test('$ concatenates expressions - \\', testScriptStdout, () => $`echo.js \\${'a'}\\ b`, '\\a\\\nb');146test('$ handles tokens - \\\\', testScriptStdout, () => $`echo.js \\\\`, '\\\\');147test('$ handles expressions - \\\\', testScriptStdout, () => $`echo.js ${'\\\\'}`, '\\\\');148test('$ splits tokens - \\\\', testScriptStdout, () => $`echo.js a\\\\b`, 'a\\\\b');149test('$ splits expressions - \\\\', testScriptStdout, () => $`echo.js ${'a'}\\\\${'b'}`, 'a\\\\b');150test('$ concatenates tokens - \\\\', testScriptStdout, () => $`echo.js \\\\a\\\\ b`, '\\\\a\\\\\nb');151test('$ concatenates expressions - \\\\', testScriptStdout, () => $`echo.js \\\\${'a'}\\\\ b`, '\\\\a\\\\\nb');152test('$ handles tokens - `', testScriptStdout, () => $`echo.js \``, '`');153test('$ handles expressions - `', testScriptStdout, () => $`echo.js ${'`'}`, '`');154test('$ splits tokens - `', testScriptStdout, () => $`echo.js a\`b`, 'a`b');155test('$ splits expressions - `', testScriptStdout, () => $`echo.js ${'a'}\`${'b'}`, 'a`b');156test('$ concatenates tokens - `', testScriptStdout, () => $`echo.js \`a\` b`, '`a`\nb');157test('$ concatenates expressions - `', testScriptStdout, () => $`echo.js \`${'a'}\` b`, '`a`\nb');158test('$ handles tokens - \\v', testScriptStdout, () => $`echo.js \v`, '\v');159test('$ handles expressions - \\v', testScriptStdout, () => $`echo.js ${'\v'}`, '\v');160test('$ splits tokens - \\v', testScriptStdout, () => $`echo.js a\vb`, 'a\vb');161test('$ splits expressions - \\v', testScriptStdout, () => $`echo.js ${'a'}\v${'b'}`, 'a\vb');162test('$ concatenates tokens - \\v', testScriptStdout, () => $`echo.js \va\v b`, '\va\v\nb');163test('$ concatenates expressions - \\v', testScriptStdout, () => $`echo.js \v${'a'}\v b`, '\va\v\nb');164test('$ handles tokens - \\u2028', testScriptStdout, () => $`echo.js \u2028`, '\u2028');165test('$ handles expressions - \\u2028', testScriptStdout, () => $`echo.js ${'\u2028'}`, '\u2028');166test('$ splits tokens - \\u2028', testScriptStdout, () => $`echo.js a\u2028b`, 'a\u2028b');167test('$ splits expressions - \\u2028', testScriptStdout, () => $`echo.js ${'a'}\u2028${'b'}`, 'a\u2028b');168test('$ concatenates tokens - \\u2028', testScriptStdout, () => $`echo.js \u2028a\u2028 b`, '\u2028a\u2028\nb');169test('$ concatenates expressions - \\u2028', testScriptStdout, () => $`echo.js \u2028${'a'}\u2028 b`, '\u2028a\u2028\nb');170test('$ handles tokens - \\a', testScriptStdout, () => $`echo.js \a`, 'a');171test('$ splits tokens - \\a', testScriptStdout, () => $`echo.js a\ab`, 'aab');172test('$ splits expressions - \\a', testScriptStdout, () => $`echo.js ${'a'}\a${'b'}`, 'aab');173test('$ concatenates tokens - \\a', testScriptStdout, () => $`echo.js \aa\a b`, 'aaa\nb');174test('$ concatenates expressions - \\a', testScriptStdout, () => $`echo.js \a${'a'}\a b`, 'aaa\nb');175test('$ handles tokens - \\cJ', testScriptStdout, () => $`echo.js \cJ`, 'cJ');176test('$ splits tokens - \\cJ', testScriptStdout, () => $`echo.js a\cJb`, 'acJb');177test('$ splits expressions - \\cJ', testScriptStdout, () => $`echo.js ${'a'}\cJ${'b'}`, 'acJb');178test('$ concatenates tokens - \\cJ', testScriptStdout, () => $`echo.js \cJa\cJ b`, 'cJacJ\nb');179test('$ concatenates expressions - \\cJ', testScriptStdout, () => $`echo.js \cJ${'a'}\cJ b`, 'cJacJ\nb');180test('$ handles tokens - \\.', testScriptStdout, () => $`echo.js \.`, '.');181test('$ splits tokens - \\.', testScriptStdout, () => $`echo.js a\.b`, 'a.b');182test('$ splits expressions - \\.', testScriptStdout, () => $`echo.js ${'a'}\.${'b'}`, 'a.b');183test('$ concatenates tokens - \\.', testScriptStdout, () => $`echo.js \.a\. b`, '.a.\nb');184test('$ concatenates expressions - \\.', testScriptStdout, () => $`echo.js \.${'a'}\. b`, '.a.\nb');185/* eslint-disable unicorn/no-hex-escape */186test('$ handles tokens - \\x63', testScriptStdout, () => $`echo.js \x63`, 'c');187test('$ splits tokens - \\x63', testScriptStdout, () => $`echo.js a\x63b`, 'acb');188test('$ splits expressions - \\x63', testScriptStdout, () => $`echo.js ${'a'}\x63${'b'}`, 'acb');189test('$ concatenates tokens - \\x63', testScriptStdout, () => $`echo.js \x63a\x63 b`, 'cac\nb');190test('$ concatenates expressions - \\x63', testScriptStdout, () => $`echo.js \x63${'a'}\x63 b`, 'cac\nb');191/* eslint-enable unicorn/no-hex-escape */192test('$ handles tokens - \\u0063', testScriptStdout, () => $`echo.js \u0063`, 'c');193test('$ splits tokens - \\u0063', testScriptStdout, () => $`echo.js a\u0063b`, 'acb');194test('$ splits expressions - \\u0063', testScriptStdout, () => $`echo.js ${'a'}\u0063${'b'}`, 'acb');195test('$ concatenates tokens - \\u0063', testScriptStdout, () => $`echo.js \u0063a\u0063 b`, 'cac\nb');196test('$ concatenates expressions - \\u0063', testScriptStdout, () => $`echo.js \u0063${'a'}\u0063 b`, 'cac\nb');197test('$ handles tokens - \\u{1}', testScriptStdout, () => $`echo.js \u{1}`, '\u0001');198test('$ splits tokens - \\u{1}', testScriptStdout, () => $`echo.js a\u{1}b`, 'a\u0001b');199test('$ splits expressions - \\u{1}', testScriptStdout, () => $`echo.js ${'a'}\u{1}${'b'}`, 'a\u0001b');200test('$ concatenates tokens - \\u{1}', testScriptStdout, () => $`echo.js \u{1}a\u{1} b`, '\u0001a\u0001\nb');201test('$ concatenates expressions - \\u{1}', testScriptStdout, () => $`echo.js \u{1}${'a'}\u{1} b`, '\u0001a\u0001\nb');202test('$ handles tokens - \\u{63}', testScriptStdout, () => $`echo.js \u{63}`, 'c');203test('$ splits tokens - \\u{63}', testScriptStdout, () => $`echo.js a\u{63}b`, 'acb');204test('$ splits expressions - \\u{63}', testScriptStdout, () => $`echo.js ${'a'}\u{63}${'b'}`, 'acb');205test('$ concatenates tokens - \\u{63}', testScriptStdout, () => $`echo.js \u{63}a\u{63} b`, 'cac\nb');206test('$ concatenates expressions - \\u{63}', testScriptStdout, () => $`echo.js \u{63}${'a'}\u{63} b`, 'cac\nb');207test('$ handles tokens - \\u{063}', testScriptStdout, () => $`echo.js \u{063}`, 'c');208test('$ splits tokens - \\u{063}', testScriptStdout, () => $`echo.js a\u{063}b`, 'acb');209test('$ splits expressions - \\u{063}', testScriptStdout, () => $`echo.js ${'a'}\u{063}${'b'}`, 'acb');210test('$ concatenates tokens - \\u{063}', testScriptStdout, () => $`echo.js \u{063}a\u{063} b`, 'cac\nb');211test('$ concatenates expressions - \\u{063}', testScriptStdout, () => $`echo.js \u{063}${'a'}\u{063} b`, 'cac\nb');212test('$ handles tokens - \\u{0063}', testScriptStdout, () => $`echo.js \u{0063}`, 'c');213test('$ splits tokens - \\u{0063}', testScriptStdout, () => $`echo.js a\u{0063}b`, 'acb');214test('$ splits expressions - \\u{0063}', testScriptStdout, () => $`echo.js ${'a'}\u{0063}${'b'}`, 'acb');215test('$ concatenates tokens - \\u{0063}', testScriptStdout, () => $`echo.js \u{0063}a\u{0063} b`, 'cac\nb');216test('$ concatenates expressions - \\u{0063}', testScriptStdout, () => $`echo.js \u{0063}${'a'}\u{0063} b`, 'cac\nb');217test('$ handles tokens - \\u{00063}', testScriptStdout, () => $`echo.js \u{00063}`, 'c');218test('$ splits tokens - \\u{00063}', testScriptStdout, () => $`echo.js a\u{00063}b`, 'acb');219test('$ splits expressions - \\u{00063}', testScriptStdout, () => $`echo.js ${'a'}\u{00063}${'b'}`, 'acb');220test('$ concatenates tokens - \\u{00063}', testScriptStdout, () => $`echo.js \u{00063}a\u{00063} b`, 'cac\nb');221test('$ concatenates expressions - \\u{00063}', testScriptStdout, () => $`echo.js \u{00063}${'a'}\u{00063} b`, 'cac\nb');222test('$ handles tokens - \\u{000063}', testScriptStdout, () => $`echo.js \u{000063}`, 'c');223test('$ splits tokens - \\u{000063}', testScriptStdout, () => $`echo.js a\u{000063}b`, 'acb');224test('$ splits expressions - \\u{000063}', testScriptStdout, () => $`echo.js ${'a'}\u{000063}${'b'}`, 'acb');225test('$ concatenates tokens - \\u{000063}', testScriptStdout, () => $`echo.js \u{000063}a\u{000063} b`, 'cac\nb');226test('$ concatenates expressions - \\u{000063}', testScriptStdout, () => $`echo.js \u{000063}${'a'}\u{000063} b`, 'cac\nb');227test('$ handles tokens - \\u{0000063}', testScriptStdout, () => $`echo.js \u{0000063}`, 'c');228test('$ splits tokens - \\u{0000063}', testScriptStdout, () => $`echo.js a\u{0000063}b`, 'acb');229test('$ splits expressions - \\u{0000063}', testScriptStdout, () => $`echo.js ${'a'}\u{0000063}${'b'}`, 'acb');230test('$ concatenates tokens - \\u{0000063}', testScriptStdout, () => $`echo.js \u{0000063}a\u{0000063} b`, 'cac\nb');231test('$ concatenates expressions - \\u{0000063}', testScriptStdout, () => $`echo.js \u{0000063}${'a'}\u{0000063} b`, 'cac\nb');232test('$ handles tokens - \\u{0063}}', testScriptStdout, () => $`echo.js \u{0063}}`, 'c}');233test('$ splits tokens - \\u{0063}}', testScriptStdout, () => $`echo.js a\u{0063}}b`, 'ac}b');234test('$ splits expressions - \\u{0063}}', testScriptStdout, () => $`echo.js ${'a'}\u{0063}}${'b'}`, 'ac}b');235test('$ concatenates tokens - \\u{0063}}', testScriptStdout, () => $`echo.js \u{0063}}a\u{0063}} b`, 'c}ac}\nb');236test('$ concatenates expressions - \\u{0063}}', testScriptStdout, () => $`echo.js \u{0063}}${'a'}\u{0063}} b`, 'c}ac}\nb');237238const testScriptErrorStdout = async (t, getSubprocess) => {239 t.throws(getSubprocess, {message: /null bytes/});240};241242test('$ handles tokens - \\0', testScriptErrorStdout, () => $`echo.js \0`);243test('$ splits tokens - \\0', testScriptErrorStdout, () => $`echo.js a\0b`);244test('$ splits expressions - \\0', testScriptErrorStdout, () => $`echo.js ${'a'}\0${'b'}`);245test('$ concatenates tokens - \\0', testScriptErrorStdout, () => $`echo.js \0a\0 b`);246test('$ concatenates expressions - \\0', testScriptErrorStdout, () => $`echo.js \0${'a'}\0 b`);247248const 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};253254test('$ allows execa return value interpolation', testReturnInterpolate, foo => $`echo.js ${foo} bar`, 'foo\nbar');255test('$ allows execa return value buffer interpolation', testReturnInterpolate, foo => $`echo.js ${foo} bar`, 'foo\nbar', {encoding: 'buffer'});256test('$ allows execa return value array interpolation', testReturnInterpolate, foo => $`echo.js ${[foo, 'bar']}`, 'foo\nbar');257test('$ allows execa return value buffer array interpolation', testReturnInterpolate, foo => $`echo.js ${[foo, 'bar']}`, 'foo\nbar', {encoding: 'buffer'});258259const testReturnInterpolateSync = (t, getSubprocess, expectedStdout, options = {}) => {260 const foo = $(options).sync`echo.js foo`;261 const {stdout} = getSubprocess(foo);262 t.is(stdout, expectedStdout);263};264265test('$.sync allows execa return value interpolation', testReturnInterpolateSync, foo => $.sync`echo.js ${foo} bar`, 'foo\nbar');266test('$.sync allows execa return value buffer interpolation', testReturnInterpolateSync, foo => $.sync`echo.js ${foo} bar`, 'foo\nbar', {encoding: 'buffer'});267test('$.sync allows execa return value array interpolation', testReturnInterpolateSync, foo => $.sync`echo.js ${[foo, 'bar']}`, 'foo\nbar');268test('$.sync allows execa return value buffer array interpolation', testReturnInterpolateSync, foo => $.sync`echo.js ${[foo, 'bar']}`, 'foo\nbar', {encoding: 'buffer'});269270const testInvalidSequence = (t, getSubprocess) => {271 t.throws(getSubprocess, {message: /Invalid backslash sequence/});272};273274test('$ handles invalid escape sequence - \\1', testInvalidSequence, () => $`echo.js \1`);275test('$ handles invalid escape sequence - \\u', testInvalidSequence, () => $`echo.js \u`);276test('$ handles invalid escape sequence - \\u0', testInvalidSequence, () => $`echo.js \u0`);277test('$ handles invalid escape sequence - \\u00', testInvalidSequence, () => $`echo.js \u00`);278test('$ handles invalid escape sequence - \\u000', testInvalidSequence, () => $`echo.js \u000`);279test('$ handles invalid escape sequence - \\ug', testInvalidSequence, () => $`echo.js \ug`);280test('$ handles invalid escape sequence - \\u{', testInvalidSequence, () => $`echo.js \u{`);281test('$ handles invalid escape sequence - \\u{0000', testInvalidSequence, () => $`echo.js \u{0000`);282test('$ handles invalid escape sequence - \\u{g}', testInvalidSequence, () => $`echo.js \u{g}`);283/* eslint-disable unicorn/no-hex-escape */284test('$ handles invalid escape sequence - \\x', testInvalidSequence, () => $`echo.js \x`);285test('$ handles invalid escape sequence - \\x0', testInvalidSequence, () => $`echo.js \x0`);286test('$ handles invalid escape sequence - \\xgg', testInvalidSequence, () => $`echo.js \xgg`);287/* eslint-enable unicorn/no-hex-escape */288289const testEmptyScript = (t, getSubprocess) => {290 t.throws(getSubprocess, {message: /Template script must not be empty/});291};292293test('$``', testEmptyScript, () => $``);294test('$` `', testEmptyScript, () => $` `);295test('$` ` (2 spaces)', testEmptyScript, () => $` `);296test('$`\\t`', testEmptyScript, () => $` `);297test('$`\\n`', testEmptyScript, () => $`298`);299300const 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};307308test('$ throws on invalid expression - undefined', testInvalidExpression, undefined, $);309test('$ throws on invalid expression - null', testInvalidExpression, null, $);310test('$ throws on invalid expression - true', testInvalidExpression, true, $);311test('$ throws on invalid expression - {}', testInvalidExpression, {}, $);312test('$ throws on invalid expression - {foo: "bar"}', testInvalidExpression, {foo: 'bar'}, $);313test('$ throws on invalid expression - {stdout: undefined}', testInvalidExpression, {stdout: undefined}, $);314test('$ throws on invalid expression - {stdout: 1}', testInvalidExpression, {stdout: 1}, $);315test('$ throws on invalid expression - Promise.resolve()', testInvalidExpression, Promise.resolve(), $);316test('$ throws on invalid expression - Promise.resolve({stdout: "foo"})', testInvalidExpression, Promise.resolve({foo: 'bar'}), $);317test('$ throws on invalid expression - $', testInvalidExpression, () => $`noop.js`, $);318test('$ throws on invalid expression - $(options).sync', testInvalidExpression, () => $({stdio: 'ignore'}).sync`noop.js`, $);319test('$ throws on invalid expression - [undefined]', testInvalidExpression, [undefined], $);320test('$ throws on invalid expression - [null]', testInvalidExpression, [null], $);321test('$ throws on invalid expression - [true]', testInvalidExpression, [true], $);322test('$ throws on invalid expression - [{}]', testInvalidExpression, [{}], $);323test('$ throws on invalid expression - [{foo: "bar"}]', testInvalidExpression, [{foo: 'bar'}], $);324test('$ throws on invalid expression - [{stdout: undefined}]', testInvalidExpression, [{stdout: undefined}], $);325test('$ throws on invalid expression - [{stdout: 1}]', testInvalidExpression, [{stdout: 1}], $);326test('$ throws on invalid expression - [Promise.resolve()]', testInvalidExpression, [Promise.resolve()], $);327test('$ throws on invalid expression - [Promise.resolve({stdout: "foo"})]', testInvalidExpression, [Promise.resolve({stdout: 'foo'})], $);328test('$ throws on invalid expression - [$]', testInvalidExpression, () => [$`noop.js`], $);329test('$ throws on invalid expression - [$(options).sync]', testInvalidExpression, () => [$({stdio: 'ignore'}).sync`noop.js`], $);
added:test/pipe/pipe-arguments.js+272 added
1import {spawn} from 'node:child_process';2import {pathToFileURL} from 'node:url';3import test from 'ava';4import {$, execa} from '../../index.js';5import {setFixtureDir, FIXTURES_DIR} from '../helpers/fixtures-dir.js';6import {foobarString} from '../helpers/input.js';78setFixtureDir();910test('$.pipe(subprocess)', async t => {11 const {stdout} = await $`noop.js ${foobarString}`.pipe($({stdin: 'pipe'})`stdin.js`);12 t.is(stdout, foobarString);13});1415test('execa.$.pipe(subprocess)', async t => {16 const {stdout} = await execa('noop.js', [foobarString]).pipe($({stdin: 'pipe'})`stdin.js`);17 t.is(stdout, foobarString);18});1920test('$.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});2627test('$.pipe`command`', async t => {28 const {stdout} = await $`noop.js ${foobarString}`.pipe`stdin.js`;29 t.is(stdout, foobarString);30});3132test('execa.$.pipe`command`', async t => {33 const {stdout} = await execa('noop.js', [foobarString]).pipe`stdin.js`;34 t.is(stdout, foobarString);35});3637test('$.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});4344test('$.pipe("file")', async t => {45 const {stdout} = await $`noop.js ${foobarString}`.pipe('stdin.js');46 t.is(stdout, foobarString);47});4849test('execa.$.pipe("file")`', async t => {50 const {stdout} = await execa('noop.js', [foobarString]).pipe('stdin.js');51 t.is(stdout, foobarString);52});5354test('$.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});6061test('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});6566test('$.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});7071test('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});7576test('$.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});8283test('$.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});8788test('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});9293test('$.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});99100test('$.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});104105test('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});109110test('$.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});116117test('$.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});121122test('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});126127test('$.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});133134test('$.pipe(options)`command`', async t => {135 const {stdout} = await $`noop.js ${foobarString}`.pipe({stripFinalNewline: false})`stdin.js`;136 t.is(stdout, `${foobarString}\n`);137});138139test('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});143144test('$.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});150151test('$.pipe("file", options)', async t => {152 const {stdout} = await $`noop.js ${foobarString}`.pipe('stdin.js', {stripFinalNewline: false});153 t.is(stdout, `${foobarString}\n`);154});155156test('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});160161test('$.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});167168test('$.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});172173test('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});177178test('$.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});184185test('$.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});189190test('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});194195test('$.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});201202test('$.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});206207test('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});211212test('$.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});218219test('$.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});223224test('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});228229test('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});235236test('$.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});242243test('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});249250test('$.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});256257test('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});263264const testInvalidPipe = async (t, ...args) => {265 await t.throwsAsync(266 $`empty.js`.pipe(...args),267 {message: /must be a template string/},268 );269};270271test('$.pipe(nonExecaSubprocess) fails', testInvalidPipe, spawn('node', ['--version']));272test('$.pipe(false) fails', testInvalidPipe, false);
deleted:test/pipe/validate.js-272 removed
1import {spawn} from 'node:child_process';2import {pathToFileURL} from 'node:url';3import test from 'ava';4import {$, execa} from '../../index.js';5import {setFixtureDir, FIXTURES_DIR} from '../helpers/fixtures-dir.js';6import {foobarString} from '../helpers/input.js';78setFixtureDir();910test('$.pipe(subprocess)', async t => {11 const {stdout} = await $`noop.js ${foobarString}`.pipe($({stdin: 'pipe'})`stdin.js`);12 t.is(stdout, foobarString);13});1415test('execa.$.pipe(subprocess)', async t => {16 const {stdout} = await execa('noop.js', [foobarString]).pipe($({stdin: 'pipe'})`stdin.js`);17 t.is(stdout, foobarString);18});1920test('$.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});2627test('$.pipe`command`', async t => {28 const {stdout} = await $`noop.js ${foobarString}`.pipe`stdin.js`;29 t.is(stdout, foobarString);30});3132test('execa.$.pipe`command`', async t => {33 const {stdout} = await execa('noop.js', [foobarString]).pipe`stdin.js`;34 t.is(stdout, foobarString);35});3637test('$.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});4344test('$.pipe("file")', async t => {45 const {stdout} = await $`noop.js ${foobarString}`.pipe('stdin.js');46 t.is(stdout, foobarString);47});4849test('execa.$.pipe("file")`', async t => {50 const {stdout} = await execa('noop.js', [foobarString]).pipe('stdin.js');51 t.is(stdout, foobarString);52});5354test('$.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});6061test('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});6566test('$.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});7071test('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});7576test('$.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});8283test('$.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});8788test('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});9293test('$.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});99100test('$.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});104105test('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});109110test('$.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});116117test('$.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});121122test('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});126127test('$.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});133134test('$.pipe(options)`command`', async t => {135 const {stdout} = await $`noop.js ${foobarString}`.pipe({stripFinalNewline: false})`stdin.js`;136 t.is(stdout, `${foobarString}\n`);137});138139test('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});143144test('$.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});150151test('$.pipe("file", options)', async t => {152 const {stdout} = await $`noop.js ${foobarString}`.pipe('stdin.js', {stripFinalNewline: false});153 t.is(stdout, `${foobarString}\n`);154});155156test('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});160161test('$.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});167168test('$.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});172173test('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});177178test('$.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});184185test('$.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});189190test('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});194195test('$.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});201202test('$.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});206207test('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});211212test('$.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});218219test('$.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});223224test('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});228229test('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});235236test('$.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});242243test('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});249250test('$.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});256257test('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});263264const testInvalidPipe = async (t, ...args) => {265 await t.throwsAsync(266 $`empty.js`.pipe(...args),267 {message: /must be a template string/},268 );269};270271test('$.pipe(nonExecaSubprocess) fails', testInvalidPipe, spawn('node', ['--version']));272test('$.pipe(false) fails', testInvalidPipe, false);
added:test/resolve/all.js+171 added
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {defaultHighWaterMark} from '../helpers/stream.js';5import {foobarString} from '../helpers/input.js';67setFixtureDir();89const textEncoder = new TextEncoder();10const foobarStringFull = `${foobarString}\n`;11const doubleFoobarStringFull = `${foobarStringFull}${foobarStringFull}`;12const doubleFoobarString = `${foobarStringFull}${foobarString}`;13const doubleFoobarUint8ArrayFull = textEncoder.encode(doubleFoobarStringFull);14const doubleFoobarUint8Array = textEncoder.encode(doubleFoobarString);15const doubleFoobarArrayFull = [foobarStringFull, foobarStringFull];16const doubleFoobarArray = [foobarString, foobarString];1718// eslint-disable-next-line max-params19const 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};2526const fdOne = {stderr: true};27const fdBoth = {stdout: true, stderr: true};2829test('result.all is defined', testAllBoth, doubleFoobarStringFull, 'utf8', false, false, false, execa);30test('result.all is defined, encoding "buffer"', testAllBoth, doubleFoobarUint8ArrayFull, 'buffer', false, false, false, execa);31test('result.all is defined, lines', testAllBoth, doubleFoobarArrayFull, 'utf8', true, false, false, execa);32test('result.all is defined, lines, fd-specific one', testAllBoth, doubleFoobarArrayFull, 'utf8', fdOne, false, false, execa);33test('result.all is defined, lines, fd-specific both', testAllBoth, doubleFoobarArrayFull, 'utf8', fdBoth, false, false, execa);34test('result.all is defined, stripFinalNewline', testAllBoth, doubleFoobarString, 'utf8', false, true, false, execa);35test('result.all is defined, stripFinalNewline, fd-specific one', testAllBoth, doubleFoobarString, 'utf8', false, fdOne, false, execa);36test('result.all is defined, stripFinalNewline, fd-specific both', testAllBoth, doubleFoobarString, 'utf8', false, fdBoth, false, execa);37test('result.all is defined, encoding "buffer", stripFinalNewline', testAllBoth, doubleFoobarUint8Array, 'buffer', false, true, false, execa);38test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific one', testAllBoth, doubleFoobarUint8Array, 'buffer', false, fdOne, false, execa);39test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific both', testAllBoth, doubleFoobarUint8Array, 'buffer', false, fdBoth, false, execa);40test('result.all is defined, lines, stripFinalNewline', testAllBoth, doubleFoobarArray, 'utf8', true, true, false, execa);41test('result.all is defined, lines, fd-specific one, stripFinalNewline', testAllBoth, doubleFoobarArray, 'utf8', fdOne, true, false, execa);42test('result.all is defined, lines, fd-specific both, stripFinalNewline', testAllBoth, doubleFoobarArray, 'utf8', fdBoth, true, false, execa);43test('result.all is defined, lines, stripFinalNewline, fd-specific one', testAllBoth, doubleFoobarArray, 'utf8', true, fdOne, false, execa);44test('result.all is defined, lines, stripFinalNewline, fd-specific both', testAllBoth, doubleFoobarArray, 'utf8', true, fdBoth, false, execa);45test('result.all is defined, failure', testAllBoth, doubleFoobarStringFull, 'utf8', false, false, true, execa);46test('result.all is defined, encoding "buffer", failure', testAllBoth, doubleFoobarUint8ArrayFull, 'buffer', false, false, true, execa);47test('result.all is defined, lines, failure', testAllBoth, doubleFoobarArrayFull, 'utf8', true, false, true, execa);48test('result.all is defined, lines, fd-specific one, failure', testAllBoth, doubleFoobarArrayFull, 'utf8', fdOne, false, true, execa);49test('result.all is defined, lines, fd-specific both, failure', testAllBoth, doubleFoobarArrayFull, 'utf8', fdBoth, false, true, execa);50test('result.all is defined, stripFinalNewline, failure', testAllBoth, doubleFoobarString, 'utf8', false, true, true, execa);51test('result.all is defined, stripFinalNewline, fd-specific one, failure', testAllBoth, doubleFoobarString, 'utf8', false, fdOne, true, execa);52test('result.all is defined, stripFinalNewline, fd-specific both, failure', testAllBoth, doubleFoobarString, 'utf8', false, fdBoth, true, execa);53test('result.all is defined, encoding "buffer", stripFinalNewline, failure', testAllBoth, doubleFoobarUint8Array, 'buffer', false, true, true, execa);54test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific one, failure', testAllBoth, doubleFoobarUint8Array, 'buffer', false, fdOne, true, execa);55test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific both, failure', testAllBoth, doubleFoobarUint8Array, 'buffer', false, fdBoth, true, execa);56test('result.all is defined, lines, stripFinalNewline, failure', testAllBoth, doubleFoobarArray, 'utf8', true, true, true, execa);57test('result.all is defined, lines, fd-specific one, stripFinalNewline, failure', testAllBoth, doubleFoobarArray, 'utf8', fdOne, true, true, execa);58test('result.all is defined, lines, fd-specific both, stripFinalNewline, failure', testAllBoth, doubleFoobarArray, 'utf8', fdBoth, true, true, execa);59test('result.all is defined, lines, stripFinalNewline, fd-specific one, failure', testAllBoth, doubleFoobarArray, 'utf8', true, fdOne, true, execa);60test('result.all is defined, lines, stripFinalNewline, fd-specific both, failure', testAllBoth, doubleFoobarArray, 'utf8', true, fdBoth, true, execa);61test('result.all is defined, sync', testAllBoth, doubleFoobarStringFull, 'utf8', false, false, false, execaSync);62test('result.all is defined, encoding "buffer", sync', testAllBoth, doubleFoobarUint8ArrayFull, 'buffer', false, false, false, execaSync);63test('result.all is defined, lines, sync', testAllBoth, doubleFoobarArrayFull, 'utf8', true, false, false, execaSync);64test('result.all is defined, lines, fd-specific one, sync', testAllBoth, doubleFoobarArrayFull, 'utf8', fdOne, false, false, execaSync);65test('result.all is defined, lines, fd-specific both, sync', testAllBoth, doubleFoobarArrayFull, 'utf8', fdBoth, false, false, execaSync);66test('result.all is defined, stripFinalNewline, sync', testAllBoth, doubleFoobarString, 'utf8', false, true, false, execaSync);67test('result.all is defined, stripFinalNewline, fd-specific one, sync', testAllBoth, doubleFoobarString, 'utf8', false, fdOne, false, execaSync);68test('result.all is defined, stripFinalNewline, fd-specific both, sync', testAllBoth, doubleFoobarString, 'utf8', false, fdBoth, false, execaSync);69test('result.all is defined, encoding "buffer", stripFinalNewline, sync', testAllBoth, doubleFoobarUint8Array, 'buffer', false, true, false, execaSync);70test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific one, sync', testAllBoth, doubleFoobarUint8Array, 'buffer', false, fdOne, false, execaSync);71test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific both, sync', testAllBoth, doubleFoobarUint8Array, 'buffer', false, fdBoth, false, execaSync);72test('result.all is defined, lines, stripFinalNewline, sync', testAllBoth, doubleFoobarArray, 'utf8', true, true, false, execaSync);73test('result.all is defined, lines, fd-specific one, stripFinalNewline, sync', testAllBoth, doubleFoobarArray, 'utf8', fdOne, true, false, execaSync);74test('result.all is defined, lines, fd-specific both, stripFinalNewline, sync', testAllBoth, doubleFoobarArray, 'utf8', fdBoth, true, false, execaSync);75test('result.all is defined, lines, stripFinalNewline, fd-specific one, sync', testAllBoth, doubleFoobarArray, 'utf8', true, fdOne, false, execaSync);76test('result.all is defined, lines, stripFinalNewline, fd-specific both, sync', testAllBoth, doubleFoobarArray, 'utf8', true, fdBoth, false, execaSync);77test('result.all is defined, failure, sync', testAllBoth, doubleFoobarStringFull, 'utf8', false, false, true, execaSync);78test('result.all is defined, encoding "buffer", failure, sync', testAllBoth, doubleFoobarUint8ArrayFull, 'buffer', false, false, true, execaSync);79test('result.all is defined, lines, failure, sync', testAllBoth, doubleFoobarArrayFull, 'utf8', true, false, true, execaSync);80test('result.all is defined, lines, fd-specific one, failure, sync', testAllBoth, doubleFoobarArrayFull, 'utf8', fdOne, false, true, execaSync);81test('result.all is defined, lines, fd-specific both, failure, sync', testAllBoth, doubleFoobarArrayFull, 'utf8', fdBoth, false, true, execaSync);82test('result.all is defined, stripFinalNewline, failure, sync', testAllBoth, doubleFoobarString, 'utf8', false, true, true, execaSync);83test('result.all is defined, stripFinalNewline, fd-specific one, failure, sync', testAllBoth, doubleFoobarString, 'utf8', false, fdOne, true, execaSync);84test('result.all is defined, stripFinalNewline, fd-specific both, failure, sync', testAllBoth, doubleFoobarString, 'utf8', false, fdBoth, true, execaSync);85test('result.all is defined, encoding "buffer", stripFinalNewline, failure, sync', testAllBoth, doubleFoobarUint8Array, 'buffer', false, true, true, execaSync);86test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific one, failure, sync', testAllBoth, doubleFoobarUint8Array, 'buffer', false, fdOne, true, execaSync);87test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific both, failure, sync', testAllBoth, doubleFoobarUint8Array, 'buffer', false, fdBoth, true, execaSync);88test('result.all is defined, lines, stripFinalNewline, failure, sync', testAllBoth, doubleFoobarArray, 'utf8', true, true, true, execaSync);89test('result.all is defined, lines, fd-specific one, stripFinalNewline, failure, sync', testAllBoth, doubleFoobarArray, 'utf8', fdOne, true, true, execaSync);90test('result.all is defined, lines, fd-specific both, stripFinalNewline, failure, sync', testAllBoth, doubleFoobarArray, 'utf8', fdBoth, true, true, execaSync);91test('result.all is defined, lines, stripFinalNewline, fd-specific one, failure, sync', testAllBoth, doubleFoobarArray, 'utf8', true, fdOne, true, execaSync);92test('result.all is defined, lines, stripFinalNewline, fd-specific both, failure, sync', testAllBoth, doubleFoobarArray, 'utf8', true, fdBoth, true, execaSync);9394test.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});9899test.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});103104const testAllIgnored = async (t, options, execaMethod) => {105 const {all} = await execaMethod('noop.js');106 t.is(all, undefined);107};108109test('result.all is undefined unless opts.all is true', testAllIgnored, {}, execa);110test('result.all is undefined if opts.all is false', testAllIgnored, {all: false}, execa);111test('result.all is undefined if ignored', testAllIgnored, {stdio: 'ignore', all: true}, execa);112test('result.all is undefined unless opts.all is true, sync', testAllIgnored, {}, execaSync);113test('result.all is undefined if opts.all is false, sync', testAllIgnored, {all: false}, execaSync);114test('result.all is undefined if ignored, sync', testAllIgnored, {stdio: 'ignore', all: true}, execaSync);115116const 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};122123test('subprocess.all has the right objectMode and highWaterMark - stdout + stderr', testAllProperties, {});124test('subprocess.all has the right objectMode and highWaterMark - stdout only', testAllProperties, {stderr: 'ignore'});125test('subprocess.all has the right objectMode and highWaterMark - stderr only', testAllProperties, {stdout: 'ignore'});126127const 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);134135 const result = await subprocess;136 t.is(result[otherStreamName], undefined);137 t.is(result[streamName], foobarString);138 t.is(result.all, foobarString);139};140141test('can use all: true with stdout: ignore', testAllIgnore, 'stderr', 'stdout');142test('can use all: true with stderr: ignore', testAllIgnore, 'stdout', 'stderr');143144const 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};150151test('can use all: true with stdout: ignore, sync', testAllIgnoreSync, 'stderr', 'stdout');152test('can use all: true with stderr: ignore, sync', testAllIgnoreSync, 'stdout', 'stderr');153154test('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);159160 const {stdout, stderr, all} = await subprocess;161 t.is(stdout, undefined);162 t.is(stderr, undefined);163 t.is(all, undefined);164});165166test('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
1import {once} from 'node:events';2import {setTimeout} from 'node:timers/promises';3import test from 'ava';4import {execa} from '../../index.js';5import {setFixtureDir} from '../helpers/fixtures-dir.js';6import {fullStdio, getStdio} from '../helpers/stdio.js';78setFixtureDir();910const testBufferIgnore = async (t, fdNumber, all) => {11 await t.notThrowsAsync(execa('max-buffer.js', [`${fdNumber}`], {...getStdio(fdNumber, 'ignore'), buffer: false, all}));12};1314test('Subprocess buffers stdout, which does not prevent exit if ignored', testBufferIgnore, 1, false);15test('Subprocess buffers stderr, which does not prevent exit if ignored', testBufferIgnore, 2, false);16test('Subprocess buffers all, which does not prevent exit if ignored', testBufferIgnore, 1, true);1718const testBufferNotRead = async (t, fdNumber, all) => {19 const subprocess = execa('max-buffer.js', [`${fdNumber}`], {...fullStdio, buffer: false, all});20 await t.notThrowsAsync(subprocess);21};2223test('Subprocess buffers stdout, which does not prevent exit if not read and buffer is false', testBufferNotRead, 1, false);24test('Subprocess buffers stderr, which does not prevent exit if not read and buffer is false', testBufferNotRead, 2, false);25test('Subprocess buffers stdio[*], which does not prevent exit if not read and buffer is false', testBufferNotRead, 3, false);26test('Subprocess buffers all, which does not prevent exit if not read and buffer is false', testBufferNotRead, 1, true);2728const 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};3435test('Subprocess buffers stdout, which does not prevent exit if read and buffer is false', testBufferRead, 1, false);36test('Subprocess buffers stderr, which does not prevent exit if read and buffer is false', testBufferRead, 2, false);37test('Subprocess buffers stdio[*], which does not prevent exit if read and buffer is false', testBufferRead, 3, false);38test('Subprocess buffers all, which does not prevent exit if read and buffer is false', testBufferRead, 1, true);3940const 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};4647test('Subprocess buffers stdout before it is read', testBufferExit, 1, 'noop-delay.js', true);48test('Subprocess buffers stderr before it is read', testBufferExit, 2, 'noop-delay.js', true);49test('Subprocess buffers stdio[*] before it is read', testBufferExit, 3, 'noop-delay.js', true);50test('Subprocess buffers stdout right away, on successfully exit', testBufferExit, 1, 'noop-fd.js', true);51test('Subprocess buffers stderr right away, on successfully exit', testBufferExit, 2, 'noop-fd.js', true);52test('Subprocess buffers stdio[*] right away, on successfully exit', testBufferExit, 3, 'noop-fd.js', true);53test('Subprocess buffers stdout right away, on failure', testBufferExit, 1, 'noop-fail.js', false);54test('Subprocess buffers stderr right away, on failure', testBufferExit, 2, 'noop-fail.js', false);55test('Subprocess buffers stdio[*] right away, on failure', testBufferExit, 3, 'noop-fail.js', false);5657const 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};6465test('Subprocess buffers stdout right away, even if directly read', testBufferDirect, 1);66test('Subprocess buffers stderr right away, even if directly read', testBufferDirect, 2);67test('Subprocess buffers stdio[*] right away, even if directly read', testBufferDirect, 3);6869const 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};7576test('subprocess.stdout must be read right away', testBufferDestroyOnEnd, 1);77test('subprocess.stderr must be read right away', testBufferDestroyOnEnd, 2);78test('subprocess.stdio[*] must be read right away', testBufferDestroyOnEnd, 3);
added:test/resolve/exit.js+85 added
1import process from 'node:process';2import test from 'ava';3import {execa} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';56const isWindows = process.platform === 'win32';78setFixtureDir();910test('exitCode is 0 on success', async t => {11 const {exitCode} = await execa('noop.js', ['foo']);12 t.is(exitCode, 0);13});1415const 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};2425test('exitCode is 2', testExitCode, 2);26test('exitCode is 3', testExitCode, 3);27test('exitCode is 4', testExitCode, 4);2829if (!isWindows) {30 test('error.signal is SIGINT', async t => {31 const subprocess = execa('forever.js');3233 process.kill(subprocess.pid, 'SIGINT');3435 const {signal} = await t.throwsAsync(subprocess, {message: /was killed with SIGINT/});36 t.is(signal, 'SIGINT');37 });3839 test('error.signalDescription is defined', async t => {40 const subprocess = execa('forever.js');4142 process.kill(subprocess.pid, 'SIGINT');4344 const {signalDescription} = await t.throwsAsync(subprocess, {message: /User interruption with CTRL-C/});45 t.is(signalDescription, 'User interruption with CTRL-C');46 });4748 test('error.signal is SIGTERM', async t => {49 const subprocess = execa('forever.js');5051 process.kill(subprocess.pid, 'SIGTERM');5253 const {signal} = await t.throwsAsync(subprocess, {message: /was killed with SIGTERM/});54 t.is(signal, 'SIGTERM');55 });5657 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 });6162 test('exitCode is undefined on signal termination', async t => {63 const subprocess = execa('forever.js');6465 process.kill(subprocess.pid);6667 const {exitCode} = await t.throwsAsync(subprocess);68 t.is(exitCode, undefined);69 });70}7172test('result.signal is undefined for successful execution', async t => {73 const {signal} = await execa('noop.js');74 t.is(signal, undefined);75});7677test('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});8182test('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
1import {once} from 'node:events';2import test from 'ava';3import getStream from 'get-stream';4import {execa, execaSync} from '../../index.js';5import {setFixtureDir} from '../helpers/fixtures-dir.js';6import {fullStdio, getStdio} from '../helpers/stdio.js';7import {foobarString, foobarUppercase, foobarUppercaseUint8Array} from '../helpers/input.js';8import {resultGenerator, uppercaseGenerator, uppercaseBufferGenerator} from '../helpers/generator.js';910setFixtureDir();1112const 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 ]);2021 t.is(output, '');2223 if (all) {24 t.is(allOutput, '');25 }26};2728test('Lacks some data when stdout is read too late `buffer` set to `false`', testLateStream, 1, false);29test('Lacks some data when stderr is read too late `buffer` set to `false`', testLateStream, 2, false);30test('Lacks some data when stdio[*] is read too late `buffer` set to `false`', testLateStream, 3, false);31test('Lacks some data when all is read too late `buffer` set to `false`', testLateStream, 1, true);3233const getFirstDataEvent = async stream => {34 const [output] = await once(stream, 'data');35 return output.toString();36};3738// eslint-disable-next-line max-params39const 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 ]);4748 const expectedResult = buffer ? foobarString : undefined;4950 t.is(result.stdio[fdNumber], expectedResult);51 t.is(output, foobarString);5253 if (all) {54 t.is(result.all, expectedResult);55 t.is(allOutput, foobarString);56 }57};5859test('Can iterate stdout when `buffer` set to `false`', testIterationBuffer, 1, false, false, false);60test('Can iterate stderr when `buffer` set to `false`', testIterationBuffer, 2, false, false, false);61test('Can iterate stdio[*] when `buffer` set to `false`', testIterationBuffer, 3, false, false, false);62test('Can iterate all when `buffer` set to `false`', testIterationBuffer, 1, false, false, true);63test('Can iterate stdout when `buffer` set to `true`', testIterationBuffer, 1, true, false, false);64test('Can iterate stderr when `buffer` set to `true`', testIterationBuffer, 2, true, false, false);65test('Can iterate stdio[*] when `buffer` set to `true`', testIterationBuffer, 3, true, false, false);66test('Can iterate all when `buffer` set to `true`', testIterationBuffer, 1, true, false, true);67test('Can listen to `data` events on stdout when `buffer` set to `false`', testIterationBuffer, 1, false, true, false);68test('Can listen to `data` events on stderr when `buffer` set to `false`', testIterationBuffer, 2, false, true, false);69test('Can listen to `data` events on stdio[*] when `buffer` set to `false`', testIterationBuffer, 3, false, true, false);70test('Can listen to `data` events on all when `buffer` set to `false`', testIterationBuffer, 1, false, true, true);71test('Can listen to `data` events on stdout when `buffer` set to `true`', testIterationBuffer, 1, true, true, false);72test('Can listen to `data` events on stderr when `buffer` set to `true`', testIterationBuffer, 2, true, true, false);73test('Can listen to `data` events on stdio[*] when `buffer` set to `true`', testIterationBuffer, 3, true, true, false);74test('Can listen to `data` events on all when `buffer` set to `true`', testIterationBuffer, 1, true, true, true);7576const 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};8384test('Listen to stdout errors even when `buffer` is `false`', testNoBufferStreamError, 1, false);85test('Listen to stderr errors even when `buffer` is `false`', testNoBufferStreamError, 2, false);86test('Listen to stdio[*] errors even when `buffer` is `false`', testNoBufferStreamError, 3, false);87test('Listen to all errors even when `buffer` is `false`', testNoBufferStreamError, 1, true);8889const testOutput = async (t, buffer, execaMethod) => {90 const {stdout} = await execaMethod('noop-fd.js', ['1', foobarString], {buffer});91 t.is(stdout, foobarString);92};9394test('buffer: true returns output', testOutput, true, execa);95test('buffer: true returns output, fd-specific', testOutput, {stderr: false}, execa);96test('buffer: default returns output', testOutput, undefined, execa);97test('buffer: default returns output, fd-specific', testOutput, {}, execa);9899const testNoOutput = async (t, stdioOption, buffer, execaMethod) => {100 const {stdout} = await execaMethod('noop.js', {stdout: stdioOption, buffer});101 t.is(stdout, undefined);102};103104test('buffer: false does not return output', testNoOutput, 'pipe', false, execa);105test('buffer: false does not return output, fd-specific', testNoOutput, 'pipe', {stdout: false}, execa);106test('buffer: false does not return output, stdout undefined', testNoOutput, undefined, false, execa);107test('buffer: false does not return output, stdout null', testNoOutput, null, false, execa);108test('buffer: false does not return output, stdout ["pipe"]', testNoOutput, ['pipe'], false, execa);109test('buffer: false does not return output, stdout [undefined]', testNoOutput, [undefined], false, execa);110test('buffer: false does not return output, stdout [null]', testNoOutput, [null], false, execa);111test('buffer: false does not return output, stdout ["pipe", undefined]', testNoOutput, ['pipe', undefined], false, execa);112test('buffer: false does not return output, sync', testNoOutput, 'pipe', false, execaSync);113test('buffer: false does not return output, fd-specific, sync', testNoOutput, 'pipe', {stdout: false}, execaSync);114test('buffer: false does not return output, stdout undefined, sync', testNoOutput, undefined, false, execaSync);115test('buffer: false does not return output, stdout null, sync', testNoOutput, null, false, execaSync);116test('buffer: false does not return output, stdout ["pipe"], sync', testNoOutput, ['pipe'], false, execaSync);117test('buffer: false does not return output, stdout [undefined], sync', testNoOutput, [undefined], false, execaSync);118test('buffer: false does not return output, stdout [null], sync', testNoOutput, [null], false, execaSync);119test('buffer: false does not return output, stdout ["pipe", undefined], sync', testNoOutput, ['pipe', undefined], false, execaSync);120121const 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};126127test('buffer: false does not return output, failure', testNoOutputFail, execa);128test('buffer: false does not return output, failure, sync', testNoOutputFail, execaSync);129130// eslint-disable-next-line max-params131const 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};138139test('buffer: {}, all: true', testNoOutputAll, {}, true, true, execa);140test('buffer: {stdout: false}, all: true', testNoOutputAll, {stdout: false}, false, true, execa);141test('buffer: {stderr: false}, all: true', testNoOutputAll, {stderr: false}, true, false, execa);142test('buffer: {all: false}, all: true', testNoOutputAll, {all: false}, false, false, execa);143test('buffer: {}, all: true, sync', testNoOutputAll, {}, true, true, execaSync);144test('buffer: {stdout: false}, all: true, sync', testNoOutputAll, {stdout: false}, false, true, execaSync);145test('buffer: {stderr: false}, all: true, sync', testNoOutputAll, {stderr: false}, true, false, execaSync);146test('buffer: {all: false}, all: true, sync', testNoOutputAll, {all: false}, false, false, execaSync);147148const 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};157158test('buffer: false still runs transforms', testTransform, false, execa);159test('buffer: false still runs transforms, objectMode', testTransform, true, execa);160test('buffer: false still runs transforms, sync', testTransform, false, execaSync);161test('buffer: false still runs transforms, objectMode, sync', testTransform, true, execaSync);162163const 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};173174test('buffer: false still runs transforms, encoding "buffer"', testTransformBinary, false, execa);175test('buffer: false still runs transforms, encoding "buffer", objectMode', testTransformBinary, true, execa);176test('buffer: false still runs transforms, encoding "buffer", sync', testTransformBinary, false, execaSync);177test('buffer: false still runs transforms, encoding "buffer", objectMode, sync', testTransformBinary, true, execaSync);178179const 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};186187test('buffer: false > emits end event on stdout when promise is rejected', testStreamEnd, 1, false);188test('buffer: false > emits end event on stderr when promise is rejected', testStreamEnd, 2, false);189test('buffer: false > emits end event on stdio[*] when promise is rejected', testStreamEnd, 3, false);190test('buffer: true > emits end event on stdout when promise is rejected', testStreamEnd, 1, true);191test('buffer: true > emits end event on stderr when promise is rejected', testStreamEnd, 2, true);192test('buffer: true > emits end event on stdio[*] when promise is rejected', testStreamEnd, 3, true);
added:test/resolve/stdio.js+117 added
1import {setTimeout} from 'node:timers/promises';2import test from 'ava';3import {execa} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';5import {fullStdio, getStdio, prematureClose, assertEpipe} from '../helpers/stdio.js';6import {infiniteGenerator} from '../helpers/generator.js';78setFixtureDir();910const getStreamInputSubprocess = fdNumber => execa('stdin-fd.js', [`${fdNumber}`], fdNumber === 311 ? getStdio(3, [new Uint8Array(), infiniteGenerator()])12 : {});13const getStreamOutputSubprocess = fdNumber => execa('noop-repeat.js', [`${fdNumber}`], fdNumber === 3 ? fullStdio : {});1415const 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};2122const assertStreamOutputError = (t, fdNumber, {exitCode, signal, isTerminated, failed, stderr}) => {23 if (fdNumber !== 3) {24 t.is(exitCode, 1);25 }2627 t.is(signal, undefined);28 t.false(isTerminated);29 t.true(failed);3031 assertEpipe(t, stderr, fdNumber);32};3334const 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};4041test('Aborting stdin should not make the subprocess exit', testStreamInputAbort, 0);42test('Aborting input stdio[*] should not make the subprocess exit', testStreamInputAbort, 3);4344const 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};5051test('Aborting stdout should not make the subprocess exit', testStreamOutputAbort, 1);52test('Aborting stderr should not make the subprocess exit', testStreamOutputAbort, 2);53test('Aborting output stdio[*] should not make the subprocess exit', testStreamOutputAbort, 3);5455const 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};6364test('Destroying stdin should not make the subprocess exit', testStreamInputDestroy, 0);65test('Destroying input stdio[*] should not make the subprocess exit', testStreamInputDestroy, 3);6667const 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};7576test('Destroying stdout should not make the subprocess exit', testStreamOutputDestroy, 1);77test('Destroying stderr should not make the subprocess exit', testStreamOutputDestroy, 2);78test('Destroying output stdio[*] should not make the subprocess exit', testStreamOutputDestroy, 3);7980const 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};9091test('Errors on stdin should not make the subprocess exit', testStreamInputError, 0);92test('Errors on input stdio[*] should not make the subprocess exit', testStreamInputError, 3);9394const 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};103104test('Errors on stdout should make the subprocess exit', testStreamOutputError, 1);105test('Errors on stderr should make the subprocess exit', testStreamOutputError, 2);106test('Errors on output stdio[*] should make the subprocess exit', testStreamOutputError, 3);107108const 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};115116test('Subprocess waits on stdin before exiting', testWaitOnStreamEnd, 0);117test('Subprocess waits on stdio[*] before exiting', testWaitOnStreamEnd, 3);
added:test/resolve/wait-abort.js+99 added
1import {setImmediate} from 'node:timers/promises';2import test from 'ava';3import {execa} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';5import {prematureClose} from '../helpers/stdio.js';6import {noopReadable, noopWritable, noopDuplex} from '../helpers/stream.js';7import {endOptionStream, destroyOptionStream, destroySubprocessStream, getStreamStdio} from '../helpers/wait.js';89setFixtureDir();1011const noop = () => {};1213// eslint-disable-next-line max-params14const 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();2021 const {stdout} = await subprocess;22 t.is(stdout, '');23 t.true(stream.destroyed);24};2526test('Keeps running when stdin option is used and subprocess.stdin ends', testStreamAbortWait, noop, noopReadable(), 0, false);27test('Keeps running when stdin option is used and subprocess.stdin Duplex ends', testStreamAbortWait, noop, noopDuplex(), 0, false);28test('Keeps running when input stdio[*] option is used and input subprocess.stdio[*] ends', testStreamAbortWait, noop, noopReadable(), 3, false);29test('Keeps running when stdin option is used and subprocess.stdin ends, with a transform', testStreamAbortWait, noop, noopReadable(), 0, true);30test('Keeps running when stdin option is used and subprocess.stdin Duplex ends, with a transform', testStreamAbortWait, noop, noopDuplex(), 0, true);31test('Keeps running when input stdio[*] option is used and input subprocess.stdio[*] ends, with a transform', testStreamAbortWait, noop, noopReadable(), 3, true);3233// eslint-disable-next-line max-params34const 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();3839 const {stdout} = await subprocess;40 t.is(stdout, '');41 t.true(stream.destroyed);42};4344test('Passes when stdin option aborts', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 0, false);45test('Passes when stdin option Duplex aborts', testStreamAbortSuccess, destroyOptionStream, noopDuplex(), 0, false);46test('Passes when input stdio[*] option aborts', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 3, false);47test('Passes when stdout option ends with no more writes', testStreamAbortSuccess, endOptionStream, noopWritable(), 1, false);48test('Passes when stderr option ends with no more writes', testStreamAbortSuccess, endOptionStream, noopWritable(), 2, false);49test('Passes when output stdio[*] option ends with no more writes', testStreamAbortSuccess, endOptionStream, noopWritable(), 3, false);50test('Passes when subprocess.stdout aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 1, false);51test('Passes when subprocess.stdout Duplex aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 1, false);52test('Passes when subprocess.stderr aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 2, false);53test('Passes when subprocess.stderr Duplex aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 2, false);54test('Passes when output subprocess.stdio[*] aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 3, false);55test('Passes when output subprocess.stdio[*] Duplex aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 3, false);56test('Passes when stdin option aborts, with a transform', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 0, true);57test('Passes when stdin option Duplex aborts, with a transform', testStreamAbortSuccess, destroyOptionStream, noopDuplex(), 0, true);58test('Passes when input stdio[*] option aborts, with a transform', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 3, true);59test('Passes when stdout option ends with no more writes, with a transform', testStreamAbortSuccess, endOptionStream, noopWritable(), 1, true);60test('Passes when stderr option ends with no more writes, with a transform', testStreamAbortSuccess, endOptionStream, noopWritable(), 2, true);61test('Passes when output stdio[*] option ends with no more writes, with a transform', testStreamAbortSuccess, endOptionStream, noopWritable(), 3, true);62test('Passes when subprocess.stdout aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 1, true);63test('Passes when subprocess.stdout Duplex aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 1, true);64test('Passes when subprocess.stderr aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 2, true);65test('Passes when subprocess.stderr Duplex aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 2, true);66test('Passes when output subprocess.stdio[*] aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 3, true);67test('Passes when output subprocess.stdio[*] Duplex aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 3, true);6869// eslint-disable-next-line max-params70const 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 }7677 const error = await t.throwsAsync(subprocess);78 t.like(error, {...prematureClose, exitCode: 0});79 t.true(stream.destroyed);80};8182test('Throws abort error when subprocess.stdin aborts', testStreamAbortFail, destroySubprocessStream, noopReadable(), 0, false);83test('Throws abort error when subprocess.stdin Duplex aborts', testStreamAbortFail, destroySubprocessStream, noopDuplex(), 0, false);84test('Throws abort error when input subprocess.stdio[*] aborts', testStreamAbortFail, destroySubprocessStream, noopReadable(), 3, false);85test('Throws abort error when stdout option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopWritable(), 1, false);86test('Throws abort error when stdout option Duplex aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopDuplex(), 1, false);87test('Throws abort error when stderr option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopWritable(), 2, false);88test('Throws abort error when stderr option Duplex aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopDuplex(), 2, false);89test('Throws abort error when output stdio[*] option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopWritable(), 3, false);90test('Throws abort error when output stdio[*] Duplex option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopDuplex(), 3, false);91test('Throws abort error when subprocess.stdin aborts, with a transform', testStreamAbortFail, destroySubprocessStream, noopReadable(), 0, true);92test('Throws abort error when subprocess.stdin Duplex aborts, with a transform', testStreamAbortFail, destroySubprocessStream, noopDuplex(), 0, true);93test('Throws abort error when input subprocess.stdio[*] aborts, with a transform', testStreamAbortFail, destroySubprocessStream, noopReadable(), 3, true);94test('Throws abort error when stdout option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopWritable(), 1, true);95test('Throws abort error when stdout option Duplex aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopDuplex(), 1, true);96test('Throws abort error when stderr option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopWritable(), 2, true);97test('Throws abort error when stderr option Duplex aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopDuplex(), 2, true);98test('Throws abort error when output stdio[*] option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopWritable(), 3, true);99test('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
1import {setImmediate} from 'node:timers/promises';2import test from 'ava';3import {execa} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';5import {assertEpipe} from '../helpers/stdio.js';6import {foobarString} from '../helpers/input.js';7import {noopWritable, noopDuplex} from '../helpers/stream.js';8import {endOptionStream, destroyOptionStream, destroySubprocessStream, getStreamStdio} from '../helpers/wait.js';910setFixtureDir();1112// eslint-disable-next-line max-params13const 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);1819 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};2526test('Throws EPIPE when stdout option ends with more writes', testStreamEpipeFail, endOptionStream, noopWritable(), 1, false);27test('Throws EPIPE when stdout option aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopWritable(), 1, false);28test('Throws EPIPE when stdout option Duplex aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 1, false);29test('Throws EPIPE when stderr option ends with more writes', testStreamEpipeFail, endOptionStream, noopWritable(), 2, false);30test('Throws EPIPE when stderr option aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopWritable(), 2, false);31test('Throws EPIPE when stderr option Duplex aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 2, false);32test('Throws EPIPE when output stdio[*] option ends with more writes', testStreamEpipeFail, endOptionStream, noopWritable(), 3, false);33test('Throws EPIPE when output stdio[*] option aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopWritable(), 3, false);34test('Throws EPIPE when output stdio[*] option Duplex aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 3, false);35test('Throws EPIPE when subprocess.stdout aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 1, false);36test('Throws EPIPE when subprocess.stdout Duplex aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 1, false);37test('Throws EPIPE when subprocess.stderr aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 2, false);38test('Throws EPIPE when subprocess.stderr Duplex aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 2, false);39test('Throws EPIPE when output subprocess.stdio[*] aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 3, false);40test('Throws EPIPE when output subprocess.stdio[*] Duplex aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 3, false);41test('Throws EPIPE when stdout option ends with more writes, with a transform', testStreamEpipeFail, endOptionStream, noopWritable(), 1, true);42test('Throws EPIPE when stdout option aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopWritable(), 1, true);43test('Throws EPIPE when stdout option Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 1, true);44test('Throws EPIPE when stderr option ends with more writes, with a transform', testStreamEpipeFail, endOptionStream, noopWritable(), 2, true);45test('Throws EPIPE when stderr option aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopWritable(), 2, true);46test('Throws EPIPE when stderr option Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 2, true);47test('Throws EPIPE when output stdio[*] option ends with more writes, with a transform', testStreamEpipeFail, endOptionStream, noopWritable(), 3, true);48test('Throws EPIPE when output stdio[*] option aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopWritable(), 3, true);49test('Throws EPIPE when output stdio[*] option Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 3, true);50test('Throws EPIPE when subprocess.stdout aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 1, true);51test('Throws EPIPE when subprocess.stdout Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 1, true);52test('Throws EPIPE when subprocess.stderr aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 2, true);53test('Throws EPIPE when subprocess.stderr Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 2, true);54test('Throws EPIPE when output subprocess.stdio[*] aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 3, true);55test('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
1import test from 'ava';2import {execa} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {noopReadable, noopWritable, noopDuplex} from '../helpers/stream.js';5import {destroyOptionStream, destroySubprocessStream, getStreamStdio} from '../helpers/wait.js';67setFixtureDir();89// eslint-disable-next-line max-params10const 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});1415 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};2324test('Throws stream error when stdin option errors', testStreamError, destroyOptionStream, noopReadable(), 0, false);25test('Throws stream error when stdin option Duplex errors', testStreamError, destroyOptionStream, noopDuplex(), 0, false);26test('Throws stream error when stdout option errors', testStreamError, destroyOptionStream, noopWritable(), 1, false);27test('Throws stream error when stdout option Duplex errors', testStreamError, destroyOptionStream, noopDuplex(), 1, false);28test('Throws stream error when stderr option errors', testStreamError, destroyOptionStream, noopWritable(), 2, false);29test('Throws stream error when stderr option Duplex errors', testStreamError, destroyOptionStream, noopDuplex(), 2, false);30test('Throws stream error when output stdio[*] option errors', testStreamError, destroyOptionStream, noopWritable(), 3, false);31test('Throws stream error when output stdio[*] Duplex option errors', testStreamError, destroyOptionStream, noopDuplex(), 3, false);32test('Throws stream error when input stdio[*] option errors', testStreamError, destroyOptionStream, noopReadable(), 3, false);33test('Throws stream error when subprocess.stdin errors', testStreamError, destroySubprocessStream, noopReadable(), 0, false);34test('Throws stream error when subprocess.stdin Duplex errors', testStreamError, destroySubprocessStream, noopDuplex(), 0, false);35test('Throws stream error when subprocess.stdout errors', testStreamError, destroySubprocessStream, noopWritable(), 1, false);36test('Throws stream error when subprocess.stdout Duplex errors', testStreamError, destroySubprocessStream, noopDuplex(), 1, false);37test('Throws stream error when subprocess.stderr errors', testStreamError, destroySubprocessStream, noopWritable(), 2, false);38test('Throws stream error when subprocess.stderr Duplex errors', testStreamError, destroySubprocessStream, noopDuplex(), 2, false);39test('Throws stream error when output subprocess.stdio[*] errors', testStreamError, destroySubprocessStream, noopWritable(), 3, false);40test('Throws stream error when output subprocess.stdio[*] Duplex errors', testStreamError, destroySubprocessStream, noopDuplex(), 3, false);41test('Throws stream error when input subprocess.stdio[*] errors', testStreamError, destroySubprocessStream, noopReadable(), 3, false);42test('Throws stream error when stdin option errors, with a transform', testStreamError, destroyOptionStream, noopReadable(), 0, true);43test('Throws stream error when stdin option Duplex errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 0, true);44test('Throws stream error when stdout option errors, with a transform', testStreamError, destroyOptionStream, noopWritable(), 1, true);45test('Throws stream error when stdout option Duplex errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 1, true);46test('Throws stream error when stderr option errors, with a transform', testStreamError, destroyOptionStream, noopWritable(), 2, true);47test('Throws stream error when stderr option Duplex errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 2, true);48test('Throws stream error when output stdio[*] option errors, with a transform', testStreamError, destroyOptionStream, noopWritable(), 3, true);49test('Throws stream error when output stdio[*] Duplex option errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 3, true);50test('Throws stream error when input stdio[*] option errors, with a transform', testStreamError, destroyOptionStream, noopReadable(), 3, true);51test('Throws stream error when subprocess.stdin errors, with a transform', testStreamError, destroySubprocessStream, noopReadable(), 0, true);52test('Throws stream error when subprocess.stdin Duplex errors, with a transform', testStreamError, destroySubprocessStream, noopDuplex(), 0, true);53test('Throws stream error when subprocess.stdout errors, with a transform', testStreamError, destroySubprocessStream, noopWritable(), 1, true);54test('Throws stream error when subprocess.stdout Duplex errors, with a transform', testStreamError, destroySubprocessStream, noopDuplex(), 1, true);55test('Throws stream error when subprocess.stderr errors, with a transform', testStreamError, destroySubprocessStream, noopWritable(), 2, true);56test('Throws stream error when subprocess.stderr Duplex errors, with a transform', testStreamError, destroySubprocessStream, noopDuplex(), 2, true);57test('Throws stream error when output subprocess.stdio[*] errors, with a transform', testStreamError, destroySubprocessStream, noopWritable(), 3, true);58test('Throws stream error when output subprocess.stdio[*] Duplex errors, with a transform', testStreamError, destroySubprocessStream, noopDuplex(), 3, true);59test('Throws stream error when input subprocess.stdio[*] errors, with a transform', testStreamError, destroySubprocessStream, noopReadable(), 3, true);
added:test/resolve/wait-subprocess.js+49 added
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {getStdio} from '../helpers/stdio.js';56setFixtureDir();78const testIgnore = async (t, fdNumber, execaMethod) => {9 const result = await execaMethod('noop.js', getStdio(fdNumber, 'ignore'));10 t.is(result.stdio[fdNumber], undefined);11};1213test('stdout is undefined if ignored', testIgnore, 1, execa);14test('stderr is undefined if ignored', testIgnore, 2, execa);15test('stdio[*] is undefined if ignored', testIgnore, 3, execa);16test('stdout is undefined if ignored - sync', testIgnore, 1, execaSync);17test('stderr is undefined if ignored - sync', testIgnore, 2, execaSync);18test('stdio[*] is undefined if ignored - sync', testIgnore, 3, execaSync);1920const 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};2627test('subprocess listeners are cleaned up on success', testSubprocessEventsCleanup, 'empty.js');28test('subprocess listeners are cleaned up on failure', testSubprocessEventsCleanup, 'fail.js');2930test('Aborting stdout should not abort stderr nor all', async t => {31 const subprocess = execa('empty.js', {all: true});3233 subprocess.stdout.destroy();34 t.false(subprocess.stdout.readable);35 t.true(subprocess.stderr.readable);36 t.true(subprocess.all.readable);3738 await subprocess;3940 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
1import test from 'ava';2import {execa, execaSync, ExecaError, ExecaSyncError} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {foobarString} from '../helpers/input.js';5import {getEarlyErrorSubprocess, getEarlyErrorSubprocessSync} from '../helpers/early-error.js';67setFixtureDir();89const 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};1718test('error instance can be null', testUnusualError, null);19test('error instance can be false', testUnusualError, false);20test('error instance can be a string', testUnusualError, 'test');21test('error instance can be a number', testUnusualError, 0);22test('error instance can be a BigInt', testUnusualError, 0n);23test('error instance can be a symbol', testUnusualError, Symbol('test'));24test('error instance can be a function', testUnusualError, () => {});25test('error instance can be an array', testUnusualError, ['test', 'test']);26// eslint-disable-next-line unicorn/error-message27test('error instance can be an error with an empty message', testUnusualError, new Error(''), '');28test('error instance can be undefined', testUnusualError, undefined, 'undefined');2930test('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});3536const runAndFail = (t, fixtureName, argument, error) => {37 const subprocess = execa(fixtureName, [argument]);38 subprocess.emit('error', error);39 return t.throwsAsync(subprocess);40};4142const testErrorCopy = async (t, getPreviousArgument, argument = 'two') => {43 const fixtureName = 'empty.js';44 const firstArgument = 'foo';4546 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}`;5051 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};5960test('error instance can be shared', testErrorCopy, () => new Error(foobarString));61test('error TypeError can be shared', testErrorCopy, () => new TypeError(foobarString));62test('error string can be shared', testErrorCopy, () => foobarString);63test('error copy can be shared', testErrorCopy, (t, fixtureName) => runAndFail(t, fixtureName, 'bar', new Error(foobarString)));64test('error with same message can be shared', testErrorCopy, () => new Error(foobarString), 'foo');6566test('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});7172test('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});7980test('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});8586test('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});9394test('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});104105test('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});113114test('Error is instanceof ExecaError', async t => {115 await t.throwsAsync(execa('fail.js'), {instanceOf: ExecaError});116});117118test('Early error is instanceof ExecaError', async t => {119 await t.throwsAsync(getEarlyErrorSubprocess(), {instanceOf: ExecaError});120});121122test('Error is instanceof ExecaSyncError', t => {123 t.throws(() => {124 execaSync('fail.js');125 }, {instanceOf: ExecaSyncError});126});127128test('Early error is instanceof ExecaSyncError', t => {129 t.throws(() => {130 getEarlyErrorSubprocessSync();131 }, {instanceOf: ExecaSyncError});132});133134test('Pipe error is instanceof ExecaError', async t => {135 await t.throwsAsync(execa('empty.js').pipe(false), {instanceOf: ExecaError});136});137138const 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};143144const {propertyIsEnumerable} = Object.prototype;145146test('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});151152test('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
1import process from 'node:process';2import test from 'ava';3import {execa, execaSync} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';5import {fullStdio} from '../helpers/stdio.js';67const isWindows = process.platform === 'win32';89setFixtureDir();1011const 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};3132test('Return value properties are not missing and are ordered', testSuccessShape, execa);33test('Return value properties are not missing and are ordered, sync', testSuccessShape, execaSync);3435const 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};6364test('Error properties are not missing and are ordered', testErrorShape, execa);65test('Error properties are not missing and are ordered, sync', testErrorShape, execaSync);6667test('failed is false on success', async t => {68 const {failed} = await execa('noop.js', ['foo']);69 t.false(failed);70});7172test('failed is true on failure', async t => {73 const {failed} = await t.throwsAsync(execa('fail.js'));74 t.true(failed);75});7677test('error.isTerminated is true if subprocess was killed directly', async t => {78 const subprocess = execa('forever.js', {killSignal: 'SIGINT'});7980 subprocess.kill();8182 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});8990test('error.isTerminated is true if subprocess was killed indirectly', async t => {91 const subprocess = execa('forever.js', {killSignal: 'SIGHUP'});9293 process.kill(subprocess.pid, 'SIGINT');9495 // `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});106107test('result.isTerminated is false if not killed', async t => {108 const {isTerminated} = await execa('noop.js');109 t.false(isTerminated);110});111112test('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});119120test('result.isTerminated is false if not killed, in sync mode', t => {121 const {isTerminated} = execaSync('noop.js');122 t.false(isTerminated);123});124125test('result.isTerminated is false on subprocess error', async t => {126 const {isTerminated} = await t.throwsAsync(execa('wrong command'));127 t.false(isTerminated);128});129130test('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});136137test('error.code is undefined on success', async t => {138 const {code} = await execa('noop.js');139 t.is(code, undefined);140});141142test('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
1import test from 'ava';2import {execa, execaSync, ExecaError, ExecaSyncError} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {foobarString} from '../helpers/input.js';5import {getEarlyErrorSubprocess, getEarlyErrorSubprocessSync} from '../helpers/early-error.js';67setFixtureDir();89const 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};1718test('error instance can be null', testUnusualError, null);19test('error instance can be false', testUnusualError, false);20test('error instance can be a string', testUnusualError, 'test');21test('error instance can be a number', testUnusualError, 0);22test('error instance can be a BigInt', testUnusualError, 0n);23test('error instance can be a symbol', testUnusualError, Symbol('test'));24test('error instance can be a function', testUnusualError, () => {});25test('error instance can be an array', testUnusualError, ['test', 'test']);26// eslint-disable-next-line unicorn/error-message27test('error instance can be an error with an empty message', testUnusualError, new Error(''), '');28test('error instance can be undefined', testUnusualError, undefined, 'undefined');2930test('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});3536const runAndFail = (t, fixtureName, argument, error) => {37 const subprocess = execa(fixtureName, [argument]);38 subprocess.emit('error', error);39 return t.throwsAsync(subprocess);40};4142const testErrorCopy = async (t, getPreviousArgument, argument = 'two') => {43 const fixtureName = 'empty.js';44 const firstArgument = 'foo';4546 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}`;5051 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};5960test('error instance can be shared', testErrorCopy, () => new Error(foobarString));61test('error TypeError can be shared', testErrorCopy, () => new TypeError(foobarString));62test('error string can be shared', testErrorCopy, () => foobarString);63test('error copy can be shared', testErrorCopy, (t, fixtureName) => runAndFail(t, fixtureName, 'bar', new Error(foobarString)));64test('error with same message can be shared', testErrorCopy, () => new Error(foobarString), 'foo');6566test('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});7172test('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});7980test('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});8586test('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});9394test('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});104105test('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});113114test('Error is instanceof ExecaError', async t => {115 await t.throwsAsync(execa('fail.js'), {instanceOf: ExecaError});116});117118test('Early error is instanceof ExecaError', async t => {119 await t.throwsAsync(getEarlyErrorSubprocess(), {instanceOf: ExecaError});120});121122test('Error is instanceof ExecaSyncError', t => {123 t.throws(() => {124 execaSync('fail.js');125 }, {instanceOf: ExecaSyncError});126});127128test('Early error is instanceof ExecaSyncError', t => {129 t.throws(() => {130 getEarlyErrorSubprocessSync();131 }, {instanceOf: ExecaSyncError});132});133134test('Pipe error is instanceof ExecaError', async t => {135 await t.throwsAsync(execa('empty.js').pipe(false), {instanceOf: ExecaError});136});137138const 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};143144const {propertyIsEnumerable} = Object.prototype;145146test('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});151152test('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
1import process from 'node:process';2import test from 'ava';3import {execa, execaSync} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';5import {fullStdio} from '../helpers/stdio.js';67const isWindows = process.platform === 'win32';89setFixtureDir();1011const 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};3132test('Return value properties are not missing and are ordered', testSuccessShape, execa);33test('Return value properties are not missing and are ordered, sync', testSuccessShape, execaSync);3435const 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};6364test('Error properties are not missing and are ordered', testErrorShape, execa);65test('Error properties are not missing and are ordered, sync', testErrorShape, execaSync);6667test('failed is false on success', async t => {68 const {failed} = await execa('noop.js', ['foo']);69 t.false(failed);70});7172test('failed is true on failure', async t => {73 const {failed} = await t.throwsAsync(execa('fail.js'));74 t.true(failed);75});7677test('error.isTerminated is true if subprocess was killed directly', async t => {78 const subprocess = execa('forever.js', {killSignal: 'SIGINT'});7980 subprocess.kill();8182 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});8990test('error.isTerminated is true if subprocess was killed indirectly', async t => {91 const subprocess = execa('forever.js', {killSignal: 'SIGHUP'});9293 process.kill(subprocess.pid, 'SIGINT');9495 // `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});106107test('result.isTerminated is false if not killed', async t => {108 const {isTerminated} = await execa('noop.js');109 t.false(isTerminated);110});111112test('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});119120test('result.isTerminated is false if not killed, in sync mode', t => {121 const {isTerminated} = execaSync('noop.js');122 t.false(isTerminated);123});124125test('result.isTerminated is false on subprocess error', async t => {126 const {isTerminated} = await t.throwsAsync(execa('wrong command'));127 t.false(isTerminated);128});129130test('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});136137test('error.code is undefined on success', async t => {138 const {code} = await execa('noop.js');139 t.is(code, undefined);140});141142test('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
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {fullStdio} from '../helpers/stdio.js';5import {noopGenerator} from '../helpers/generator.js';6import {foobarString} from '../helpers/input.js';78setFixtureDir();910// eslint-disable-next-line max-params11const 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};1516test('stripFinalNewline: default with stdout', testStripFinalNewline, 1, undefined, true, execa);17test('stripFinalNewline: true with stdout', testStripFinalNewline, 1, true, true, execa);18test('stripFinalNewline: false with stdout', testStripFinalNewline, 1, false, false, execa);19test('stripFinalNewline: default with stderr', testStripFinalNewline, 2, undefined, true, execa);20test('stripFinalNewline: true with stderr', testStripFinalNewline, 2, true, true, execa);21test('stripFinalNewline: false with stderr', testStripFinalNewline, 2, false, false, execa);22test('stripFinalNewline: default with stdio[*]', testStripFinalNewline, 3, undefined, true, execa);23test('stripFinalNewline: true with stdio[*]', testStripFinalNewline, 3, true, true, execa);24test('stripFinalNewline: false with stdio[*]', testStripFinalNewline, 3, false, false, execa);25test('stripFinalNewline: default with stdout, fd-specific', testStripFinalNewline, 1, {}, true, execa);26test('stripFinalNewline: true with stdout, fd-specific', testStripFinalNewline, 1, {stdout: true}, true, execa);27test('stripFinalNewline: false with stdout, fd-specific', testStripFinalNewline, 1, {stdout: false}, false, execa);28test('stripFinalNewline: default with stderr, fd-specific', testStripFinalNewline, 2, {}, true, execa);29test('stripFinalNewline: true with stderr, fd-specific', testStripFinalNewline, 2, {stderr: true}, true, execa);30test('stripFinalNewline: false with stderr, fd-specific', testStripFinalNewline, 2, {stderr: false}, false, execa);31test('stripFinalNewline: default with stdio[*], fd-specific', testStripFinalNewline, 3, {}, true, execa);32test('stripFinalNewline: true with stdio[*], fd-specific', testStripFinalNewline, 3, {fd3: true}, true, execa);33test('stripFinalNewline: false with stdio[*], fd-specific', testStripFinalNewline, 3, {fd3: false}, false, execa);34test('stripFinalNewline: default with stdout, sync', testStripFinalNewline, 1, undefined, true, execaSync);35test('stripFinalNewline: true with stdout, sync', testStripFinalNewline, 1, true, true, execaSync);36test('stripFinalNewline: false with stdout, sync', testStripFinalNewline, 1, false, false, execaSync);37test('stripFinalNewline: default with stderr, sync', testStripFinalNewline, 2, undefined, true, execaSync);38test('stripFinalNewline: true with stderr, sync', testStripFinalNewline, 2, true, true, execaSync);39test('stripFinalNewline: false with stderr, sync', testStripFinalNewline, 2, false, false, execaSync);40test('stripFinalNewline: default with stdio[*], sync', testStripFinalNewline, 3, undefined, true, execaSync);41test('stripFinalNewline: true with stdio[*], sync', testStripFinalNewline, 3, true, true, execaSync);42test('stripFinalNewline: false with stdio[*], sync', testStripFinalNewline, 3, false, false, execaSync);43test('stripFinalNewline: default with stdout, fd-specific, sync', testStripFinalNewline, 1, {}, true, execaSync);44test('stripFinalNewline: true with stdout, fd-specific, sync', testStripFinalNewline, 1, {stdout: true}, true, execaSync);45test('stripFinalNewline: false with stdout, fd-specific, sync', testStripFinalNewline, 1, {stdout: false}, false, execaSync);46test('stripFinalNewline: default with stderr, fd-specific, sync', testStripFinalNewline, 2, {}, true, execaSync);47test('stripFinalNewline: true with stderr, fd-specific, sync', testStripFinalNewline, 2, {stderr: true}, true, execaSync);48test('stripFinalNewline: false with stderr, fd-specific, sync', testStripFinalNewline, 2, {stderr: false}, false, execaSync);49test('stripFinalNewline: default with stdio[*], fd-specific, sync', testStripFinalNewline, 3, {}, true, execaSync);50test('stripFinalNewline: true with stdio[*], fd-specific, sync', testStripFinalNewline, 3, {fd3: true}, true, execaSync);51test('stripFinalNewline: false with stdio[*], fd-specific, sync', testStripFinalNewline, 3, {fd3: false}, false, execaSync);5253test('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
1import {Buffer} from 'node:buffer';2import {exec} from 'node:child_process';3import {promisify} from 'node:util';4import test from 'ava';5import getStream from 'get-stream';6import {execa, execaSync} from '../../index.js';7import {setFixtureDir, FIXTURES_DIR} from '../helpers/fixtures-dir.js';8import {fullStdio} from '../helpers/stdio.js';9import {foobarString, foobarUint8Array, foobarHex} from '../helpers/input.js';1011const pExec = promisify(exec);1213setFixtureDir();1415const 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);1819 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 }2526 if (fdNumber === 3) {27 return;28 }2930 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};3334const 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};4243// This string gives different outputs with each encoding type44const STRING_TO_ENCODE = '\u1000.';45const BUFFER_TO_ENCODE = Buffer.from(STRING_TO_ENCODE);4647test('can pass encoding "buffer" to stdout', checkEncoding, 'buffer', 1, execa);48test('can pass encoding "utf8" to stdout', checkEncoding, 'utf8', 1, execa);49test('can pass encoding "utf16le" to stdout', checkEncoding, 'utf16le', 1, execa);50test('can pass encoding "latin1" to stdout', checkEncoding, 'latin1', 1, execa);51test('can pass encoding "ascii" to stdout', checkEncoding, 'ascii', 1, execa);52test('can pass encoding "hex" to stdout', checkEncoding, 'hex', 1, execa);53test('can pass encoding "base64" to stdout', checkEncoding, 'base64', 1, execa);54test('can pass encoding "base64url" to stdout', checkEncoding, 'base64url', 1, execa);55test('can pass encoding "buffer" to stderr', checkEncoding, 'buffer', 2, execa);56test('can pass encoding "utf8" to stderr', checkEncoding, 'utf8', 2, execa);57test('can pass encoding "utf16le" to stderr', checkEncoding, 'utf16le', 2, execa);58test('can pass encoding "latin1" to stderr', checkEncoding, 'latin1', 2, execa);59test('can pass encoding "ascii" to stderr', checkEncoding, 'ascii', 2, execa);60test('can pass encoding "hex" to stderr', checkEncoding, 'hex', 2, execa);61test('can pass encoding "base64" to stderr', checkEncoding, 'base64', 2, execa);62test('can pass encoding "base64url" to stderr', checkEncoding, 'base64url', 2, execa);63test('can pass encoding "buffer" to stdio[*]', checkEncoding, 'buffer', 3, execa);64test('can pass encoding "utf8" to stdio[*]', checkEncoding, 'utf8', 3, execa);65test('can pass encoding "utf16le" to stdio[*]', checkEncoding, 'utf16le', 3, execa);66test('can pass encoding "latin1" to stdio[*]', checkEncoding, 'latin1', 3, execa);67test('can pass encoding "ascii" to stdio[*]', checkEncoding, 'ascii', 3, execa);68test('can pass encoding "hex" to stdio[*]', checkEncoding, 'hex', 3, execa);69test('can pass encoding "base64" to stdio[*]', checkEncoding, 'base64', 3, execa);70test('can pass encoding "base64url" to stdio[*]', checkEncoding, 'base64url', 3, execa);71test('can pass encoding "buffer" to stdout - sync', checkEncoding, 'buffer', 1, execaSync);72test('can pass encoding "utf8" to stdout - sync', checkEncoding, 'utf8', 1, execaSync);73test('can pass encoding "utf16le" to stdout - sync', checkEncoding, 'utf16le', 1, execaSync);74test('can pass encoding "latin1" to stdout - sync', checkEncoding, 'latin1', 1, execaSync);75test('can pass encoding "ascii" to stdout - sync', checkEncoding, 'ascii', 1, execaSync);76test('can pass encoding "hex" to stdout - sync', checkEncoding, 'hex', 1, execaSync);77test('can pass encoding "base64" to stdout - sync', checkEncoding, 'base64', 1, execaSync);78test('can pass encoding "base64url" to stdout - sync', checkEncoding, 'base64url', 1, execaSync);79test('can pass encoding "buffer" to stderr - sync', checkEncoding, 'buffer', 2, execaSync);80test('can pass encoding "utf8" to stderr - sync', checkEncoding, 'utf8', 2, execaSync);81test('can pass encoding "utf16le" to stderr - sync', checkEncoding, 'utf16le', 2, execaSync);82test('can pass encoding "latin1" to stderr - sync', checkEncoding, 'latin1', 2, execaSync);83test('can pass encoding "ascii" to stderr - sync', checkEncoding, 'ascii', 2, execaSync);84test('can pass encoding "hex" to stderr - sync', checkEncoding, 'hex', 2, execaSync);85test('can pass encoding "base64" to stderr - sync', checkEncoding, 'base64', 2, execaSync);86test('can pass encoding "base64url" to stderr - sync', checkEncoding, 'base64url', 2, execaSync);87test('can pass encoding "buffer" to stdio[*] - sync', checkEncoding, 'buffer', 3, execaSync);88test('can pass encoding "utf8" to stdio[*] - sync', checkEncoding, 'utf8', 3, execaSync);89test('can pass encoding "utf16le" to stdio[*] - sync', checkEncoding, 'utf16le', 3, execaSync);90test('can pass encoding "latin1" to stdio[*] - sync', checkEncoding, 'latin1', 3, execaSync);91test('can pass encoding "ascii" to stdio[*] - sync', checkEncoding, 'ascii', 3, execaSync);92test('can pass encoding "hex" to stdio[*] - sync', checkEncoding, 'hex', 3, execaSync);93test('can pass encoding "base64" to stdio[*] - sync', checkEncoding, 'base64', 3, execaSync);94test('can pass encoding "base64url" to stdio[*] - sync', checkEncoding, 'base64url', 3, execaSync);9596// eslint-disable-next-line max-params97const testEncodingInput = async (t, input, expectedStdout, encoding, execaMethod) => {98 const {stdout} = await execaMethod('stdin.js', {input, encoding});99 t.deepEqual(stdout, expectedStdout);100};101102test('Can use string input', testEncodingInput, foobarString, foobarString, 'utf8', execa);103test('Can use Uint8Array input', testEncodingInput, foobarUint8Array, foobarString, 'utf8', execa);104test('Can use string input, encoding "buffer"', testEncodingInput, foobarString, foobarUint8Array, 'buffer', execa);105test('Can use Uint8Array input, encoding "buffer"', testEncodingInput, foobarUint8Array, foobarUint8Array, 'buffer', execa);106test('Can use string input, encoding "hex"', testEncodingInput, foobarString, foobarHex, 'hex', execa);107test('Can use Uint8Array input, encoding "hex"', testEncodingInput, foobarUint8Array, foobarHex, 'hex', execa);108test('Can use string input, sync', testEncodingInput, foobarString, foobarString, 'utf8', execaSync);109test('Can use Uint8Array input, sync', testEncodingInput, foobarUint8Array, foobarString, 'utf8', execaSync);110test('Can use string input, encoding "buffer", sync', testEncodingInput, foobarString, foobarUint8Array, 'buffer', execaSync);111test('Can use Uint8Array input, encoding "buffer", sync', testEncodingInput, foobarUint8Array, foobarUint8Array, 'buffer', execaSync);112test('Can use string input, encoding "hex", sync', testEncodingInput, foobarString, foobarHex, 'hex', execaSync);113test('Can use Uint8Array input, encoding "hex", sync', testEncodingInput, foobarUint8Array, foobarHex, 'hex', execaSync);114115const 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};121122test('Does not modify subprocess.std* encoding, "utf8"', testSubprocessEncoding, 'utf8');123test('Does not modify subprocess.std* encoding, "utf16le"', testSubprocessEncoding, 'utf16le');124test('Does not modify subprocess.std* encoding, "buffer"', testSubprocessEncoding, 'buffer');125test('Does not modify subprocess.std* encoding, "hex"', testSubprocessEncoding, 'hex');126test('Does not modify subprocess.std* encoding, "base64"', testSubprocessEncoding, 'base64');127test('Does not modify subprocess.std* encoding, "base64url"', testSubprocessEncoding, 'base64url');128test('Does not modify subprocess.std* encoding, "latin1"', testSubprocessEncoding, 'latin1');129test('Does not modify subprocess.std* encoding, "ascii"', testSubprocessEncoding, 'ascii');
deleted:test/stdio/encoding-ignored.js-92 removed
1import process from 'node:process';2import test from 'ava';3import {execa, execaSync} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';5import {outputObjectGenerator, addNoopGenerator} from '../helpers/generator.js';6import {foobarObject} from '../helpers/input.js';78setFixtureDir();910const 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};1718test('Other encodings work with transforms that return objects', testObjectMode, false, execa);19test('Other encodings work with transforms that return objects, noop transform', testObjectMode, true, execa);20test('Other encodings work with transforms that return objects, sync', testObjectMode, false, execaSync);21test('Other encodings work with transforms that return objects, noop transform, sync', testObjectMode, true, execaSync);2223// eslint-disable-next-line max-params24const testIgnoredEncoding = async (t, stdoutOption, isUndefined, options, execaMethod) => {25 const {stdout} = await execaMethod('empty.js', {stdout: stdoutOption, ...options});26 t.is(stdout === undefined, isUndefined);27};2829const base64Options = {encoding: 'base64'};30const linesOptions = {lines: true};31test('Is ignored with other encodings and "ignore"', testIgnoredEncoding, 'ignore', true, base64Options, execa);32test('Is ignored with other encodings and ["ignore"]', testIgnoredEncoding, ['ignore'], true, base64Options, execa);33test('Is ignored with other encodings and "ipc"', testIgnoredEncoding, 'ipc', true, base64Options, execa);34test('Is ignored with other encodings and ["ipc"]', testIgnoredEncoding, ['ipc'], true, base64Options, execa);35test('Is ignored with other encodings and "inherit"', testIgnoredEncoding, 'inherit', true, base64Options, execa);36test('Is ignored with other encodings and ["inherit"]', testIgnoredEncoding, ['inherit'], true, base64Options, execa);37test('Is ignored with other encodings and 1', testIgnoredEncoding, 1, true, base64Options, execa);38test('Is ignored with other encodings and [1]', testIgnoredEncoding, [1], true, base64Options, execa);39test('Is ignored with other encodings and process.stdout', testIgnoredEncoding, process.stdout, true, base64Options, execa);40test('Is ignored with other encodings and [process.stdout]', testIgnoredEncoding, [process.stdout], true, base64Options, execa);41test('Is not ignored with other encodings and "pipe"', testIgnoredEncoding, 'pipe', false, base64Options, execa);42test('Is not ignored with other encodings and ["pipe"]', testIgnoredEncoding, ['pipe'], false, base64Options, execa);43test('Is not ignored with other encodings and "overlapped"', testIgnoredEncoding, 'overlapped', false, base64Options, execa);44test('Is not ignored with other encodings and ["overlapped"]', testIgnoredEncoding, ['overlapped'], false, base64Options, execa);45test('Is not ignored with other encodings and ["inherit", "pipe"]', testIgnoredEncoding, ['inherit', 'pipe'], false, base64Options, execa);46test('Is not ignored with other encodings and undefined', testIgnoredEncoding, undefined, false, base64Options, execa);47test('Is not ignored with other encodings and null', testIgnoredEncoding, null, false, base64Options, execa);48test('Is ignored with "lines: true" and "ignore"', testIgnoredEncoding, 'ignore', true, linesOptions, execa);49test('Is ignored with "lines: true" and ["ignore"]', testIgnoredEncoding, ['ignore'], true, linesOptions, execa);50test('Is ignored with "lines: true" and "ipc"', testIgnoredEncoding, 'ipc', true, linesOptions, execa);51test('Is ignored with "lines: true" and ["ipc"]', testIgnoredEncoding, ['ipc'], true, linesOptions, execa);52test('Is ignored with "lines: true" and "inherit"', testIgnoredEncoding, 'inherit', true, linesOptions, execa);53test('Is ignored with "lines: true" and ["inherit"]', testIgnoredEncoding, ['inherit'], true, linesOptions, execa);54test('Is ignored with "lines: true" and 1', testIgnoredEncoding, 1, true, linesOptions, execa);55test('Is ignored with "lines: true" and [1]', testIgnoredEncoding, [1], true, linesOptions, execa);56test('Is ignored with "lines: true" and process.stdout', testIgnoredEncoding, process.stdout, true, linesOptions, execa);57test('Is ignored with "lines: true" and [process.stdout]', testIgnoredEncoding, [process.stdout], true, linesOptions, execa);58test('Is not ignored with "lines: true" and "pipe"', testIgnoredEncoding, 'pipe', false, linesOptions, execa);59test('Is not ignored with "lines: true" and ["pipe"]', testIgnoredEncoding, ['pipe'], false, linesOptions, execa);60test('Is not ignored with "lines: true" and "overlapped"', testIgnoredEncoding, 'overlapped', false, linesOptions, execa);61test('Is not ignored with "lines: true" and ["overlapped"]', testIgnoredEncoding, ['overlapped'], false, linesOptions, execa);62test('Is not ignored with "lines: true" and ["inherit", "pipe"]', testIgnoredEncoding, ['inherit', 'pipe'], false, linesOptions, execa);63test('Is not ignored with "lines: true" and undefined', testIgnoredEncoding, undefined, false, linesOptions, execa);64test('Is not ignored with "lines: true" and null', testIgnoredEncoding, null, false, linesOptions, execa);65test('Is ignored with "lines: true", other encodings and "ignore"', testIgnoredEncoding, 'ignore', true, {...base64Options, ...linesOptions}, execa);66test('Is not ignored with "lines: true", other encodings and "pipe"', testIgnoredEncoding, 'pipe', false, {...base64Options, ...linesOptions}, execa);67test('Is ignored with other encodings and "ignore", sync', testIgnoredEncoding, 'ignore', true, base64Options, execaSync);68test('Is ignored with other encodings and ["ignore"], sync', testIgnoredEncoding, ['ignore'], true, base64Options, execaSync);69test('Is ignored with other encodings and "inherit", sync', testIgnoredEncoding, 'inherit', true, base64Options, execaSync);70test('Is ignored with other encodings and ["inherit"], sync', testIgnoredEncoding, ['inherit'], true, base64Options, execaSync);71test('Is ignored with other encodings and 1, sync', testIgnoredEncoding, 1, true, base64Options, execaSync);72test('Is ignored with other encodings and [1], sync', testIgnoredEncoding, [1], true, base64Options, execaSync);73test('Is ignored with other encodings and process.stdout, sync', testIgnoredEncoding, process.stdout, true, base64Options, execaSync);74test('Is ignored with other encodings and [process.stdout], sync', testIgnoredEncoding, [process.stdout], true, base64Options, execaSync);75test('Is not ignored with other encodings and "pipe", sync', testIgnoredEncoding, 'pipe', false, base64Options, execaSync);76test('Is not ignored with other encodings and ["pipe"], sync', testIgnoredEncoding, ['pipe'], false, base64Options, execaSync);77test('Is not ignored with other encodings and undefined, sync', testIgnoredEncoding, undefined, false, base64Options, execaSync);78test('Is not ignored with other encodings and null, sync', testIgnoredEncoding, null, false, base64Options, execaSync);79test('Is ignored with "lines: true" and "ignore", sync', testIgnoredEncoding, 'ignore', true, linesOptions, execaSync);80test('Is ignored with "lines: true" and ["ignore"], sync', testIgnoredEncoding, ['ignore'], true, linesOptions, execaSync);81test('Is ignored with "lines: true" and "inherit", sync', testIgnoredEncoding, 'inherit', true, linesOptions, execaSync);82test('Is ignored with "lines: true" and ["inherit"], sync', testIgnoredEncoding, ['inherit'], true, linesOptions, execaSync);83test('Is ignored with "lines: true" and 1, sync', testIgnoredEncoding, 1, true, linesOptions, execaSync);84test('Is ignored with "lines: true" and [1], sync', testIgnoredEncoding, [1], true, linesOptions, execaSync);85test('Is ignored with "lines: true" and process.stdout, sync', testIgnoredEncoding, process.stdout, true, linesOptions, execaSync);86test('Is ignored with "lines: true" and [process.stdout], sync', testIgnoredEncoding, [process.stdout], true, linesOptions, execaSync);87test('Is not ignored with "lines: true" and "pipe", sync', testIgnoredEncoding, 'pipe', false, linesOptions, execaSync);88test('Is not ignored with "lines: true" and ["pipe"], sync', testIgnoredEncoding, ['pipe'], false, linesOptions, execaSync);89test('Is not ignored with "lines: true" and undefined, sync', testIgnoredEncoding, undefined, false, linesOptions, execaSync);90test('Is not ignored with "lines: true" and null, sync', testIgnoredEncoding, null, false, linesOptions, execaSync);91test('Is ignored with "lines: true", other encodings and "ignore", sync', testIgnoredEncoding, 'ignore', true, {...base64Options, ...linesOptions}, execaSync);92test('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
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {noopGenerator, getOutputsGenerator, addNoopGenerator} from '../helpers/generator.js';5import {multibyteChar, multibyteString, multibyteUint8Array, breakingLength, brokenSymbol} from '../helpers/encoding.js';67setFixtureDir();89const foobarArray = ['fo', 'ob', 'ar', '..'];1011const 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};2223test('Handle multibyte characters', testMultibyteCharacters, false, false, execa);24test('Handle multibyte characters, noop transform', testMultibyteCharacters, false, true, execa);25test('Handle multibyte characters, with objectMode', testMultibyteCharacters, true, false, execa);26test('Handle multibyte characters, with objectMode, noop transform', testMultibyteCharacters, true, true, execa);27test('Handle multibyte characters, sync', testMultibyteCharacters, false, false, execaSync);28test('Handle multibyte characters, noop transform, sync', testMultibyteCharacters, false, true, execaSync);29test('Handle multibyte characters, with objectMode, sync', testMultibyteCharacters, true, false, execaSync);30test('Handle multibyte characters, with objectMode, noop transform, sync', testMultibyteCharacters, true, true, execaSync);3132const 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};4142test('Generator handles multibyte characters with Uint8Array', testMultibyte, false, execa);43test('Generator handles multibyte characters with Uint8Array, objectMode', testMultibyte, true, execa);44test('Generator handles multibyte characters with Uint8Array, sync', testMultibyte, false, execaSync);45test('Generator handles multibyte characters with Uint8Array, objectMode, sync', testMultibyte, true, execaSync);4647const 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};5657test('Generator handles partial multibyte characters with Uint8Array', testMultibytePartial, false, execa);58test('Generator handles partial multibyte characters with Uint8Array, objectMode', testMultibytePartial, true, execa);59test('Generator handles partial multibyte characters with Uint8Array, sync', testMultibytePartial, false, execaSync);60test('Generator handles partial multibyte characters with Uint8Array, objectMode, sync', testMultibytePartial, true, execaSync);6162const 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};7172test('Generator handles output multibyte characters with Uint8Array', testMultibytePartialOutput, execa);73test('Generator handles output multibyte characters with Uint8Array, sync', testMultibytePartialOutput, execaSync);
deleted:test/stdio/encoding-transform.js-172 removed
1import {Buffer} from 'node:buffer';2import test from 'ava';3import {execa, execaSync} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';5import {getStdio} from '../helpers/stdio.js';6import {foobarString, foobarUint8Array, foobarBuffer, foobarObject} from '../helpers/input.js';7import {noopGenerator, getOutputGenerator} from '../helpers/generator.js';89setFixtureDir();1011const getTypeofGenerator = lines => (objectMode, binary) => ({12 * transform(line) {13 lines.push(Object.prototype.toString.call(line));14 yield '';15 },16 objectMode,17 binary,18});1920const assertTypeofChunk = (t, lines, expectedType) => {21 t.deepEqual(lines, [`[object ${expectedType}]`]);22};2324// eslint-disable-next-line max-params25const 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};3233test('First generator argument is string with default encoding, with string writes', testGeneratorFirstEncoding, foobarString, 'utf8', 'String', false, undefined);34test('First generator argument is string with default encoding, with Buffer writes', testGeneratorFirstEncoding, foobarBuffer, 'utf8', 'String', false, undefined);35test('First generator argument is string with default encoding, with Uint8Array writes', testGeneratorFirstEncoding, foobarUint8Array, 'utf8', 'String', false, undefined);36test('First generator argument is string with default encoding, with string writes, "binary: false"', testGeneratorFirstEncoding, foobarString, 'utf8', 'String', false, false);37test('First generator argument is Uint8Array with default encoding, with string writes, "binary: true"', testGeneratorFirstEncoding, foobarString, 'utf8', 'Uint8Array', false, true);38test('First generator argument is string with encoding "utf16le", with string writes', testGeneratorFirstEncoding, foobarString, 'utf16le', 'String', false, undefined);39test('First generator argument is string with encoding "utf16le", with Buffer writes', testGeneratorFirstEncoding, foobarBuffer, 'utf16le', 'String', false, undefined);40test('First generator argument is string with encoding "utf16le", with Uint8Array writes', testGeneratorFirstEncoding, foobarUint8Array, 'utf16le', 'String', false, undefined);41test('First generator argument is string with encoding "utf16le", with string writes, "binary: false"', testGeneratorFirstEncoding, foobarString, 'utf16le', 'String', false, false);42test('First generator argument is Uint8Array with encoding "utf16le", with string writes, "binary: true"', testGeneratorFirstEncoding, foobarString, 'utf16le', 'Uint8Array', false, true);43test('First generator argument is Uint8Array with encoding "buffer", with string writes', testGeneratorFirstEncoding, foobarString, 'buffer', 'Uint8Array', false, undefined);44test('First generator argument is Uint8Array with encoding "buffer", with Buffer writes', testGeneratorFirstEncoding, foobarBuffer, 'buffer', 'Uint8Array', false, undefined);45test('First generator argument is Uint8Array with encoding "buffer", with Uint8Array writes', testGeneratorFirstEncoding, foobarUint8Array, 'buffer', 'Uint8Array', false, undefined);46test('First generator argument is Uint8Array with encoding "buffer", with string writes, "binary: false"', testGeneratorFirstEncoding, foobarString, 'buffer', 'Uint8Array', false, false);47test('First generator argument is Uint8Array with encoding "buffer", with string writes, "binary: true"', testGeneratorFirstEncoding, foobarString, 'buffer', 'Uint8Array', false, true);48test('First generator argument is Uint8Array with encoding "hex", with string writes', testGeneratorFirstEncoding, foobarString, 'hex', 'Uint8Array', false, undefined);49test('First generator argument is Uint8Array with encoding "hex", with Buffer writes', testGeneratorFirstEncoding, foobarBuffer, 'hex', 'Uint8Array', false, undefined);50test('First generator argument is Uint8Array with encoding "hex", with Uint8Array writes', testGeneratorFirstEncoding, foobarUint8Array, 'hex', 'Uint8Array', false, undefined);51test('First generator argument is Uint8Array with encoding "hex", with string writes, "binary: false"', testGeneratorFirstEncoding, foobarString, 'hex', 'Uint8Array', false, false);52test('First generator argument is Uint8Array with encoding "hex", with string writes, "binary: true"', testGeneratorFirstEncoding, foobarString, 'hex', 'Uint8Array', false, true);53test('First generator argument can be string with objectMode', testGeneratorFirstEncoding, foobarString, 'utf8', 'String', true, undefined);54test('First generator argument can be string with objectMode, "binary: false"', testGeneratorFirstEncoding, foobarString, 'utf8', 'String', true, false);55test('First generator argument can be string with objectMode, "binary: true"', testGeneratorFirstEncoding, foobarString, 'utf8', 'String', true, true);56test('First generator argument can be objects with objectMode', testGeneratorFirstEncoding, foobarObject, 'utf8', 'Object', true, undefined);57test('First generator argument can be objects with objectMode, "binary: false"', testGeneratorFirstEncoding, foobarObject, 'utf8', 'Object', true, false);58test('First generator argument can be objects with objectMode, "binary: true"', testGeneratorFirstEncoding, foobarObject, 'utf8', 'Object', true, true);5960// eslint-disable-next-line max-params61const 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};6667test('First generator argument is string with default encoding, with string writes, sync', testGeneratorFirstEncodingSync, foobarString, 'utf8', 'String', false, undefined);68test('First generator argument is string with default encoding, with Uint8Array writes, sync', testGeneratorFirstEncodingSync, foobarUint8Array, 'utf8', 'String', false, undefined);69test('First generator argument is string with default encoding, with string writes, "binary: false", sync', testGeneratorFirstEncodingSync, foobarString, 'utf8', 'String', false, false);70test('First generator argument is Uint8Array with default encoding, with string writes, "binary: true", sync', testGeneratorFirstEncodingSync, foobarString, 'utf8', 'Uint8Array', false, true);71test('First generator argument is string with encoding "utf16le", with string writes, sync', testGeneratorFirstEncodingSync, foobarString, 'utf16le', 'String', false, undefined);72test('First generator argument is string with encoding "utf16le", with Uint8Array writes, sync', testGeneratorFirstEncodingSync, foobarUint8Array, 'utf16le', 'String', false, undefined);73test('First generator argument is string with encoding "utf16le", with string writes, "binary: false", sync', testGeneratorFirstEncodingSync, foobarString, 'utf16le', 'String', false, false);74test('First generator argument is Uint8Array with encoding "utf16le", with string writes, "binary: true", sync', testGeneratorFirstEncodingSync, foobarString, 'utf16le', 'Uint8Array', false, true);75test('First generator argument is Uint8Array with encoding "buffer", with string writes, sync', testGeneratorFirstEncodingSync, foobarString, 'buffer', 'Uint8Array', false, undefined);76test('First generator argument is Uint8Array with encoding "buffer", with Uint8Array writes, sync', testGeneratorFirstEncodingSync, foobarUint8Array, 'buffer', 'Uint8Array', false, undefined);77test('First generator argument is Uint8Array with encoding "buffer", with string writes, "binary: false", sync', testGeneratorFirstEncodingSync, foobarString, 'buffer', 'Uint8Array', false, false);78test('First generator argument is Uint8Array with encoding "buffer", with string writes, "binary: true", sync', testGeneratorFirstEncodingSync, foobarString, 'buffer', 'Uint8Array', false, true);79test('First generator argument is Uint8Array with encoding "hex", with string writes, sync', testGeneratorFirstEncodingSync, foobarString, 'hex', 'Uint8Array', false, undefined);80test('First generator argument is Uint8Array with encoding "hex", with Uint8Array writes, sync', testGeneratorFirstEncodingSync, foobarUint8Array, 'hex', 'Uint8Array', false, undefined);81test('First generator argument is Uint8Array with encoding "hex", with string writes, "binary: false", sync', testGeneratorFirstEncodingSync, foobarString, 'hex', 'Uint8Array', false, false);82test('First generator argument is Uint8Array with encoding "hex", with string writes, "binary: true", sync', testGeneratorFirstEncodingSync, foobarString, 'hex', 'Uint8Array', false, true);83test('First generator argument can be string with objectMode, sync', testGeneratorFirstEncodingSync, foobarString, 'utf8', 'String', true, undefined);84test('First generator argument can be string with objectMode, "binary: false", sync', testGeneratorFirstEncodingSync, foobarString, 'utf8', 'String', true, false);85test('First generator argument can be string with objectMode, "binary: true", sync', testGeneratorFirstEncodingSync, foobarString, 'utf8', 'String', true, true);86test('First generator argument can be objects with objectMode, sync', testGeneratorFirstEncodingSync, foobarObject, 'utf8', 'Object', true, undefined);87test('First generator argument can be objects with objectMode, "binary: false", sync', testGeneratorFirstEncodingSync, foobarObject, 'utf8', 'Object', true, false);88test('First generator argument can be objects with objectMode, "binary: true", sync', testGeneratorFirstEncodingSync, foobarObject, 'utf8', 'Object', true, true);8990const 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};9798test('Write call encoding "utf8" is ignored with objectMode', testEncodingIgnored, 'utf8');99test('Write call encoding "utf16le" is ignored with objectMode', testEncodingIgnored, 'utf16le');100test('Write call encoding "hex" is ignored with objectMode', testEncodingIgnored, 'hex');101test('Write call encoding "base64" is ignored with objectMode', testEncodingIgnored, 'base64');102103// eslint-disable-next-line max-params104const 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};115116test('Next generator argument is string with default encoding, with string writes', testGeneratorNextEncoding, foobarString, 'utf8', false, false, 'String', execa);117test('Next generator argument is string with default encoding, with string writes, objectMode first', testGeneratorNextEncoding, foobarString, 'utf8', true, false, 'String', execa);118test('Next generator argument is string with default encoding, with string writes, objectMode both', testGeneratorNextEncoding, foobarString, 'utf8', true, true, 'String', execa);119test('Next generator argument is string with default encoding, with Uint8Array writes', testGeneratorNextEncoding, foobarUint8Array, 'utf8', false, false, 'String', execa);120test('Next generator argument is Uint8Array with default encoding, with Uint8Array writes, objectMode first', testGeneratorNextEncoding, foobarUint8Array, 'utf8', true, false, 'Uint8Array', execa);121test('Next generator argument is string with default encoding, with Uint8Array writes, objectMode both', testGeneratorNextEncoding, foobarUint8Array, 'utf8', true, true, 'Uint8Array', execa);122test('Next generator argument is string with encoding "utf16le", with string writes', testGeneratorNextEncoding, foobarString, 'utf16le', false, false, 'String', execa);123test('Next generator argument is string with encoding "utf16le",, with string writes, objectMode first', testGeneratorNextEncoding, foobarString, 'utf16le', true, false, 'String', execa);124test('Next generator argument is string with encoding "utf16le",, with string writes, objectMode both', testGeneratorNextEncoding, foobarString, 'utf16le', true, true, 'String', execa);125test('Next generator argument is string with encoding "utf16le",, with Uint8Array writes', testGeneratorNextEncoding, foobarUint8Array, 'utf16le', false, false, 'String', execa);126test('Next generator argument is Uint8Array with encoding "utf16le",, with Uint8Array writes, objectMode first', testGeneratorNextEncoding, foobarUint8Array, 'utf16le', true, false, 'Uint8Array', execa);127test('Next generator argument is string with encoding "utf16le",, with Uint8Array writes, objectMode both', testGeneratorNextEncoding, foobarUint8Array, 'utf16le', true, true, 'Uint8Array', execa);128test('Next generator argument is Uint8Array with encoding "buffer", with string writes', testGeneratorNextEncoding, foobarString, 'buffer', false, false, 'Uint8Array', execa);129test('Next generator argument is string with encoding "buffer", with string writes, objectMode first', testGeneratorNextEncoding, foobarString, 'buffer', true, false, 'String', execa);130test('Next generator argument is string with encoding "buffer", with string writes, objectMode both', testGeneratorNextEncoding, foobarString, 'buffer', true, true, 'String', execa);131test('Next generator argument is Uint8Array with encoding "buffer", with Uint8Array writes', testGeneratorNextEncoding, foobarUint8Array, 'buffer', false, false, 'Uint8Array', execa);132test('Next generator argument is Uint8Array with encoding "buffer", with Uint8Array writes, objectMode first', testGeneratorNextEncoding, foobarUint8Array, 'buffer', true, false, 'Uint8Array', execa);133test('Next generator argument is Uint8Array with encoding "buffer", with Uint8Array writes, objectMode both', testGeneratorNextEncoding, foobarUint8Array, 'buffer', true, true, 'Uint8Array', execa);134test('Next generator argument is Uint8Array with encoding "hex", with string writes', testGeneratorNextEncoding, foobarString, 'hex', false, false, 'Uint8Array', execa);135test('Next generator argument is Uint8Array with encoding "hex", with Uint8Array writes', testGeneratorNextEncoding, foobarUint8Array, 'hex', false, false, 'Uint8Array', execa);136test('Next generator argument is object with default encoding, with object writes, objectMode first', testGeneratorNextEncoding, foobarObject, 'utf8', true, false, 'Object', execa);137test('Next generator argument is object with default encoding, with object writes, objectMode both', testGeneratorNextEncoding, foobarObject, 'utf8', true, true, 'Object', execa);138test('Next generator argument is string with default encoding, with string writes, sync', testGeneratorNextEncoding, foobarString, 'utf8', false, false, 'String', execaSync);139test('Next generator argument is string with default encoding, with string writes, objectMode first, sync', testGeneratorNextEncoding, foobarString, 'utf8', true, false, 'String', execaSync);140test('Next generator argument is string with default encoding, with string writes, objectMode both, sync', testGeneratorNextEncoding, foobarString, 'utf8', true, true, 'String', execaSync);141test('Next generator argument is string with default encoding, with Uint8Array writes, sync', testGeneratorNextEncoding, foobarUint8Array, 'utf8', false, false, 'String', execaSync);142test('Next generator argument is Uint8Array with default encoding, with Uint8Array writes, objectMode first, sync', testGeneratorNextEncoding, foobarUint8Array, 'utf8', true, false, 'Uint8Array', execaSync);143test('Next generator argument is string with default encoding, with Uint8Array writes, objectMode both, sync', testGeneratorNextEncoding, foobarUint8Array, 'utf8', true, true, 'Uint8Array', execaSync);144test('Next generator argument is string with encoding "utf16le", with string writes, sync', testGeneratorNextEncoding, foobarString, 'utf16le', false, false, 'String', execaSync);145test('Next generator argument is string with encoding "utf16le",, with string writes, objectMode first, sync', testGeneratorNextEncoding, foobarString, 'utf16le', true, false, 'String', execaSync);146test('Next generator argument is string with encoding "utf16le",, with string writes, objectMode both, sync', testGeneratorNextEncoding, foobarString, 'utf16le', true, true, 'String', execaSync);147test('Next generator argument is string with encoding "utf16le",, with Uint8Array writes, sync', testGeneratorNextEncoding, foobarUint8Array, 'utf16le', false, false, 'String', execaSync);148test('Next generator argument is Uint8Array with encoding "utf16le",, with Uint8Array writes, objectMode first, sync', testGeneratorNextEncoding, foobarUint8Array, 'utf16le', true, false, 'Uint8Array', execaSync);149test('Next generator argument is string with encoding "utf16le",, with Uint8Array writes, objectMode both, sync', testGeneratorNextEncoding, foobarUint8Array, 'utf16le', true, true, 'Uint8Array', execaSync);150test('Next generator argument is Uint8Array with encoding "buffer", with string writes, sync', testGeneratorNextEncoding, foobarString, 'buffer', false, false, 'Uint8Array', execaSync);151test('Next generator argument is string with encoding "buffer", with string writes, objectMode first, sync', testGeneratorNextEncoding, foobarString, 'buffer', true, false, 'String', execaSync);152test('Next generator argument is string with encoding "buffer", with string writes, objectMode both, sync', testGeneratorNextEncoding, foobarString, 'buffer', true, true, 'String', execaSync);153test('Next generator argument is Uint8Array with encoding "buffer", with Uint8Array writes, sync', testGeneratorNextEncoding, foobarUint8Array, 'buffer', false, false, 'Uint8Array', execaSync);154test('Next generator argument is Uint8Array with encoding "buffer", with Uint8Array writes, objectMode first, sync', testGeneratorNextEncoding, foobarUint8Array, 'buffer', true, false, 'Uint8Array', execaSync);155test('Next generator argument is Uint8Array with encoding "buffer", with Uint8Array writes, objectMode both, sync', testGeneratorNextEncoding, foobarUint8Array, 'buffer', true, true, 'Uint8Array', execaSync);156test('Next generator argument is Uint8Array with encoding "hex", with string writes, sync', testGeneratorNextEncoding, foobarString, 'hex', false, false, 'Uint8Array', execaSync);157test('Next generator argument is Uint8Array with encoding "hex", with Uint8Array writes, sync', testGeneratorNextEncoding, foobarUint8Array, 'hex', false, false, 'Uint8Array', execaSync);158test('Next generator argument is object with default encoding, with object writes, objectMode first, sync', testGeneratorNextEncoding, foobarObject, 'utf8', true, false, 'Object', execaSync);159test('Next generator argument is object with default encoding, with object writes, objectMode both, sync', testGeneratorNextEncoding, foobarObject, 'utf8', true, true, 'Object', execaSync);160161const 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};166167test('The first generator with result.stdout does not receive an object argument even in objectMode', testFirstOutputGeneratorArgument, 1, execa);168test('The first generator with result.stderr does not receive an object argument even in objectMode', testFirstOutputGeneratorArgument, 2, execa);169test('The first generator with result.stdio[*] does not receive an object argument even in objectMode', testFirstOutputGeneratorArgument, 3, execa);170test('The first generator with result.stdout does not receive an object argument even in objectMode, sync', testFirstOutputGeneratorArgument, 1, execaSync);171test('The first generator with result.stderr does not receive an object argument even in objectMode, sync', testFirstOutputGeneratorArgument, 2, execaSync);172test('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
1import {Buffer} from 'node:buffer';2import test from 'ava';3import {execa, execaSync} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';5import {foobarString, foobarUint8Array} from '../helpers/input.js';6import {getOutputGenerator, convertTransformToFinal} from '../helpers/generator.js';78setFixtureDir();910// eslint-disable-next-line max-params11const 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};2223test('Generator can return string with default encoding', testGeneratorReturnType, foobarString, 'utf8', true, false, false, execa);24test('Generator can return Uint8Array with default encoding', testGeneratorReturnType, foobarUint8Array, 'utf8', true, false, false, execa);25test('Generator can return string with encoding "utf16le"', testGeneratorReturnType, foobarString, 'utf16le', true, false, false, execa);26test('Generator can return Uint8Array with encoding "utf16le"', testGeneratorReturnType, foobarUint8Array, 'utf16le', true, false, false, execa);27test('Generator can return string with encoding "buffer"', testGeneratorReturnType, foobarString, 'buffer', true, false, false, execa);28test('Generator can return Uint8Array with encoding "buffer"', testGeneratorReturnType, foobarUint8Array, 'buffer', true, false, false, execa);29test('Generator can return string with encoding "hex"', testGeneratorReturnType, foobarString, 'hex', true, false, false, execa);30test('Generator can return Uint8Array with encoding "hex"', testGeneratorReturnType, foobarUint8Array, 'hex', true, false, false, execa);31test('Generator can return string with default encoding, failure', testGeneratorReturnType, foobarString, 'utf8', false, false, false, execa);32test('Generator can return Uint8Array with default encoding, failure', testGeneratorReturnType, foobarUint8Array, 'utf8', false, false, false, execa);33test('Generator can return string with encoding "utf16le", failure', testGeneratorReturnType, foobarString, 'utf16le', false, false, false, execa);34test('Generator can return Uint8Array with encoding "utf16le", failure', testGeneratorReturnType, foobarUint8Array, 'utf16le', false, false, false, execa);35test('Generator can return string with encoding "buffer", failure', testGeneratorReturnType, foobarString, 'buffer', false, false, false, execa);36test('Generator can return Uint8Array with encoding "buffer", failure', testGeneratorReturnType, foobarUint8Array, 'buffer', false, false, false, execa);37test('Generator can return string with encoding "hex", failure', testGeneratorReturnType, foobarString, 'hex', false, false, false, execa);38test('Generator can return Uint8Array with encoding "hex", failure', testGeneratorReturnType, foobarUint8Array, 'hex', false, false, false, execa);39test('Generator can return string with default encoding, objectMode', testGeneratorReturnType, foobarString, 'utf8', true, true, false, execa);40test('Generator can return Uint8Array with default encoding, objectMode', testGeneratorReturnType, foobarUint8Array, 'utf8', true, true, false, execa);41test('Generator can return string with encoding "utf16le", objectMode', testGeneratorReturnType, foobarString, 'utf16le', true, true, false, execa);42test('Generator can return Uint8Array with encoding "utf16le", objectMode', testGeneratorReturnType, foobarUint8Array, 'utf16le', true, true, false, execa);43test('Generator can return string with encoding "buffer", objectMode', testGeneratorReturnType, foobarString, 'buffer', true, true, false, execa);44test('Generator can return Uint8Array with encoding "buffer", objectMode', testGeneratorReturnType, foobarUint8Array, 'buffer', true, true, false, execa);45test('Generator can return string with encoding "hex", objectMode', testGeneratorReturnType, foobarString, 'hex', true, true, false, execa);46test('Generator can return Uint8Array with encoding "hex", objectMode', testGeneratorReturnType, foobarUint8Array, 'hex', true, true, false, execa);47test('Generator can return string with default encoding, objectMode, failure', testGeneratorReturnType, foobarString, 'utf8', false, true, false, execa);48test('Generator can return Uint8Array with default encoding, objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'utf8', false, true, false, execa);49test('Generator can return string with encoding "utf16le", objectMode, failure', testGeneratorReturnType, foobarString, 'utf16le', false, true, false, execa);50test('Generator can return Uint8Array with encoding "utf16le", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'utf16le', false, true, false, execa);51test('Generator can return string with encoding "buffer", objectMode, failure', testGeneratorReturnType, foobarString, 'buffer', false, true, false, execa);52test('Generator can return Uint8Array with encoding "buffer", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'buffer', false, true, false, execa);53test('Generator can return string with encoding "hex", objectMode, failure', testGeneratorReturnType, foobarString, 'hex', false, true, false, execa);54test('Generator can return Uint8Array with encoding "hex", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'hex', false, true, false, execa);55test('Generator can return final string with default encoding', testGeneratorReturnType, foobarString, 'utf8', true, false, true, execa);56test('Generator can return final Uint8Array with default encoding', testGeneratorReturnType, foobarUint8Array, 'utf8', true, false, true, execa);57test('Generator can return final string with encoding "utf16le"', testGeneratorReturnType, foobarString, 'utf16le', true, false, true, execa);58test('Generator can return final Uint8Array with encoding "utf16le"', testGeneratorReturnType, foobarUint8Array, 'utf16le', true, false, true, execa);59test('Generator can return final string with encoding "buffer"', testGeneratorReturnType, foobarString, 'buffer', true, false, true, execa);60test('Generator can return final Uint8Array with encoding "buffer"', testGeneratorReturnType, foobarUint8Array, 'buffer', true, false, true, execa);61test('Generator can return final string with encoding "hex"', testGeneratorReturnType, foobarString, 'hex', true, false, true, execa);62test('Generator can return final Uint8Array with encoding "hex"', testGeneratorReturnType, foobarUint8Array, 'hex', true, false, true, execa);63test('Generator can return final string with default encoding, failure', testGeneratorReturnType, foobarString, 'utf8', false, false, true, execa);64test('Generator can return final Uint8Array with default encoding, failure', testGeneratorReturnType, foobarUint8Array, 'utf8', false, false, true, execa);65test('Generator can return final string with encoding "utf16le", failure', testGeneratorReturnType, foobarString, 'utf16le', false, false, true, execa);66test('Generator can return final Uint8Array with encoding "utf16le", failure', testGeneratorReturnType, foobarUint8Array, 'utf16le', false, false, true, execa);67test('Generator can return final string with encoding "buffer", failure', testGeneratorReturnType, foobarString, 'buffer', false, false, true, execa);68test('Generator can return final Uint8Array with encoding "buffer", failure', testGeneratorReturnType, foobarUint8Array, 'buffer', false, false, true, execa);69test('Generator can return final string with encoding "hex", failure', testGeneratorReturnType, foobarString, 'hex', false, false, true, execa);70test('Generator can return final Uint8Array with encoding "hex", failure', testGeneratorReturnType, foobarUint8Array, 'hex', false, false, true, execa);71test('Generator can return final string with default encoding, objectMode', testGeneratorReturnType, foobarString, 'utf8', true, true, true, execa);72test('Generator can return final Uint8Array with default encoding, objectMode', testGeneratorReturnType, foobarUint8Array, 'utf8', true, true, true, execa);73test('Generator can return final string with encoding "utf16le", objectMode', testGeneratorReturnType, foobarString, 'utf16le', true, true, true, execa);74test('Generator can return final Uint8Array with encoding "utf16le", objectMode', testGeneratorReturnType, foobarUint8Array, 'utf16le', true, true, true, execa);75test('Generator can return final string with encoding "buffer", objectMode', testGeneratorReturnType, foobarString, 'buffer', true, true, true, execa);76test('Generator can return final Uint8Array with encoding "buffer", objectMode', testGeneratorReturnType, foobarUint8Array, 'buffer', true, true, true, execa);77test('Generator can return final string with encoding "hex", objectMode', testGeneratorReturnType, foobarString, 'hex', true, true, true, execa);78test('Generator can return final Uint8Array with encoding "hex", objectMode', testGeneratorReturnType, foobarUint8Array, 'hex', true, true, true, execa);79test('Generator can return final string with default encoding, objectMode, failure', testGeneratorReturnType, foobarString, 'utf8', false, true, true, execa);80test('Generator can return final Uint8Array with default encoding, objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'utf8', false, true, true, execa);81test('Generator can return final string with encoding "utf16le", objectMode, failure', testGeneratorReturnType, foobarString, 'utf16le', false, true, true, execa);82test('Generator can return final Uint8Array with encoding "utf16le", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'utf16le', false, true, true, execa);83test('Generator can return final string with encoding "buffer", objectMode, failure', testGeneratorReturnType, foobarString, 'buffer', false, true, true, execa);84test('Generator can return final Uint8Array with encoding "buffer", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'buffer', false, true, true, execa);85test('Generator can return final string with encoding "hex", objectMode, failure', testGeneratorReturnType, foobarString, 'hex', false, true, true, execa);86test('Generator can return final Uint8Array with encoding "hex", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'hex', false, true, true, execa);87test('Generator can return string with default encoding, sync', testGeneratorReturnType, foobarString, 'utf8', true, false, false, execaSync);88test('Generator can return Uint8Array with default encoding, sync', testGeneratorReturnType, foobarUint8Array, 'utf8', true, false, false, execaSync);89test('Generator can return string with encoding "utf16le", sync', testGeneratorReturnType, foobarString, 'utf16le', true, false, false, execaSync);90test('Generator can return Uint8Array with encoding "utf16le", sync', testGeneratorReturnType, foobarUint8Array, 'utf16le', true, false, false, execaSync);91test('Generator can return string with encoding "buffer", sync', testGeneratorReturnType, foobarString, 'buffer', true, false, false, execaSync);92test('Generator can return Uint8Array with encoding "buffer", sync', testGeneratorReturnType, foobarUint8Array, 'buffer', true, false, false, execaSync);93test('Generator can return string with encoding "hex", sync', testGeneratorReturnType, foobarString, 'hex', true, false, false, execaSync);94test('Generator can return Uint8Array with encoding "hex", sync', testGeneratorReturnType, foobarUint8Array, 'hex', true, false, false, execaSync);95test('Generator can return string with default encoding, failure, sync', testGeneratorReturnType, foobarString, 'utf8', false, false, false, execaSync);96test('Generator can return Uint8Array with default encoding, failure, sync', testGeneratorReturnType, foobarUint8Array, 'utf8', false, false, false, execaSync);97test('Generator can return string with encoding "utf16le", failure, sync', testGeneratorReturnType, foobarString, 'utf16le', false, false, false, execaSync);98test('Generator can return Uint8Array with encoding "utf16le", failure, sync', testGeneratorReturnType, foobarUint8Array, 'utf16le', false, false, false, execaSync);99test('Generator can return string with encoding "buffer", failure, sync', testGeneratorReturnType, foobarString, 'buffer', false, false, false, execaSync);100test('Generator can return Uint8Array with encoding "buffer", failure, sync', testGeneratorReturnType, foobarUint8Array, 'buffer', false, false, false, execaSync);101test('Generator can return string with encoding "hex", failure, sync', testGeneratorReturnType, foobarString, 'hex', false, false, false, execaSync);102test('Generator can return Uint8Array with encoding "hex", failure, sync', testGeneratorReturnType, foobarUint8Array, 'hex', false, false, false, execaSync);103test('Generator can return string with default encoding, objectMode, sync', testGeneratorReturnType, foobarString, 'utf8', true, true, false, execaSync);104test('Generator can return Uint8Array with default encoding, objectMode, sync', testGeneratorReturnType, foobarUint8Array, 'utf8', true, true, false, execaSync);105test('Generator can return string with encoding "utf16le", objectMode, sync', testGeneratorReturnType, foobarString, 'utf16le', true, true, false, execaSync);106test('Generator can return Uint8Array with encoding "utf16le", objectMode, sync', testGeneratorReturnType, foobarUint8Array, 'utf16le', true, true, false, execaSync);107test('Generator can return string with encoding "buffer", objectMode, sync', testGeneratorReturnType, foobarString, 'buffer', true, true, false, execaSync);108test('Generator can return Uint8Array with encoding "buffer", objectMode, sync', testGeneratorReturnType, foobarUint8Array, 'buffer', true, true, false, execaSync);109test('Generator can return string with encoding "hex", objectMode, sync', testGeneratorReturnType, foobarString, 'hex', true, true, false, execaSync);110test('Generator can return Uint8Array with encoding "hex", objectMode, sync', testGeneratorReturnType, foobarUint8Array, 'hex', true, true, false, execaSync);111test('Generator can return string with default encoding, objectMode, failure, sync', testGeneratorReturnType, foobarString, 'utf8', false, true, false, execaSync);112test('Generator can return Uint8Array with default encoding, objectMode, failure, sync', testGeneratorReturnType, foobarUint8Array, 'utf8', false, true, false, execaSync);113test('Generator can return string with encoding "utf16le", objectMode, failure, sync', testGeneratorReturnType, foobarString, 'utf16le', false, true, false, execaSync);114test('Generator can return Uint8Array with encoding "utf16le", objectMode, failure, sync', testGeneratorReturnType, foobarUint8Array, 'utf16le', false, true, false, execaSync);115test('Generator can return string with encoding "buffer", objectMode, failure, sync', testGeneratorReturnType, foobarString, 'buffer', false, true, false, execaSync);116test('Generator can return Uint8Array with encoding "buffer", objectMode, failure, sync', testGeneratorReturnType, foobarUint8Array, 'buffer', false, true, false, execaSync);117test('Generator can return string with encoding "hex", objectMode, failure, sync', testGeneratorReturnType, foobarString, 'hex', false, true, false, execaSync);118test('Generator can return Uint8Array with encoding "hex", objectMode, failure, sync', testGeneratorReturnType, foobarUint8Array, 'hex', false, true, false, execaSync);119test('Generator can return final string with default encoding, sync', testGeneratorReturnType, foobarString, 'utf8', true, false, true, execaSync);120test('Generator can return final Uint8Array with default encoding, sync', testGeneratorReturnType, foobarUint8Array, 'utf8', true, false, true, execaSync);121test('Generator can return final string with encoding "utf16le", sync', testGeneratorReturnType, foobarString, 'utf16le', true, false, true, execaSync);122test('Generator can return final Uint8Array with encoding "utf16le", sync', testGeneratorReturnType, foobarUint8Array, 'utf16le', true, false, true, execaSync);123test('Generator can return final string with encoding "buffer", sync', testGeneratorReturnType, foobarString, 'buffer', true, false, true, execaSync);124test('Generator can return final Uint8Array with encoding "buffer", sync', testGeneratorReturnType, foobarUint8Array, 'buffer', true, false, true, execaSync);125test('Generator can return final string with encoding "hex", sync', testGeneratorReturnType, foobarString, 'hex', true, false, true, execaSync);126test('Generator can return final Uint8Array with encoding "hex", sync', testGeneratorReturnType, foobarUint8Array, 'hex', true, false, true, execaSync);127test('Generator can return final string with default encoding, failure, sync', testGeneratorReturnType, foobarString, 'utf8', false, false, true, execaSync);128test('Generator can return final Uint8Array with default encoding, failure, sync', testGeneratorReturnType, foobarUint8Array, 'utf8', false, false, true, execaSync);129test('Generator can return final string with encoding "utf16le", failure, sync', testGeneratorReturnType, foobarString, 'utf16le', false, false, true, execaSync);130test('Generator can return final Uint8Array with encoding "utf16le", failure, sync', testGeneratorReturnType, foobarUint8Array, 'utf16le', false, false, true, execaSync);131test('Generator can return final string with encoding "buffer", failure, sync', testGeneratorReturnType, foobarString, 'buffer', false, false, true, execaSync);132test('Generator can return final Uint8Array with encoding "buffer", failure, sync', testGeneratorReturnType, foobarUint8Array, 'buffer', false, false, true, execaSync);133test('Generator can return final string with encoding "hex", failure, sync', testGeneratorReturnType, foobarString, 'hex', false, false, true, execaSync);134test('Generator can return final Uint8Array with encoding "hex", failure, sync', testGeneratorReturnType, foobarUint8Array, 'hex', false, false, true, execaSync);135test('Generator can return final string with default encoding, objectMode, sync', testGeneratorReturnType, foobarString, 'utf8', true, true, true, execaSync);136test('Generator can return final Uint8Array with default encoding, objectMode, sync', testGeneratorReturnType, foobarUint8Array, 'utf8', true, true, true, execaSync);137test('Generator can return final string with encoding "utf16le", objectMode, sync', testGeneratorReturnType, foobarString, 'utf16le', true, true, true, execaSync);138test('Generator can return final Uint8Array with encoding "utf16le", objectMode, sync', testGeneratorReturnType, foobarUint8Array, 'utf16le', true, true, true, execaSync);139test('Generator can return final string with encoding "buffer", objectMode, sync', testGeneratorReturnType, foobarString, 'buffer', true, true, true, execaSync);140test('Generator can return final Uint8Array with encoding "buffer", objectMode, sync', testGeneratorReturnType, foobarUint8Array, 'buffer', true, true, true, execaSync);141test('Generator can return final string with encoding "hex", objectMode, sync', testGeneratorReturnType, foobarString, 'hex', true, true, true, execaSync);142test('Generator can return final Uint8Array with encoding "hex", objectMode, sync', testGeneratorReturnType, foobarUint8Array, 'hex', true, true, true, execaSync);143test('Generator can return final string with default encoding, objectMode, failure, sync', testGeneratorReturnType, foobarString, 'utf8', false, true, true, execaSync);144test('Generator can return final Uint8Array with default encoding, objectMode, failure, sync', testGeneratorReturnType, foobarUint8Array, 'utf8', false, true, true, execaSync);145test('Generator can return final string with encoding "utf16le", objectMode, failure, sync', testGeneratorReturnType, foobarString, 'utf16le', false, true, true, execaSync);146test('Generator can return final Uint8Array with encoding "utf16le", objectMode, failure, sync', testGeneratorReturnType, foobarUint8Array, 'utf16le', false, true, true, execaSync);147test('Generator can return final string with encoding "buffer", objectMode, failure, sync', testGeneratorReturnType, foobarString, 'buffer', false, true, true, execaSync);148test('Generator can return final Uint8Array with encoding "buffer", objectMode, failure, sync', testGeneratorReturnType, foobarUint8Array, 'buffer', false, true, true, execaSync);149test('Generator can return final string with encoding "hex", objectMode, failure, sync', testGeneratorReturnType, foobarString, 'hex', false, true, true, execaSync);150test('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
1import test from 'ava';2import {execaSync} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {getStdio} from '../helpers/stdio.js';56setFixtureDir();78const getFd3InputMessage = type => `not \`stdio[3]\`, can be ${type}`;910const testFd3InputSync = (t, stdioOption, expectedMessage) => {11 const {message} = t.throws(() => {12 execaSync('empty.js', getStdio(3, stdioOption));13 });14 t.true(message.includes(expectedMessage));15};1617test('Cannot use Uint8Array with stdio[*], sync', testFd3InputSync, new Uint8Array(), getFd3InputMessage('a Uint8Array'));18test('Cannot use iterable with stdio[*], sync', testFd3InputSync, [[]], getFd3InputMessage('an iterable'));
deleted:test/stdio/input.js-43 removed
1import {Writable} from 'node:stream';2import test from 'ava';3import {execa, execaSync} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';5import {runExeca, runExecaSync, runScript, runScriptSync} from '../helpers/run.js';6import {foobarUint8Array, foobarBuffer, foobarArrayBuffer, foobarUint16Array, foobarDataView} from '../helpers/input.js';78setFixtureDir();910const testInput = async (t, input, execaMethod) => {11 const {stdout} = await execaMethod('stdin.js', {input});12 t.is(stdout, 'foobar');13};1415test('input option can be a String', testInput, 'foobar', runExeca);16test('input option can be a Uint8Array', testInput, foobarUint8Array, runExeca);17test('input option can be a String - sync', testInput, 'foobar', runExecaSync);18test('input option can be a Uint8Array - sync', testInput, foobarUint8Array, runExecaSync);19test('input option can be used with $', testInput, 'foobar', runScript);20test('input option can be used with $.sync', testInput, 'foobar', runScriptSync);2122const testInvalidInput = async (t, input, execaMethod) => {23 t.throws(() => {24 execaMethod('empty.js', {input});25 }, {message: /a string, a Uint8Array/});26};2728test('input option cannot be a Buffer', testInvalidInput, foobarBuffer, execa);29test('input option cannot be an ArrayBuffer', testInvalidInput, foobarArrayBuffer, execa);30test('input option cannot be a DataView', testInvalidInput, foobarDataView, execa);31test('input option cannot be a Uint16Array', testInvalidInput, foobarUint16Array, execa);32test('input option cannot be 0', testInvalidInput, 0, execa);33test('input option cannot be false', testInvalidInput, false, execa);34test('input option cannot be null', testInvalidInput, null, execa);35test('input option cannot be a non-Readable stream', testInvalidInput, new Writable(), execa);36test('input option cannot be a Buffer - sync', testInvalidInput, foobarBuffer, execaSync);37test('input option cannot be an ArrayBuffer - sync', testInvalidInput, foobarArrayBuffer, execaSync);38test('input option cannot be a DataView - sync', testInvalidInput, foobarDataView, execaSync);39test('input option cannot be a Uint16Array - sync', testInvalidInput, foobarUint16Array, execaSync);40test('input option cannot be 0 - sync', testInvalidInput, 0, execaSync);41test('input option cannot be false - sync', testInvalidInput, false, execaSync);42test('input option cannot be null - sync', testInvalidInput, null, execaSync);43test('input option cannot be a non-Readable stream - sync', testInvalidInput, new Writable(), execaSync);
deleted:test/stdio/normalize-transform.js-55 removed
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {foobarString, foobarUppercase, foobarUint8Array} from '../helpers/input.js';5import {casedSuffix} from '../helpers/generator.js';6import {generatorsMap} from '../helpers/map.js';78setFixtureDir();910const 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};1718test('Can use multiple generators as input', testAppendInput, false, 'generator', execa);19test('Can use multiple generators as input, reversed', testAppendInput, true, 'generator', execa);20test('Can use multiple generators as input, sync', testAppendInput, false, 'generator', execaSync);21test('Can use multiple generators as input, reversed, sync', testAppendInput, true, 'generator', execaSync);22test('Can use multiple duplexes as input', testAppendInput, false, 'duplex', execa);23test('Can use multiple duplexes as input, reversed', testAppendInput, true, 'duplex', execa);24test('Can use multiple webTransforms as input', testAppendInput, false, 'webTransform', execa);25test('Can use multiple webTransforms as input, reversed', testAppendInput, true, 'webTransform', execa);2627const 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};3435test('Can use multiple generators as output', testAppendOutput, false, 'generator', execa);36test('Can use multiple generators as output, reversed', testAppendOutput, true, 'generator', execa);37test('Can use multiple generators as output, sync', testAppendOutput, false, 'generator', execaSync);38test('Can use multiple generators as output, reversed, sync', testAppendOutput, true, 'generator', execaSync);39test('Can use multiple duplexes as output', testAppendOutput, false, 'duplex', execa);40test('Can use multiple duplexes as output, reversed', testAppendOutput, true, 'duplex', execa);41test('Can use multiple webTransforms as output', testAppendOutput, false, 'webTransform', execa);42test('Can use multiple webTransforms as output, reversed', testAppendOutput, true, 'webTransform', execa);4344const 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};4950test('Can pass generators with an options plain object', testGeneratorSyntax, 'generator', false, execa);51test('Can pass generators without an options plain object', testGeneratorSyntax, 'generator', true, execa);52test('Can pass generators with an options plain object, sync', testGeneratorSyntax, 'generator', false, execaSync);53test('Can pass generators without an options plain object, sync', testGeneratorSyntax, 'generator', true, execaSync);54test('Can pass webTransforms with an options plain object', testGeneratorSyntax, 'webTransform', true, execa);55test('Can pass webTransforms without an options plain object', testGeneratorSyntax, 'webTransform', false, execa);
deleted:test/stdio/option.js-57 removed
1import {inspect} from 'node:util';2import test from 'ava';3import {normalizeStdio} from '../../lib/stdio/option.js';45const macro = (t, input, expected, func) => {6 if (expected instanceof Error) {7 t.throws(() => {8 normalizeStdio(input);9 }, {message: expected.message});10 return;11 }1213 t.deepEqual(func(input), expected);14};1516const macroTitle = name => (title, input) => `${name} ${(inspect(input))}`;1718const stdioMacro = (...args) => macro(...args, normalizeStdio);19stdioMacro.title = macroTitle('execa()');2021test(stdioMacro, {stdio: 'inherit'}, ['inherit', 'inherit', 'inherit']);22test(stdioMacro, {stdio: 'pipe'}, ['pipe', 'pipe', 'pipe']);23test(stdioMacro, {stdio: 'ignore'}, ['ignore', 'ignore', 'ignore']);2425test(stdioMacro, {}, ['pipe', 'pipe', 'pipe']);26test(stdioMacro, {stdio: []}, ['pipe', 'pipe', 'pipe']);27test(stdioMacro, {stdio: [0]}, [0, 'pipe', 'pipe']);28test(stdioMacro, {stdio: [0, 1]}, [0, 1, 'pipe']);29test(stdioMacro, {stdio: [0, 1, 2]}, [0, 1, 2]);30test(stdioMacro, {stdio: [0, 1, 2, 3]}, [0, 1, 2, 3]);31test(stdioMacro, {stdio: [undefined, 1, 2]}, ['pipe', 1, 2]);32test(stdioMacro, {stdio: [null, 1, 2]}, ['pipe', 1, 2]);33test(stdioMacro, {stdio: [0, undefined, 2]}, [0, 'pipe', 2]);34test(stdioMacro, {stdio: [0, null, 2]}, [0, 'pipe', 2]);35test(stdioMacro, {stdio: [0, 1, undefined]}, [0, 1, 'pipe']);36test(stdioMacro, {stdio: [0, 1, null]}, [0, 1, 'pipe']);37test(stdioMacro, {stdio: [0, 1, 2, undefined]}, [0, 1, 2, 'ignore']);38test(stdioMacro, {stdio: [0, 1, 2, null]}, [0, 1, 2, 'ignore']);3940test(stdioMacro, {stdin: 'pipe'}, ['pipe', 'pipe', 'pipe']);41test(stdioMacro, {stdout: 'ignore'}, ['pipe', 'ignore', 'pipe']);42test(stdioMacro, {stderr: 'inherit'}, ['pipe', 'pipe', 'inherit']);43test(stdioMacro, {stdin: 'pipe', stdout: 'ignore', stderr: 'inherit'}, ['pipe', 'ignore', 'inherit']);44test(stdioMacro, {stdin: 'pipe', stdout: 'ignore'}, ['pipe', 'ignore', 'pipe']);45test(stdioMacro, {stdin: 'pipe', stderr: 'inherit'}, ['pipe', 'pipe', 'inherit']);46test(stdioMacro, {stdout: 'ignore', stderr: 'inherit'}, ['pipe', 'ignore', 'inherit']);47test(stdioMacro, {stdin: 0, stdout: 1, stderr: 2}, [0, 1, 2]);48test(stdioMacro, {stdin: 0, stdout: 1}, [0, 1, 'pipe']);49test(stdioMacro, {stdin: 0, stderr: 2}, [0, 'pipe', 2]);50test(stdioMacro, {stdout: 1, stderr: 2}, ['pipe', 1, 2]);5152test(stdioMacro, {stdio: {foo: 'bar'}}, new TypeError('Expected `stdio` to be of type `string` or `Array`, got `object`'));5354test(stdioMacro, {stdin: 'inherit', stdio: 'pipe'}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));55test(stdioMacro, {stdin: 'inherit', stdio: ['pipe']}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));56test(stdioMacro, {stdin: 'inherit', stdio: [undefined, 'pipe']}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));57test(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
1import {once, defaultMaxListeners} from 'node:events';2import process from 'node:process';3import {setImmediate} from 'node:timers/promises';4import test from 'ava';5import {execa} from '../../index.js';6import {STANDARD_STREAMS} from '../helpers/stdio.js';7import {foobarString} from '../helpers/input.js';8import {setFixtureDir} from '../helpers/fixtures-dir.js';9import {assertMaxListeners} from '../helpers/listeners.js';1011setFixtureDir();1213const getStandardStreamListeners = stream => Object.fromEntries(stream.eventNames().map(eventName => [eventName, stream.listeners(eventName)]));14const getStandardStreamsListeners = () => STANDARD_STREAMS.map(stream => getStandardStreamListeners(stream));1516const 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});2122const onStdinRemoveListener = () => once(process.stdin, 'removeListener');2324const 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 }3233 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};3839test.serial('process.std* listeners are cleaned up on success with a single input', testListenersCleanup, false);40test.serial('process.std* listeners are cleaned up on success with multiple inputs', testListenersCleanup, true);4142const subprocessesCount = 100;4344test.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});5051const testMaxListeners = async (t, isMultiple, maxListenersCount) => {52 const checkMaxListeners = assertMaxListeners(t);5354 for (const standardStream of STANDARD_STREAMS) {55 standardStream.setMaxListeners(maxListenersCount);56 }5758 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();6768 for (const standardStream of STANDARD_STREAMS) {69 t.is(standardStream.getMaxListeners(), maxListenersCount);70 standardStream.setMaxListeners(defaultMaxListeners);71 }72 }73};7475test.serial('No warning with maxListeners 1 and ["pipe", "inherit"]', testMaxListeners, false, 1);76test.serial('No warning with maxListeners default and ["pipe", "inherit"]', testMaxListeners, false, defaultMaxListeners);77test.serial('No warning with maxListeners 100 and ["pipe", "inherit"]', testMaxListeners, false, 100);78test.serial('No warning with maxListeners Infinity and ["pipe", "inherit"]', testMaxListeners, false, Number.POSITIVE_INFINITY);79test.serial('No warning with maxListeners 0 and ["pipe", "inherit"]', testMaxListeners, false, 0);80test.serial('No warning with maxListeners 1 and ["pipe", "inherit"], multiple inputs', testMaxListeners, true, 1);81test.serial('No warning with maxListeners default and ["pipe", "inherit"], multiple inputs', testMaxListeners, true, defaultMaxListeners);82test.serial('No warning with maxListeners 100 and ["pipe", "inherit"], multiple inputs', testMaxListeners, true, 100);83test.serial('No warning with maxListeners Infinity and ["pipe", "inherit"], multiple inputs', testMaxListeners, true, Number.POSITIVE_INFINITY);84test.serial('No warning with maxListeners 0 and ["pipe", "inherit"], multiple inputs', testMaxListeners, true, 0);
deleted:test/stdio/output-sync.js-33 removed
1import test from 'ava';2import {execaSync} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {throwingGenerator} from '../helpers/generator.js';5import {foobarString} from '../helpers/input.js';67setFixtureDir();89test('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});1617test('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});2526test('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
1import test from 'ava';2import {execa} from '../../index.js';3import {getStdio, STANDARD_STREAMS} from '../helpers/stdio.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';56setFixtureDir();78const 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};1314test('Does not destroy process.stdin on subprocess errors', testDestroyStandard, 0);15test('Does not destroy process.stdout on subprocess errors', testDestroyStandard, 1);16test('Does not destroy process.stderr on subprocess errors', testDestroyStandard, 2);1718const 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};2223test('Does not destroy process.stdin on subprocess early errors', testDestroyStandardSpawn, 0);24test('Does not destroy process.stdout on subprocess early errors', testDestroyStandardSpawn, 1);25test('Does not destroy process.stderr on subprocess early errors', testDestroyStandardSpawn, 2);2627const 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};3536test('Does not destroy process.stdin on stream subprocess errors', testDestroyStandardStream, 0);37test('Does not destroy process.stdout on stream subprocess errors', testDestroyStandardStream, 1);38test('Does not destroy process.stderr on stream subprocess errors', testDestroyStandardStream, 2);
deleted:test/stdio/split-binary.js-95 removed
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {getOutputsGenerator, resultGenerator} from '../helpers/generator.js';5import {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';1819setFixtureDir();2021// eslint-disable-next-line max-params22const 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};3536test('Does not split lines when "binary" is true', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFull, false, true, 'utf8', execa);37test('Splits lines when "binary" is false', testBinaryOption, false, simpleChunks, simpleLines, simpleFull, false, true, 'utf8', execa);38test('Splits lines when "binary" is undefined', testBinaryOption, undefined, simpleChunks, simpleLines, simpleFull, false, true, 'utf8', execa);39test('Does not split lines when "binary" is true, encoding "utf16le"', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUtf16Inverted, false, true, 'utf16le', execa);40test('Splits lines when "binary" is false, encoding "utf16le"', testBinaryOption, false, [simpleFullUtf16Uint8Array], simpleLines, simpleFullUtf16Inverted, false, true, 'utf16le', execa);41test('Splits lines when "binary" is undefined, encoding "utf16le"', testBinaryOption, undefined, [simpleFullUtf16Uint8Array], simpleLines, simpleFullUtf16Inverted, false, true, 'utf16le', execa);42test('Does not split lines when "binary" is true, encoding "buffer"', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, true, 'buffer', execa);43test('Does not split lines when "binary" is undefined, encoding "buffer"', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, true, 'buffer', execa);44test('Does not split lines when "binary" is false, encoding "buffer"', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, true, 'buffer', execa);45test('Does not split lines when "binary" is true, encoding "hex"', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, true, 'hex', execa);46test('Does not split lines when "binary" is undefined, encoding "hex"', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, true, 'hex', execa);47test('Does not split lines when "binary" is false, encoding "hex"', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, true, 'hex', execa);48test('Does not split lines when "binary" is true, objectMode', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleChunksUint8Array, true, true, 'utf8', execa);49test('Splits lines when "binary" is false, objectMode', testBinaryOption, false, simpleChunks, simpleLines, simpleLines, true, true, 'utf8', execa);50test('Splits lines when "binary" is undefined, objectMode', testBinaryOption, undefined, simpleChunks, simpleLines, simpleLines, true, true, 'utf8', execa);51test('Does not split lines when "binary" is true, preserveNewlines', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFull, false, false, 'utf8', execa);52test('Splits lines when "binary" is false, preserveNewlines', testBinaryOption, false, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, 'utf8', execa);53test('Splits lines when "binary" is undefined, preserveNewlines', testBinaryOption, undefined, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, 'utf8', execa);54test('Does not split lines when "binary" is true, preserveNewlines, encoding "utf16le"', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUtf16Inverted, false, false, 'utf16le', execa);55test('Splits lines when "binary" is false, preserveNewlines, encoding "utf16le"', testBinaryOption, false, [simpleFullUtf16Uint8Array], noNewlinesChunks, simpleFullEndUtf16Inverted, false, false, 'utf16le', execa);56test('Splits lines when "binary" is undefined, preserveNewlines, encoding "utf16le"', testBinaryOption, undefined, [simpleFullUtf16Uint8Array], noNewlinesChunks, simpleFullEndUtf16Inverted, false, false, 'utf16le', execa);57test('Does not split lines when "binary" is true, encoding "buffer", preserveNewlines', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, false, 'buffer', execa);58test('Does not split lines when "binary" is undefined, encoding "buffer", preserveNewlines', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, false, 'buffer', execa);59test('Does not split lines when "binary" is false, encoding "buffer", preserveNewlines', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, false, 'buffer', execa);60test('Does not split lines when "binary" is true, objectMode, preserveNewlines', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleChunksUint8Array, true, false, 'utf8', execa);61test('Does not split lines when "binary" is true, encoding "hex", preserveNewlines', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, false, 'hex', execa);62test('Does not split lines when "binary" is undefined, encoding "hex", preserveNewlines', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, false, 'hex', execa);63test('Does not split lines when "binary" is false, encoding "hex", preserveNewlines', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, false, 'hex', execa);64test('Splits lines when "binary" is false, objectMode, preserveNewlines', testBinaryOption, false, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, 'utf8', execa);65test('Splits lines when "binary" is undefined, objectMode, preserveNewlines', testBinaryOption, undefined, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, 'utf8', execa);66test('Does not split lines when "binary" is true, sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFull, false, true, 'utf8', execaSync);67test('Splits lines when "binary" is false, sync', testBinaryOption, false, simpleChunks, simpleLines, simpleFull, false, true, 'utf8', execaSync);68test('Splits lines when "binary" is undefined, sync', testBinaryOption, undefined, simpleChunks, simpleLines, simpleFull, false, true, 'utf8', execaSync);69test('Does not split lines when "binary" is true, encoding "utf16le", sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUtf16Inverted, false, true, 'utf16le', execaSync);70test('Splits lines when "binary" is false, encoding "utf16le", sync', testBinaryOption, false, [simpleFullUtf16Uint8Array], simpleLines, simpleFullUtf16Inverted, false, true, 'utf16le', execaSync);71test('Splits lines when "binary" is undefined, encoding "utf16le", sync', testBinaryOption, undefined, [simpleFullUtf16Uint8Array], simpleLines, simpleFullUtf16Inverted, false, true, 'utf16le', execaSync);72test('Does not split lines when "binary" is true, encoding "buffer", sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, true, 'buffer', execaSync);73test('Does not split lines when "binary" is undefined, encoding "buffer", sync', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, true, 'buffer', execaSync);74test('Does not split lines when "binary" is false, encoding "buffer", sync', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, true, 'buffer', execaSync);75test('Does not split lines when "binary" is true, encoding "hex", sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, true, 'hex', execaSync);76test('Does not split lines when "binary" is undefined, encoding "hex", sync', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, true, 'hex', execaSync);77test('Does not split lines when "binary" is false, encoding "hex", sync', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, true, 'hex', execaSync);78test('Does not split lines when "binary" is true, objectMode, sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleChunksUint8Array, true, true, 'utf8', execaSync);79test('Splits lines when "binary" is false, objectMode, sync', testBinaryOption, false, simpleChunks, simpleLines, simpleLines, true, true, 'utf8', execaSync);80test('Splits lines when "binary" is undefined, objectMode, sync', testBinaryOption, undefined, simpleChunks, simpleLines, simpleLines, true, true, 'utf8', execaSync);81test('Does not split lines when "binary" is true, preserveNewlines, sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFull, false, false, 'utf8', execaSync);82test('Splits lines when "binary" is false, preserveNewlines, sync', testBinaryOption, false, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, 'utf8', execaSync);83test('Splits lines when "binary" is undefined, preserveNewlines, sync', testBinaryOption, undefined, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, 'utf8', execaSync);84test('Does not split lines when "binary" is true, preserveNewlines, encoding "utf16le", sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUtf16Inverted, false, false, 'utf16le', execaSync);85test('Splits lines when "binary" is false, preserveNewlines, encoding "utf16le", sync', testBinaryOption, false, [simpleFullUtf16Uint8Array], noNewlinesChunks, simpleFullEndUtf16Inverted, false, false, 'utf16le', execaSync);86test('Splits lines when "binary" is undefined, preserveNewlines, encoding "utf16le", sync', testBinaryOption, undefined, [simpleFullUtf16Uint8Array], noNewlinesChunks, simpleFullEndUtf16Inverted, false, false, 'utf16le', execaSync);87test('Does not split lines when "binary" is true, encoding "buffer", preserveNewlines, sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, false, 'buffer', execaSync);88test('Does not split lines when "binary" is undefined, encoding "buffer", preserveNewlines, sync', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, false, 'buffer', execaSync);89test('Does not split lines when "binary" is false, encoding "buffer", preserveNewlines, sync', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, false, 'buffer', execaSync);90test('Does not split lines when "binary" is true, objectMode, preserveNewlines, sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleChunksUint8Array, true, false, 'utf8', execaSync);91test('Does not split lines when "binary" is true, encoding "hex", preserveNewlines, sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, false, 'hex', execaSync);92test('Does not split lines when "binary" is undefined, encoding "hex", preserveNewlines, sync', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, false, 'hex', execaSync);93test('Does not split lines when "binary" is false, encoding "hex", preserveNewlines, sync', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, false, 'hex', execaSync);94test('Splits lines when "binary" is false, objectMode, preserveNewlines, sync', testBinaryOption, false, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, 'utf8', execaSync);95test('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
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {getStdio} from '../helpers/stdio.js';5import {getOutputsGenerator, resultGenerator} from '../helpers/generator.js';6import {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';1819setFixtureDir();2021const windowsFull = 'aaa\r\nbbb\r\nccc';22const windowsFullEnd = `${windowsFull}\r\n`;23const windowsChunks = [windowsFull];24const windowsLines = ['aaa\r\n', 'bbb\r\n', 'ccc'];25const noNewlinesFullEnd = `${noNewlinesFull}\n`;26const noNewlinesLines = ['aaabbbccc'];27const singleChunks = [singleFull];28const noLines = [];29const emptyFull = '';30const emptyChunks = [emptyFull];31const manyEmptyChunks = [emptyFull, emptyFull, emptyFull];32const newlineFull = '\n';33const newlineChunks = [newlineFull];34const newlinesFull = '\n\n\n';35const newlinesChunks = [newlinesFull];36const newlinesLines = ['\n', '\n', '\n'];37const windowsNewlinesFull = '\r\n\r\n\r\n';38const windowsNewlinesChunks = [windowsNewlinesFull];39const windowsNewlinesLines = ['\r\n', '\r\n', '\r\n'];40const runOverChunks = ['aaa\nb', 'b', 'b\nccc'];41const bigFull = '.'.repeat(1e5);42const bigFullEnd = `${bigFull}\n`;43const bigChunks = [bigFull];44const manyChunks = Array.from({length: 1e3}).fill('.');45const manyFull = manyChunks.join('');46const manyFullEnd = `${manyFull}\n`;47const manyLines = [manyFull];4849// eslint-disable-next-line max-params50const 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};6263test('Split stdout - n newlines, 1 chunk', testLines, 1, simpleChunks, simpleLines, simpleFull, false, true, execa);64test('Split stderr - n newlines, 1 chunk', testLines, 2, simpleChunks, simpleLines, simpleFull, false, true, execa);65test('Split stdio[*] - n newlines, 1 chunk', testLines, 3, simpleChunks, simpleLines, simpleFull, false, true, execa);66test('Split stdout - preserveNewlines, n chunks', testLines, 1, noNewlinesChunks, noNewlinesLines, noNewlinesFull, false, true, execa);67test('Split stdout - 0 newlines, 1 chunk', testLines, 1, singleChunks, singleChunks, singleFull, false, true, execa);68test('Split stdout - empty, 1 chunk', testLines, 1, emptyChunks, noLines, emptyFull, false, true, execa);69test('Split stdout - Windows newlines', testLines, 1, windowsChunks, windowsLines, windowsFull, false, true, execa);70test('Split stdout - chunk ends with newline', testLines, 1, simpleFullEndChunks, simpleFullEndLines, simpleFullEnd, false, true, execa);71test('Split stdout - single newline', testLines, 1, newlineChunks, newlineChunks, newlineFull, false, true, execa);72test('Split stdout - only newlines', testLines, 1, newlinesChunks, newlinesLines, newlinesFull, false, true, execa);73test('Split stdout - only Windows newlines', testLines, 1, windowsNewlinesChunks, windowsNewlinesLines, windowsNewlinesFull, false, true, execa);74test('Split stdout - line split over multiple chunks', testLines, 1, runOverChunks, simpleLines, simpleFull, false, true, execa);75test('Split stdout - 0 newlines, big line', testLines, 1, bigChunks, bigChunks, bigFull, false, true, execa);76test('Split stdout - 0 newlines, many chunks', testLines, 1, manyChunks, manyLines, manyFull, false, true, execa);77test('Split stdout - n newlines, 1 chunk, objectMode', testLines, 1, simpleChunks, simpleLines, simpleLines, true, true, execa);78test('Split stderr - n newlines, 1 chunk, objectMode', testLines, 2, simpleChunks, simpleLines, simpleLines, true, true, execa);79test('Split stdio[*] - n newlines, 1 chunk, objectMode', testLines, 3, simpleChunks, simpleLines, simpleLines, true, true, execa);80test('Split stdout - preserveNewlines, n chunks, objectMode', testLines, 1, noNewlinesChunks, noNewlinesLines, noNewlinesLines, true, true, execa);81test('Split stdout - empty, 1 chunk, objectMode', testLines, 1, emptyChunks, noLines, noLines, true, true, execa);82test('Split stdout - 0 newlines, 1 chunk, objectMode', testLines, 1, singleChunks, singleChunks, singleChunks, true, true, execa);83test('Split stdout - Windows newlines, objectMode', testLines, 1, windowsChunks, windowsLines, windowsLines, true, true, execa);84test('Split stdout - chunk ends with newline, objectMode', testLines, 1, simpleFullEndChunks, simpleFullEndLines, simpleFullEndLines, true, true, execa);85test('Split stdout - single newline, objectMode', testLines, 1, newlineChunks, newlineChunks, newlineChunks, true, true, execa);86test('Split stdout - only newlines, objectMode', testLines, 1, newlinesChunks, newlinesLines, newlinesLines, true, true, execa);87test('Split stdout - only Windows newlines, objectMode', testLines, 1, windowsNewlinesChunks, windowsNewlinesLines, windowsNewlinesLines, true, true, execa);88test('Split stdout - line split over multiple chunks, objectMode', testLines, 1, runOverChunks, simpleLines, simpleLines, true, true, execa);89test('Split stdout - 0 newlines, big line, objectMode', testLines, 1, bigChunks, bigChunks, bigChunks, true, true, execa);90test('Split stdout - 0 newlines, many chunks, objectMode', testLines, 1, manyChunks, manyLines, manyLines, true, true, execa);91test('Split stdout - n newlines, 1 chunk, preserveNewlines', testLines, 1, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, execa);92test('Split stderr - n newlines, 1 chunk, preserveNewlines', testLines, 2, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, execa);93test('Split stdio[*] - n newlines, 1 chunk, preserveNewlines', testLines, 3, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, execa);94test('Split stdout - preserveNewlines, n chunks, preserveNewlines', testLines, 1, noNewlinesChunks, noNewlinesLines, noNewlinesFullEnd, false, false, execa);95test('Split stdout - empty, 1 chunk, preserveNewlines', testLines, 1, emptyChunks, noLines, emptyFull, false, false, execa);96test('Split stdout - 0 newlines, 1 chunk, preserveNewlines', testLines, 1, singleChunks, singleChunks, singleFullEnd, false, false, execa);97test('Split stdout - Windows newlines, preserveNewlines', testLines, 1, windowsChunks, noNewlinesChunks, windowsFullEnd, false, false, execa);98test('Split stdout - chunk ends with newline, preserveNewlines', testLines, 1, simpleFullEndChunks, noNewlinesChunks, simpleFullEnd, false, false, execa);99test('Split stdout - single newline, preserveNewlines', testLines, 1, newlineChunks, emptyChunks, newlineFull, false, false, execa);100test('Split stdout - only newlines, preserveNewlines', testLines, 1, newlinesChunks, manyEmptyChunks, newlinesFull, false, false, execa);101test('Split stdout - only Windows newlines, preserveNewlines', testLines, 1, windowsNewlinesChunks, manyEmptyChunks, windowsNewlinesFull, false, false, execa);102test('Split stdout - line split over multiple chunks, preserveNewlines', testLines, 1, runOverChunks, noNewlinesChunks, simpleFullEnd, false, false, execa);103test('Split stdout - 0 newlines, big line, preserveNewlines', testLines, 1, bigChunks, bigChunks, bigFullEnd, false, false, execa);104test('Split stdout - 0 newlines, many chunks, preserveNewlines', testLines, 1, manyChunks, manyLines, manyFullEnd, false, false, execa);105test('Split stdout - n newlines, 1 chunk, objectMode, preserveNewlines', testLines, 1, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, execa);106test('Split stderr - n newlines, 1 chunk, objectMode, preserveNewlines', testLines, 2, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, execa);107test('Split stdio[*] - n newlines, 1 chunk, objectMode, preserveNewlines', testLines, 3, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, execa);108test('Split stdout - preserveNewlines, n chunks, objectMode, preserveNewlines', testLines, 1, noNewlinesChunks, noNewlinesLines, noNewlinesLines, true, false, execa);109test('Split stdout - empty, 1 chunk, objectMode, preserveNewlines', testLines, 1, emptyChunks, noLines, noLines, true, false, execa);110test('Split stdout - 0 newlines, 1 chunk, objectMode, preserveNewlines', testLines, 1, singleChunks, singleChunks, singleChunks, true, false, execa);111test('Split stdout - Windows newlines, objectMode, preserveNewlines', testLines, 1, windowsChunks, noNewlinesChunks, noNewlinesChunks, true, false, execa);112test('Split stdout - chunk ends with newline, objectMode, preserveNewlines', testLines, 1, simpleFullEndChunks, noNewlinesChunks, noNewlinesChunks, true, false, execa);113test('Split stdout - single newline, objectMode, preserveNewlines', testLines, 1, newlineChunks, emptyChunks, emptyChunks, true, false, execa);114test('Split stdout - only newlines, objectMode, preserveNewlines', testLines, 1, newlinesChunks, manyEmptyChunks, manyEmptyChunks, true, false, execa);115test('Split stdout - only Windows newlines, objectMode, preserveNewlines', testLines, 1, windowsNewlinesChunks, manyEmptyChunks, manyEmptyChunks, true, false, execa);116test('Split stdout - line split over multiple chunks, objectMode, preserveNewlines', testLines, 1, runOverChunks, noNewlinesChunks, noNewlinesChunks, true, false, execa);117test('Split stdout - 0 newlines, big line, objectMode, preserveNewlines', testLines, 1, bigChunks, bigChunks, bigChunks, true, false, execa);118test('Split stdout - 0 newlines, many chunks, objectMode, preserveNewlines', testLines, 1, manyChunks, manyLines, manyLines, true, false, execa);119test('Split stdout - n newlines, 1 chunk, sync', testLines, 1, simpleChunks, simpleLines, simpleFull, false, true, execaSync);120test('Split stderr - n newlines, 1 chunk, sync', testLines, 2, simpleChunks, simpleLines, simpleFull, false, true, execaSync);121test('Split stdio[*] - n newlines, 1 chunk, sync', testLines, 3, simpleChunks, simpleLines, simpleFull, false, true, execaSync);122test('Split stdout - preserveNewlines, n chunks, sync', testLines, 1, noNewlinesChunks, noNewlinesLines, noNewlinesFull, false, true, execaSync);123test('Split stdout - 0 newlines, 1 chunk, sync', testLines, 1, singleChunks, singleChunks, singleFull, false, true, execaSync);124test('Split stdout - empty, 1 chunk, sync', testLines, 1, emptyChunks, noLines, emptyFull, false, true, execaSync);125test('Split stdout - Windows newlines, sync', testLines, 1, windowsChunks, windowsLines, windowsFull, false, true, execaSync);126test('Split stdout - chunk ends with newline, sync', testLines, 1, simpleFullEndChunks, simpleFullEndLines, simpleFullEnd, false, true, execaSync);127test('Split stdout - single newline, sync', testLines, 1, newlineChunks, newlineChunks, newlineFull, false, true, execaSync);128test('Split stdout - only newlines, sync', testLines, 1, newlinesChunks, newlinesLines, newlinesFull, false, true, execaSync);129test('Split stdout - only Windows newlines, sync', testLines, 1, windowsNewlinesChunks, windowsNewlinesLines, windowsNewlinesFull, false, true, execaSync);130test('Split stdout - line split over multiple chunks, sync', testLines, 1, runOverChunks, simpleLines, simpleFull, false, true, execaSync);131test('Split stdout - 0 newlines, big line, sync', testLines, 1, bigChunks, bigChunks, bigFull, false, true, execaSync);132test('Split stdout - 0 newlines, many chunks, sync', testLines, 1, manyChunks, manyLines, manyFull, false, true, execaSync);133test('Split stdout - n newlines, 1 chunk, objectMode, sync', testLines, 1, simpleChunks, simpleLines, simpleLines, true, true, execaSync);134test('Split stderr - n newlines, 1 chunk, objectMode, sync', testLines, 2, simpleChunks, simpleLines, simpleLines, true, true, execaSync);135test('Split stdio[*] - n newlines, 1 chunk, objectMode, sync', testLines, 3, simpleChunks, simpleLines, simpleLines, true, true, execaSync);136test('Split stdout - preserveNewlines, n chunks, objectMode, sync', testLines, 1, noNewlinesChunks, noNewlinesLines, noNewlinesLines, true, true, execaSync);137test('Split stdout - empty, 1 chunk, objectMode, sync', testLines, 1, emptyChunks, noLines, noLines, true, true, execaSync);138test('Split stdout - 0 newlines, 1 chunk, objectMode, sync', testLines, 1, singleChunks, singleChunks, singleChunks, true, true, execaSync);139test('Split stdout - Windows newlines, objectMode, sync', testLines, 1, windowsChunks, windowsLines, windowsLines, true, true, execaSync);140test('Split stdout - chunk ends with newline, objectMode, sync', testLines, 1, simpleFullEndChunks, simpleFullEndLines, simpleFullEndLines, true, true, execaSync);141test('Split stdout - single newline, objectMode, sync', testLines, 1, newlineChunks, newlineChunks, newlineChunks, true, true, execaSync);142test('Split stdout - only newlines, objectMode, sync', testLines, 1, newlinesChunks, newlinesLines, newlinesLines, true, true, execaSync);143test('Split stdout - only Windows newlines, objectMode, sync', testLines, 1, windowsNewlinesChunks, windowsNewlinesLines, windowsNewlinesLines, true, true, execaSync);144test('Split stdout - line split over multiple chunks, objectMode, sync', testLines, 1, runOverChunks, simpleLines, simpleLines, true, true, execaSync);145test('Split stdout - 0 newlines, big line, objectMode, sync', testLines, 1, bigChunks, bigChunks, bigChunks, true, true, execaSync);146test('Split stdout - 0 newlines, many chunks, objectMode, sync', testLines, 1, manyChunks, manyLines, manyLines, true, true, execaSync);147test('Split stdout - n newlines, 1 chunk, preserveNewlines, sync', testLines, 1, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, execaSync);148test('Split stderr - n newlines, 1 chunk, preserveNewlines, sync', testLines, 2, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, execaSync);149test('Split stdio[*] - n newlines, 1 chunk, preserveNewlines, sync', testLines, 3, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, execaSync);150test('Split stdout - preserveNewlines, n chunks, preserveNewlines, sync', testLines, 1, noNewlinesChunks, noNewlinesLines, noNewlinesFullEnd, false, false, execaSync);151test('Split stdout - empty, 1 chunk, preserveNewlines, sync', testLines, 1, emptyChunks, noLines, emptyFull, false, false, execaSync);152test('Split stdout - 0 newlines, 1 chunk, preserveNewlines, sync', testLines, 1, singleChunks, singleChunks, singleFullEnd, false, false, execaSync);153test('Split stdout - Windows newlines, preserveNewlines, sync', testLines, 1, windowsChunks, noNewlinesChunks, windowsFullEnd, false, false, execaSync);154test('Split stdout - chunk ends with newline, preserveNewlines, sync', testLines, 1, simpleFullEndChunks, noNewlinesChunks, simpleFullEnd, false, false, execaSync);155test('Split stdout - single newline, preserveNewlines, sync', testLines, 1, newlineChunks, emptyChunks, newlineFull, false, false, execaSync);156test('Split stdout - only newlines, preserveNewlines, sync', testLines, 1, newlinesChunks, manyEmptyChunks, newlinesFull, false, false, execaSync);157test('Split stdout - only Windows newlines, preserveNewlines, sync', testLines, 1, windowsNewlinesChunks, manyEmptyChunks, windowsNewlinesFull, false, false, execaSync);158test('Split stdout - line split over multiple chunks, preserveNewlines, sync', testLines, 1, runOverChunks, noNewlinesChunks, simpleFullEnd, false, false, execaSync);159test('Split stdout - 0 newlines, big line, preserveNewlines, sync', testLines, 1, bigChunks, bigChunks, bigFullEnd, false, false, execaSync);160test('Split stdout - 0 newlines, many chunks, preserveNewlines, sync', testLines, 1, manyChunks, manyLines, manyFullEnd, false, false, execaSync);161test('Split stdout - n newlines, 1 chunk, objectMode, preserveNewlines, sync', testLines, 1, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, execaSync);162test('Split stderr - n newlines, 1 chunk, objectMode, preserveNewlines, sync', testLines, 2, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, execaSync);163test('Split stdio[*] - n newlines, 1 chunk, objectMode, preserveNewlines, sync', testLines, 3, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, execaSync);164test('Split stdout - preserveNewlines, n chunks, objectMode, preserveNewlines, sync', testLines, 1, noNewlinesChunks, noNewlinesLines, noNewlinesLines, true, false, execaSync);165test('Split stdout - empty, 1 chunk, objectMode, preserveNewlines, sync', testLines, 1, emptyChunks, noLines, noLines, true, false, execaSync);166test('Split stdout - 0 newlines, 1 chunk, objectMode, preserveNewlines, sync', testLines, 1, singleChunks, singleChunks, singleChunks, true, false, execaSync);167test('Split stdout - Windows newlines, objectMode, preserveNewlines, sync', testLines, 1, windowsChunks, noNewlinesChunks, noNewlinesChunks, true, false, execaSync);168test('Split stdout - chunk ends with newline, objectMode, preserveNewlines, sync', testLines, 1, simpleFullEndChunks, noNewlinesChunks, noNewlinesChunks, true, false, execaSync);169test('Split stdout - single newline, objectMode, preserveNewlines, sync', testLines, 1, newlineChunks, emptyChunks, emptyChunks, true, false, execaSync);170test('Split stdout - only newlines, objectMode, preserveNewlines, sync', testLines, 1, newlinesChunks, manyEmptyChunks, manyEmptyChunks, true, false, execaSync);171test('Split stdout - only Windows newlines, objectMode, preserveNewlines, sync', testLines, 1, windowsNewlinesChunks, manyEmptyChunks, manyEmptyChunks, true, false, execaSync);172test('Split stdout - line split over multiple chunks, objectMode, preserveNewlines, sync', testLines, 1, runOverChunks, noNewlinesChunks, noNewlinesChunks, true, false, execaSync);173test('Split stdout - 0 newlines, big line, objectMode, preserveNewlines, sync', testLines, 1, bigChunks, bigChunks, bigChunks, true, false, execaSync);174test('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
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {getOutputsGenerator, noopGenerator, noopAsyncGenerator} from '../helpers/generator.js';5import {singleFull, singleFullEnd} from '../helpers/lines.js';67setFixtureDir();89const singleFullEndWindows = `${singleFull}\r\n`;10const mixedNewlines = '.\n.\r\n.\n.\r\n.\n';1112const 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};1920test('Strips newline when user do not mistakenly yield one at the end', testStripNewline, singleFull, singleFullEnd, execa);21test('Strips newline when user mistakenly yielded one at the end', testStripNewline, singleFullEnd, singleFullEnd, execa);22test('Strips newline when user mistakenly yielded one at the end, Windows newline', testStripNewline, singleFullEndWindows, singleFullEndWindows, execa);23test('Strips newline when user do not mistakenly yield one at the end, sync', testStripNewline, singleFull, singleFullEnd, execaSync);24test('Strips newline when user mistakenly yielded one at the end, sync', testStripNewline, singleFullEnd, singleFullEnd, execaSync);25test('Strips newline when user mistakenly yielded one at the end, Windows newline, sync', testStripNewline, singleFullEndWindows, singleFullEndWindows, execaSync);2627const 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};3435test('Can mix Unix and Windows newlines', testMixNewlines, noopGenerator, execa);36test('Can mix Unix and Windows newlines, sync', testMixNewlines, noopGenerator, execaSync);37test('Can mix Unix and Windows newlines, async', testMixNewlines, noopAsyncGenerator, execa);
deleted:test/stdio/split-transform.js-78 removed
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {getOutputsGenerator, resultGenerator} from '../helpers/generator.js';5import {foobarString, foobarUint8Array, foobarObject, foobarObjectString} from '../helpers/input.js';67setFixtureDir();89const resultUint8ArrayGenerator = function * (lines, chunk) {10 lines.push(chunk);11 yield new TextEncoder().encode(chunk);12};1314// eslint-disable-next-line max-params15const 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};2829test('Line splitting when converting from string to Uint8Array', testStringToUint8Array, [foobarString], false, true, execa);30test('Line splitting when converting from string to Uint8Array, objectMode', testStringToUint8Array, [foobarUint8Array], true, true, execa);31test('Line splitting when converting from string to Uint8Array, preserveNewlines', testStringToUint8Array, [foobarString], false, false, execa);32test('Line splitting when converting from string to Uint8Array, objectMode, preserveNewlines', testStringToUint8Array, [foobarUint8Array], true, false, execa);33test('Line splitting when converting from string to Uint8Array, sync', testStringToUint8Array, [foobarString], false, true, execaSync);34test('Line splitting when converting from string to Uint8Array, objectMode, sync', testStringToUint8Array, [foobarUint8Array], true, true, execaSync);35test('Line splitting when converting from string to Uint8Array, preserveNewlines, sync', testStringToUint8Array, [foobarString], false, false, execaSync);36test('Line splitting when converting from string to Uint8Array, objectMode, preserveNewlines, sync', testStringToUint8Array, [foobarUint8Array], true, false, execaSync);3738const serializeResultGenerator = function * (lines, chunk) {39 lines.push(chunk);40 yield JSON.stringify(chunk);41};4243const 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};5556test('Can switch from objectMode to non-objectMode', testUnsetObjectMode, `${foobarObjectString}\n`, false, execa);57test('Can switch from objectMode to non-objectMode, preserveNewlines', testUnsetObjectMode, foobarObjectString, true, execa);58test('Can switch from objectMode to non-objectMode, sync', testUnsetObjectMode, `${foobarObjectString}\n`, false, execaSync);59test('Can switch from objectMode to non-objectMode, preserveNewlines, sync', testUnsetObjectMode, foobarObjectString, true, execaSync);6061// eslint-disable-next-line max-params62const 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};7475test('Can use "yield* array" to produce multiple lines', testYieldArray, [foobarString, foobarString], [foobarString, foobarString], `${foobarString}\n${foobarString}\n`, execa);76test('Can use "yield* array" to produce empty lines', testYieldArray, [foobarString, ''], [foobarString, ''], `${foobarString}\n\n`, execa);77test('Can use "yield* array" to produce multiple lines, sync', testYieldArray, [foobarString, foobarString], [foobarString, foobarString], `${foobarString}\n${foobarString}\n`, execaSync);78test('Can use "yield* array" to produce empty lines, sync', testYieldArray, [foobarString, ''], [foobarString, ''], `${foobarString}\n\n`, execaSync);
added:test/stdio/stdio-option.js+57 added
1import {inspect} from 'node:util';2import test from 'ava';3import {normalizeStdioOption} from '../../lib/stdio/stdio-option.js';45const macro = (t, input, expected, func) => {6 if (expected instanceof Error) {7 t.throws(() => {8 normalizeStdioOption(input);9 }, {message: expected.message});10 return;11 }1213 t.deepEqual(func(input), expected);14};1516const macroTitle = name => (title, input) => `${name} ${(inspect(input))}`;1718const stdioMacro = (...args) => macro(...args, normalizeStdioOption);19stdioMacro.title = macroTitle('execa()');2021test(stdioMacro, {stdio: 'inherit'}, ['inherit', 'inherit', 'inherit']);22test(stdioMacro, {stdio: 'pipe'}, ['pipe', 'pipe', 'pipe']);23test(stdioMacro, {stdio: 'ignore'}, ['ignore', 'ignore', 'ignore']);2425test(stdioMacro, {}, ['pipe', 'pipe', 'pipe']);26test(stdioMacro, {stdio: []}, ['pipe', 'pipe', 'pipe']);27test(stdioMacro, {stdio: [0]}, [0, 'pipe', 'pipe']);28test(stdioMacro, {stdio: [0, 1]}, [0, 1, 'pipe']);29test(stdioMacro, {stdio: [0, 1, 2]}, [0, 1, 2]);30test(stdioMacro, {stdio: [0, 1, 2, 3]}, [0, 1, 2, 3]);31test(stdioMacro, {stdio: [undefined, 1, 2]}, ['pipe', 1, 2]);32test(stdioMacro, {stdio: [null, 1, 2]}, ['pipe', 1, 2]);33test(stdioMacro, {stdio: [0, undefined, 2]}, [0, 'pipe', 2]);34test(stdioMacro, {stdio: [0, null, 2]}, [0, 'pipe', 2]);35test(stdioMacro, {stdio: [0, 1, undefined]}, [0, 1, 'pipe']);36test(stdioMacro, {stdio: [0, 1, null]}, [0, 1, 'pipe']);37test(stdioMacro, {stdio: [0, 1, 2, undefined]}, [0, 1, 2, 'ignore']);38test(stdioMacro, {stdio: [0, 1, 2, null]}, [0, 1, 2, 'ignore']);3940test(stdioMacro, {stdin: 'pipe'}, ['pipe', 'pipe', 'pipe']);41test(stdioMacro, {stdout: 'ignore'}, ['pipe', 'ignore', 'pipe']);42test(stdioMacro, {stderr: 'inherit'}, ['pipe', 'pipe', 'inherit']);43test(stdioMacro, {stdin: 'pipe', stdout: 'ignore', stderr: 'inherit'}, ['pipe', 'ignore', 'inherit']);44test(stdioMacro, {stdin: 'pipe', stdout: 'ignore'}, ['pipe', 'ignore', 'pipe']);45test(stdioMacro, {stdin: 'pipe', stderr: 'inherit'}, ['pipe', 'pipe', 'inherit']);46test(stdioMacro, {stdout: 'ignore', stderr: 'inherit'}, ['pipe', 'ignore', 'inherit']);47test(stdioMacro, {stdin: 0, stdout: 1, stderr: 2}, [0, 1, 2]);48test(stdioMacro, {stdin: 0, stdout: 1}, [0, 1, 'pipe']);49test(stdioMacro, {stdin: 0, stderr: 2}, [0, 'pipe', 2]);50test(stdioMacro, {stdout: 1, stderr: 2}, ['pipe', 1, 2]);5152test(stdioMacro, {stdio: {foo: 'bar'}}, new TypeError('Expected `stdio` to be of type `string` or `Array`, got `object`'));5354test(stdioMacro, {stdin: 'inherit', stdio: 'pipe'}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));55test(stdioMacro, {stdin: 'inherit', stdio: ['pipe']}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));56test(stdioMacro, {stdin: 'inherit', stdio: [undefined, 'pipe']}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));57test(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
1import {Buffer} from 'node:buffer';2import test from 'ava';3import {execa, execaSync} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';5import {foobarObject} from '../helpers/input.js';6import {7 outputObjectGenerator,8 uppercaseGenerator,9 uppercaseBufferGenerator,10} from '../helpers/generator.js';1112setFixtureDir();1314const textEncoder = new TextEncoder();1516const getAllStdioOption = (stdioOption, encoding, objectMode) => {17 if (stdioOption) {18 return 'pipe';19 }2021 if (objectMode) {22 return outputObjectGenerator();23 }2425 return encoding === 'utf8' ? uppercaseGenerator() : uppercaseBufferGenerator();26};2728const getStdoutStderrOutput = ({output, stdioOption, encoding, objectMode, lines}) => {29 if (objectMode && !stdioOption) {30 return encoding === 'utf8' ? [foobarObject, foobarObject] : [foobarObject];31 }3233 const stdioOutput = stdioOption ? output : output.toUpperCase();3435 if (encoding === 'hex') {36 return Buffer.from(stdioOutput).toString('hex');37 }3839 if (encoding === 'buffer') {40 return textEncoder.encode(stdioOutput);41 }4243 return lines ? stdioOutput.trim().split('\n').map(string => `${string}\n`) : stdioOutput;44};4546const getAllOutput = ({stdoutOutput, stderrOutput, encoding, objectMode, lines}) => {47 if (objectMode || (lines && encoding === 'utf8')) {48 return [stdoutOutput, stderrOutput].flat();49 }5051 return encoding === 'buffer'52 ? new Uint8Array([...stdoutOutput, ...stderrOutput])53 : `${stdoutOutput}${stderrOutput}`;54};5556// eslint-disable-next-line max-params57const 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 });6869 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};8081test('Can use generators with result.all = transform + transform', testGeneratorAll, true, 'utf8', false, false, false, false, execa);82test('Can use generators with error.all = transform + transform', testGeneratorAll, false, 'utf8', false, false, false, false, execa);83test('Can use generators with result.all = transform + transform, encoding "buffer"', testGeneratorAll, true, 'buffer', false, false, false, false, execa);84test('Can use generators with error.all = transform + transform, encoding "buffer"', testGeneratorAll, false, 'buffer', false, false, false, false, execa);85test('Can use generators with result.all = transform + transform, encoding "hex"', testGeneratorAll, true, 'hex', false, false, false, false, execa);86test('Can use generators with error.all = transform + transform, encoding "hex"', testGeneratorAll, false, 'hex', false, false, false, false, execa);87test('Can use generators with result.all = transform + pipe', testGeneratorAll, true, 'utf8', false, false, true, false, execa);88test('Can use generators with error.all = transform + pipe', testGeneratorAll, false, 'utf8', false, false, true, false, execa);89test('Can use generators with result.all = transform + pipe, encoding "buffer"', testGeneratorAll, true, 'buffer', false, false, true, false, execa);90test('Can use generators with error.all = transform + pipe, encoding "buffer"', testGeneratorAll, false, 'buffer', false, false, true, false, execa);91test('Can use generators with result.all = transform + pipe, encoding "hex"', testGeneratorAll, true, 'hex', false, false, true, false, execa);92test('Can use generators with error.all = transform + pipe, encoding "hex"', testGeneratorAll, false, 'hex', false, false, true, false, execa);93test('Can use generators with result.all = pipe + transform', testGeneratorAll, true, 'utf8', false, true, false, false, execa);94test('Can use generators with error.all = pipe + transform', testGeneratorAll, false, 'utf8', false, true, false, false, execa);95test('Can use generators with result.all = pipe + transform, encoding "buffer"', testGeneratorAll, true, 'buffer', false, true, false, false, execa);96test('Can use generators with error.all = pipe + transform, encoding "buffer"', testGeneratorAll, false, 'buffer', false, true, false, false, execa);97test('Can use generators with result.all = pipe + transform, encoding "hex"', testGeneratorAll, true, 'hex', false, true, false, false, execa);98test('Can use generators with error.all = pipe + transform, encoding "hex"', testGeneratorAll, false, 'hex', false, true, false, false, execa);99test('Can use generators with result.all = transform + transform, objectMode', testGeneratorAll, true, 'utf8', true, false, false, false, execa);100test('Can use generators with error.all = transform + transform, objectMode', testGeneratorAll, false, 'utf8', true, false, false, false, execa);101test('Can use generators with result.all = transform + transform, objectMode, encoding "buffer"', testGeneratorAll, true, 'buffer', true, false, false, false, execa);102test('Can use generators with error.all = transform + transform, objectMode, encoding "buffer"', testGeneratorAll, false, 'buffer', true, false, false, false, execa);103test('Can use generators with result.all = transform + transform, objectMode, encoding "hex"', testGeneratorAll, true, 'hex', true, false, false, false, execa);104test('Can use generators with error.all = transform + transform, objectMode, encoding "hex"', testGeneratorAll, false, 'hex', true, false, false, false, execa);105test('Can use generators with result.all = transform + pipe, objectMode', testGeneratorAll, true, 'utf8', true, false, true, false, execa);106test('Can use generators with error.all = transform + pipe, objectMode', testGeneratorAll, false, 'utf8', true, false, true, false, execa);107test('Can use generators with result.all = transform + pipe, objectMode, encoding "buffer"', testGeneratorAll, true, 'buffer', true, false, true, false, execa);108test('Can use generators with error.all = transform + pipe, objectMode, encoding "buffer"', testGeneratorAll, false, 'buffer', true, false, true, false, execa);109test('Can use generators with result.all = transform + pipe, objectMode, encoding "hex"', testGeneratorAll, true, 'hex', true, false, true, false, execa);110test('Can use generators with error.all = transform + pipe, objectMode, encoding "hex"', testGeneratorAll, false, 'hex', true, false, true, false, execa);111test('Can use generators with result.all = pipe + transform, objectMode', testGeneratorAll, true, 'utf8', true, true, false, false, execa);112test('Can use generators with error.all = pipe + transform, objectMode', testGeneratorAll, false, 'utf8', true, true, false, false, execa);113test('Can use generators with result.all = pipe + transform, objectMode, encoding "buffer"', testGeneratorAll, true, 'buffer', true, true, false, false, execa);114test('Can use generators with error.all = pipe + transform, objectMode, encoding "buffer"', testGeneratorAll, false, 'buffer', true, true, false, false, execa);115test('Can use generators with result.all = pipe + transform, objectMode, encoding "hex"', testGeneratorAll, true, 'hex', true, true, false, false, execa);116test('Can use generators with error.all = pipe + transform, objectMode, encoding "hex"', testGeneratorAll, false, 'hex', true, true, false, false, execa);117test('Can use generators with result.all = transform + transform, sync', testGeneratorAll, true, 'utf8', false, false, false, false, execaSync);118test('Can use generators with error.all = transform + transform, sync', testGeneratorAll, false, 'utf8', false, false, false, false, execaSync);119test('Can use generators with result.all = transform + transform, encoding "buffer", sync', testGeneratorAll, true, 'buffer', false, false, false, false, execaSync);120test('Can use generators with error.all = transform + transform, encoding "buffer", sync', testGeneratorAll, false, 'buffer', false, false, false, false, execaSync);121test('Can use generators with result.all = transform + transform, encoding "hex", sync', testGeneratorAll, true, 'hex', false, false, false, false, execaSync);122test('Can use generators with error.all = transform + transform, encoding "hex", sync', testGeneratorAll, false, 'hex', false, false, false, false, execaSync);123test('Can use generators with result.all = transform + pipe, sync', testGeneratorAll, true, 'utf8', false, false, true, false, execaSync);124test('Can use generators with error.all = transform + pipe, sync', testGeneratorAll, false, 'utf8', false, false, true, false, execaSync);125test('Can use generators with result.all = transform + pipe, encoding "buffer", sync', testGeneratorAll, true, 'buffer', false, false, true, false, execaSync);126test('Can use generators with error.all = transform + pipe, encoding "buffer", sync', testGeneratorAll, false, 'buffer', false, false, true, false, execaSync);127test('Can use generators with result.all = transform + pipe, encoding "hex", sync', testGeneratorAll, true, 'hex', false, false, true, false, execaSync);128test('Can use generators with error.all = transform + pipe, encoding "hex", sync', testGeneratorAll, false, 'hex', false, false, true, false, execaSync);129test('Can use generators with result.all = pipe + transform, sync', testGeneratorAll, true, 'utf8', false, true, false, false, execaSync);130test('Can use generators with error.all = pipe + transform, sync', testGeneratorAll, false, 'utf8', false, true, false, false, execaSync);131test('Can use generators with result.all = pipe + transform, encoding "buffer", sync', testGeneratorAll, true, 'buffer', false, true, false, false, execaSync);132test('Can use generators with error.all = pipe + transform, encoding "buffer", sync', testGeneratorAll, false, 'buffer', false, true, false, false, execaSync);133test('Can use generators with result.all = pipe + transform, encoding "hex", sync', testGeneratorAll, true, 'hex', false, true, false, false, execaSync);134test('Can use generators with error.all = pipe + transform, encoding "hex", sync', testGeneratorAll, false, 'hex', false, true, false, false, execaSync);135test('Can use generators with result.all = transform + transform, objectMode, sync', testGeneratorAll, true, 'utf8', true, false, false, false, execaSync);136test('Can use generators with error.all = transform + transform, objectMode, sync', testGeneratorAll, false, 'utf8', true, false, false, false, execaSync);137test('Can use generators with result.all = transform + transform, objectMode, encoding "buffer", sync', testGeneratorAll, true, 'buffer', true, false, false, false, execaSync);138test('Can use generators with error.all = transform + transform, objectMode, encoding "buffer", sync', testGeneratorAll, false, 'buffer', true, false, false, false, execaSync);139test('Can use generators with result.all = transform + transform, objectMode, encoding "hex", sync', testGeneratorAll, true, 'hex', true, false, false, false, execaSync);140test('Can use generators with error.all = transform + transform, objectMode, encoding "hex", sync', testGeneratorAll, false, 'hex', true, false, false, false, execaSync);141test('Can use generators with result.all = transform + pipe, objectMode, sync', testGeneratorAll, true, 'utf8', true, false, true, false, execaSync);142test('Can use generators with error.all = transform + pipe, objectMode, sync', testGeneratorAll, false, 'utf8', true, false, true, false, execaSync);143test('Can use generators with result.all = transform + pipe, objectMode, encoding "buffer", sync', testGeneratorAll, true, 'buffer', true, false, true, false, execaSync);144test('Can use generators with error.all = transform + pipe, objectMode, encoding "buffer", sync', testGeneratorAll, false, 'buffer', true, false, true, false, execaSync);145test('Can use generators with result.all = transform + pipe, objectMode, encoding "hex", sync', testGeneratorAll, true, 'hex', true, false, true, false, execaSync);146test('Can use generators with error.all = transform + pipe, objectMode, encoding "hex", sync', testGeneratorAll, false, 'hex', true, false, true, false, execaSync);147test('Can use generators with result.all = pipe + transform, objectMode, sync', testGeneratorAll, true, 'utf8', true, true, false, false, execaSync);148test('Can use generators with error.all = pipe + transform, objectMode, sync', testGeneratorAll, false, 'utf8', true, true, false, false, execaSync);149test('Can use generators with result.all = pipe + transform, objectMode, encoding "buffer", sync', testGeneratorAll, true, 'buffer', true, true, false, false, execaSync);150test('Can use generators with error.all = pipe + transform, objectMode, encoding "buffer", sync', testGeneratorAll, false, 'buffer', true, true, false, false, execaSync);151test('Can use generators with result.all = pipe + transform, objectMode, encoding "hex", sync', testGeneratorAll, true, 'hex', true, true, false, false, execaSync);152test('Can use generators with error.all = pipe + transform, objectMode, encoding "hex", sync', testGeneratorAll, false, 'hex', true, true, false, false, execaSync);153test('Can use generators with result.all = transform + transform, lines', testGeneratorAll, true, 'utf8', false, false, false, true, execa);154test('Can use generators with error.all = transform + transform, lines', testGeneratorAll, false, 'utf8', false, false, false, true, execa);155test('Can use generators with result.all = transform + transform, encoding "buffer", lines', testGeneratorAll, true, 'buffer', false, false, false, true, execa);156test('Can use generators with error.all = transform + transform, encoding "buffer", lines', testGeneratorAll, false, 'buffer', false, false, false, true, execa);157test('Can use generators with result.all = transform + transform, encoding "hex", lines', testGeneratorAll, true, 'hex', false, false, false, true, execa);158test('Can use generators with error.all = transform + transform, encoding "hex", lines', testGeneratorAll, false, 'hex', false, false, false, true, execa);159test('Can use generators with result.all = transform + pipe, lines', testGeneratorAll, true, 'utf8', false, false, true, true, execa);160test('Can use generators with error.all = transform + pipe, lines', testGeneratorAll, false, 'utf8', false, false, true, true, execa);161test('Can use generators with result.all = transform + pipe, encoding "buffer", lines', testGeneratorAll, true, 'buffer', false, false, true, true, execa);162test('Can use generators with error.all = transform + pipe, encoding "buffer", lines', testGeneratorAll, false, 'buffer', false, false, true, true, execa);163test('Can use generators with result.all = transform + pipe, encoding "hex", lines', testGeneratorAll, true, 'hex', false, false, true, true, execa);164test('Can use generators with error.all = transform + pipe, encoding "hex", lines', testGeneratorAll, false, 'hex', false, false, true, true, execa);165test('Can use generators with result.all = pipe + transform, lines', testGeneratorAll, true, 'utf8', false, true, false, true, execa);166test('Can use generators with error.all = pipe + transform, lines', testGeneratorAll, false, 'utf8', false, true, false, true, execa);167test('Can use generators with result.all = pipe + transform, encoding "buffer", lines', testGeneratorAll, true, 'buffer', false, true, false, true, execa);168test('Can use generators with error.all = pipe + transform, encoding "buffer", lines', testGeneratorAll, false, 'buffer', false, true, false, true, execa);169test('Can use generators with result.all = pipe + transform, encoding "hex", lines', testGeneratorAll, true, 'hex', false, true, false, true, execa);170test('Can use generators with error.all = pipe + transform, encoding "hex", lines', testGeneratorAll, false, 'hex', false, true, false, true, execa);171test('Can use generators with result.all = transform + transform, objectMode, lines', testGeneratorAll, true, 'utf8', true, false, false, true, execa);172test('Can use generators with error.all = transform + transform, objectMode, lines', testGeneratorAll, false, 'utf8', true, false, false, true, execa);173test('Can use generators with result.all = transform + transform, objectMode, encoding "buffer", lines', testGeneratorAll, true, 'buffer', true, false, false, true, execa);174test('Can use generators with error.all = transform + transform, objectMode, encoding "buffer", lines', testGeneratorAll, false, 'buffer', true, false, false, true, execa);175test('Can use generators with result.all = transform + transform, objectMode, encoding "hex", lines', testGeneratorAll, true, 'hex', true, false, false, true, execa);176test('Can use generators with error.all = transform + transform, objectMode, encoding "hex", lines', testGeneratorAll, false, 'hex', true, false, false, true, execa);177test('Can use generators with result.all = transform + pipe, objectMode, lines', testGeneratorAll, true, 'utf8', true, false, true, true, execa);178test('Can use generators with error.all = transform + pipe, objectMode, lines', testGeneratorAll, false, 'utf8', true, false, true, true, execa);179test('Can use generators with result.all = transform + pipe, objectMode, encoding "buffer", lines', testGeneratorAll, true, 'buffer', true, false, true, true, execa);180test('Can use generators with error.all = transform + pipe, objectMode, encoding "buffer", lines', testGeneratorAll, false, 'buffer', true, false, true, true, execa);181test('Can use generators with result.all = transform + pipe, objectMode, encoding "hex", lines', testGeneratorAll, true, 'hex', true, false, true, true, execa);182test('Can use generators with error.all = transform + pipe, objectMode, encoding "hex", lines', testGeneratorAll, false, 'hex', true, false, true, true, execa);183test('Can use generators with result.all = pipe + transform, objectMode, lines', testGeneratorAll, true, 'utf8', true, true, false, true, execa);184test('Can use generators with error.all = pipe + transform, objectMode, lines', testGeneratorAll, false, 'utf8', true, true, false, true, execa);185test('Can use generators with result.all = pipe + transform, objectMode, encoding "buffer", lines', testGeneratorAll, true, 'buffer', true, true, false, true, execa);186test('Can use generators with error.all = pipe + transform, objectMode, encoding "buffer", lines', testGeneratorAll, false, 'buffer', true, true, false, true, execa);187test('Can use generators with result.all = pipe + transform, objectMode, encoding "hex", lines', testGeneratorAll, true, 'hex', true, true, false, true, execa);188test('Can use generators with error.all = pipe + transform, objectMode, encoding "hex", lines', testGeneratorAll, false, 'hex', true, true, false, true, execa);189test('Can use generators with result.all = transform + transform, sync, lines', testGeneratorAll, true, 'utf8', false, false, false, true, execaSync);190test('Can use generators with error.all = transform + transform, sync, lines', testGeneratorAll, false, 'utf8', false, false, false, true, execaSync);191test('Can use generators with result.all = transform + transform, encoding "buffer", sync, lines', testGeneratorAll, true, 'buffer', false, false, false, true, execaSync);192test('Can use generators with error.all = transform + transform, encoding "buffer", sync, lines', testGeneratorAll, false, 'buffer', false, false, false, true, execaSync);193test('Can use generators with result.all = transform + transform, encoding "hex", sync, lines', testGeneratorAll, true, 'hex', false, false, false, true, execaSync);194test('Can use generators with error.all = transform + transform, encoding "hex", sync, lines', testGeneratorAll, false, 'hex', false, false, false, true, execaSync);195test('Can use generators with result.all = transform + pipe, sync, lines', testGeneratorAll, true, 'utf8', false, false, true, true, execaSync);196test('Can use generators with error.all = transform + pipe, sync, lines', testGeneratorAll, false, 'utf8', false, false, true, true, execaSync);197test('Can use generators with result.all = transform + pipe, encoding "buffer", sync, lines', testGeneratorAll, true, 'buffer', false, false, true, true, execaSync);198test('Can use generators with error.all = transform + pipe, encoding "buffer", sync, lines', testGeneratorAll, false, 'buffer', false, false, true, true, execaSync);199test('Can use generators with result.all = transform + pipe, encoding "hex", sync, lines', testGeneratorAll, true, 'hex', false, false, true, true, execaSync);200test('Can use generators with error.all = transform + pipe, encoding "hex", sync, lines', testGeneratorAll, false, 'hex', false, false, true, true, execaSync);201test('Can use generators with result.all = pipe + transform, sync, lines', testGeneratorAll, true, 'utf8', false, true, false, true, execaSync);202test('Can use generators with error.all = pipe + transform, sync, lines', testGeneratorAll, false, 'utf8', false, true, false, true, execaSync);203test('Can use generators with result.all = pipe + transform, encoding "buffer", sync, lines', testGeneratorAll, true, 'buffer', false, true, false, true, execaSync);204test('Can use generators with error.all = pipe + transform, encoding "buffer", sync, lines', testGeneratorAll, false, 'buffer', false, true, false, true, execaSync);205test('Can use generators with result.all = pipe + transform, encoding "hex", sync, lines', testGeneratorAll, true, 'hex', false, true, false, true, execaSync);206test('Can use generators with error.all = pipe + transform, encoding "hex", sync, lines', testGeneratorAll, false, 'hex', false, true, false, true, execaSync);207test('Can use generators with result.all = transform + transform, objectMode, sync, lines', testGeneratorAll, true, 'utf8', true, false, false, true, execaSync);208test('Can use generators with error.all = transform + transform, objectMode, sync, lines', testGeneratorAll, false, 'utf8', true, false, false, true, execaSync);209test('Can use generators with result.all = transform + transform, objectMode, encoding "buffer", sync, lines', testGeneratorAll, true, 'buffer', true, false, false, true, execaSync);210test('Can use generators with error.all = transform + transform, objectMode, encoding "buffer", sync, lines', testGeneratorAll, false, 'buffer', true, false, false, true, execaSync);211test('Can use generators with result.all = transform + transform, objectMode, encoding "hex", sync, lines', testGeneratorAll, true, 'hex', true, false, false, true, execaSync);212test('Can use generators with error.all = transform + transform, objectMode, encoding "hex", sync, lines', testGeneratorAll, false, 'hex', true, false, false, true, execaSync);213test('Can use generators with result.all = transform + pipe, objectMode, sync, lines', testGeneratorAll, true, 'utf8', true, false, true, true, execaSync);214test('Can use generators with error.all = transform + pipe, objectMode, sync, lines', testGeneratorAll, false, 'utf8', true, false, true, true, execaSync);215test('Can use generators with result.all = transform + pipe, objectMode, encoding "buffer", sync, lines', testGeneratorAll, true, 'buffer', true, false, true, true, execaSync);216test('Can use generators with error.all = transform + pipe, objectMode, encoding "buffer", sync, lines', testGeneratorAll, false, 'buffer', true, false, true, true, execaSync);217test('Can use generators with result.all = transform + pipe, objectMode, encoding "hex", sync, lines', testGeneratorAll, true, 'hex', true, false, true, true, execaSync);218test('Can use generators with error.all = transform + pipe, objectMode, encoding "hex", sync, lines', testGeneratorAll, false, 'hex', true, false, true, true, execaSync);219test('Can use generators with result.all = pipe + transform, objectMode, sync, lines', testGeneratorAll, true, 'utf8', true, true, false, true, execaSync);220test('Can use generators with error.all = pipe + transform, objectMode, sync, lines', testGeneratorAll, false, 'utf8', true, true, false, true, execaSync);221test('Can use generators with result.all = pipe + transform, objectMode, encoding "buffer", sync, lines', testGeneratorAll, true, 'buffer', true, true, false, true, execaSync);222test('Can use generators with error.all = pipe + transform, objectMode, encoding "buffer", sync, lines', testGeneratorAll, false, 'buffer', true, true, false, true, execaSync);223test('Can use generators with result.all = pipe + transform, objectMode, encoding "hex", sync, lines', testGeneratorAll, true, 'hex', true, true, false, true, execaSync);224test('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
1import {once} from 'node:events';2import test from 'ava';3import {execa, execaSync} from '../../index.js';4import {foobarString} from '../helpers/input.js';5import {noopGenerator, infiniteGenerator, convertTransformToFinal} from '../helpers/generator.js';6import {generatorsMap} from '../helpers/map.js';7import {setFixtureDir} from '../helpers/fixtures-dir.js';89setFixtureDir();1011const 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};2122const testThrowingGenerator = async (t, type, final, execaMethod) => {23 await assertProcessError(t, type, execaMethod, transform => execaMethod('noop.js', {24 stdout: convertTransformToFinal(transform, final),25 }));26};2728test('Generators "transform" errors make subprocess fail', testThrowingGenerator, 'generator', false, execa);29test('Generators "final" errors make subprocess fail', testThrowingGenerator, 'generator', true, execa);30test('Generators "transform" errors make subprocess fail, sync', testThrowingGenerator, 'generator', false, execaSync);31test('Generators "final" errors make subprocess fail, sync', testThrowingGenerator, 'generator', true, execaSync);32test('Duplexes "transform" errors make subprocess fail', testThrowingGenerator, 'duplex', false, execa);33test('WebTransform "transform" errors make subprocess fail', testThrowingGenerator, 'webTransform', false, execa);3435const 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};4445test('Generators errors make subprocess fail even when other output generators do not throw', testSingleErrorOutput, 'generator', execa);46test('Generators errors make subprocess fail even when other output generators do not throw, sync', testSingleErrorOutput, 'generator', execaSync);47test('Duplexes errors make subprocess fail even when other output generators do not throw', testSingleErrorOutput, 'duplex', execa);48test('WebTransform errors make subprocess fail even when other output generators do not throw', testSingleErrorOutput, 'webTransform', execa);4950const 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};6061test('Generators errors make subprocess fail even when other input generators do not throw', testSingleErrorInput, 'generator', execa);62test('Generators errors make subprocess fail even when other input generators do not throw, sync', testSingleErrorInput, 'generator', execaSync);63test('Duplexes errors make subprocess fail even when other input generators do not throw', testSingleErrorInput, 'duplex', execa);64test('WebTransform errors make subprocess fail even when other input generators do not throw', testSingleErrorInput, 'webTransform', execa);6566const 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};7273test('Running generators are canceled on subprocess abort', testGeneratorCancel, undefined);74test('Running generators are canceled on subprocess error', testGeneratorCancel, new Error('test'));7576const 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};8384test('Generators are destroyed on subprocess error, sync', testGeneratorDestroy, noopGenerator(false));85test('Generators are destroyed on subprocess error, async', testGeneratorDestroy, infiniteGenerator());8687test('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
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {foobarString} from '../helpers/input.js';4import {getOutputAsyncGenerator, getOutputGenerator, convertTransformToFinal} from '../helpers/generator.js';5import {setFixtureDir} from '../helpers/fixtures-dir.js';67setFixtureDir();89const testGeneratorFinal = async (t, fixtureName, execaMethod) => {10 const {stdout} = await execaMethod(fixtureName, {stdout: convertTransformToFinal(getOutputGenerator(foobarString)(), true)});11 t.is(stdout, foobarString);12};1314test('Generators "final" can be used', testGeneratorFinal, 'noop.js', execa);15test('Generators "final" is used even on empty streams', testGeneratorFinal, 'empty.js', execa);16test('Generators "final" can be used, sync', testGeneratorFinal, 'noop.js', execaSync);17test('Generators "final" is used even on empty streams, sync', testGeneratorFinal, 'empty.js', execaSync);1819const 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};2324test('Generators "final" can be used without "transform"', testFinalAlone, getOutputGenerator, execa);25test('Generators "final" can be used without "transform", sync', testFinalAlone, getOutputGenerator, execaSync);26test('Generators "final" can be used without "transform", async', testFinalAlone, getOutputAsyncGenerator, execa);2728const testFinalNoOutput = async (t, final, execaMethod) => {29 const {stdout} = await execaMethod('empty.js', {stdout: {final: final(foobarString)().transform}});30 t.is(stdout, foobarString);31};3233test('Generators "final" can be used without "transform" nor output', testFinalNoOutput, getOutputGenerator, execa);34test('Generators "final" can be used without "transform" nor output, sync', testFinalNoOutput, getOutputGenerator, execaSync);35test('Generators "final" can be used without "transform" nor output, async', testFinalNoOutput, getOutputAsyncGenerator, execa);
deleted:test/stdio/transform-input.js-158 removed
1import {Buffer} from 'node:buffer';2import test from 'ava';3import {execa, execaSync} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';5import {getStdio} from '../helpers/stdio.js';6import {7 foobarString,8 foobarUppercase,9 foobarHex,10 foobarUint8Array,11 foobarBuffer,12 foobarObject,13 foobarObjectString,14} from '../helpers/input.js';15import {generatorsMap} from '../helpers/map.js';1617setFixtureDir();1819const 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 };3031// eslint-disable-next-line max-params32const 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};3738test('Can use generators with result.stdin', testGeneratorInput, 0, false, false, 'generator', execa);39test('Can use generators with result.stdio[*] as input', testGeneratorInput, 3, false, false, 'generator', execa);40test('Can use generators with result.stdin, objectMode', testGeneratorInput, 0, true, false, 'generator', execa);41test('Can use generators with result.stdio[*] as input, objectMode', testGeneratorInput, 3, true, false, 'generator', execa);42test('Can use generators with result.stdin, noop transform', testGeneratorInput, 0, false, true, 'generator', execa);43test('Can use generators with result.stdio[*] as input, noop transform', testGeneratorInput, 3, false, true, 'generator', execa);44test('Can use generators with result.stdin, objectMode, noop transform', testGeneratorInput, 0, true, true, 'generator', execa);45test('Can use generators with result.stdio[*] as input, objectMode, noop transform', testGeneratorInput, 3, true, true, 'generator', execa);46test('Can use generators with result.stdin, sync', testGeneratorInput, 0, false, false, 'generator', execaSync);47test('Can use generators with result.stdin, objectMode, sync', testGeneratorInput, 0, true, false, 'generator', execaSync);48test('Can use generators with result.stdin, noop transform, sync', testGeneratorInput, 0, false, true, 'generator', execaSync);49test('Can use generators with result.stdin, objectMode, noop transform, sync', testGeneratorInput, 0, true, true, 'generator', execaSync);50test('Can use duplexes with result.stdin', testGeneratorInput, 0, false, false, 'duplex', execa);51test('Can use duplexes with result.stdio[*] as input', testGeneratorInput, 3, false, false, 'duplex', execa);52test('Can use duplexes with result.stdin, objectMode', testGeneratorInput, 0, true, false, 'duplex', execa);53test('Can use duplexes with result.stdio[*] as input, objectMode', testGeneratorInput, 3, true, false, 'duplex', execa);54test('Can use duplexes with result.stdin, noop transform', testGeneratorInput, 0, false, true, 'duplex', execa);55test('Can use duplexes with result.stdio[*] as input, noop transform', testGeneratorInput, 3, false, true, 'duplex', execa);56test('Can use duplexes with result.stdin, objectMode, noop transform', testGeneratorInput, 0, true, true, 'duplex', execa);57test('Can use duplexes with result.stdio[*] as input, objectMode, noop transform', testGeneratorInput, 3, true, true, 'duplex', execa);58test('Can use webTransforms with result.stdin', testGeneratorInput, 0, false, false, 'webTransform', execa);59test('Can use webTransforms with result.stdio[*] as input', testGeneratorInput, 3, false, false, 'webTransform', execa);60test('Can use webTransforms with result.stdin, objectMode', testGeneratorInput, 0, true, false, 'webTransform', execa);61test('Can use webTransforms with result.stdio[*] as input, objectMode', testGeneratorInput, 3, true, false, 'webTransform', execa);62test('Can use webTransforms with result.stdin, noop transform', testGeneratorInput, 0, false, true, 'webTransform', execa);63test('Can use webTransforms with result.stdio[*] as input, noop transform', testGeneratorInput, 3, false, true, 'webTransform', execa);64test('Can use webTransforms with result.stdin, objectMode, noop transform', testGeneratorInput, 0, true, true, 'webTransform', execa);65test('Can use webTransforms with result.stdio[*] as input, objectMode, noop transform', testGeneratorInput, 3, true, true, 'webTransform', execa);6667// eslint-disable-next-line max-params68const 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};7778test('Can use generators with subprocess.stdio[0] and default encoding', testGeneratorInputPipe, false, false, false, 'generator', [foobarString, 'utf8']);79test('Can use generators with subprocess.stdin and default encoding', testGeneratorInputPipe, true, false, false, 'generator', [foobarString, 'utf8']);80test('Can use generators with subprocess.stdio[0] and encoding "utf16le"', testGeneratorInputPipe, false, false, false, 'generator', [foobarString, 'utf16le']);81test('Can use generators with subprocess.stdin and encoding "utf16le"', testGeneratorInputPipe, true, false, false, 'generator', [foobarString, 'utf16le']);82test('Can use generators with subprocess.stdio[0] and encoding "buffer"', testGeneratorInputPipe, false, false, false, 'generator', [foobarBuffer, 'buffer']);83test('Can use generators with subprocess.stdin and encoding "buffer"', testGeneratorInputPipe, true, false, false, 'generator', [foobarBuffer, 'buffer']);84test('Can use generators with subprocess.stdio[0] and encoding "hex"', testGeneratorInputPipe, false, false, false, 'generator', [foobarHex, 'hex']);85test('Can use generators with subprocess.stdin and encoding "hex"', testGeneratorInputPipe, true, false, false, 'generator', [foobarHex, 'hex']);86test('Can use generators with subprocess.stdio[0], objectMode', testGeneratorInputPipe, false, true, false, 'generator', [foobarObject]);87test('Can use generators with subprocess.stdin, objectMode', testGeneratorInputPipe, true, true, false, 'generator', [foobarObject]);88test('Can use generators with subprocess.stdio[0] and default encoding, noop transform', testGeneratorInputPipe, false, false, true, 'generator', [foobarString, 'utf8']);89test('Can use generators with subprocess.stdin and default encoding, noop transform', testGeneratorInputPipe, true, false, true, 'generator', [foobarString, 'utf8']);90test('Can use generators with subprocess.stdio[0] and encoding "utf16le", noop transform', testGeneratorInputPipe, false, false, true, 'generator', [foobarString, 'utf16le']);91test('Can use generators with subprocess.stdin and encoding "utf16le", noop transform', testGeneratorInputPipe, true, false, true, 'generator', [foobarString, 'utf16le']);92test('Can use generators with subprocess.stdio[0] and encoding "buffer", noop transform', testGeneratorInputPipe, false, false, true, 'generator', [foobarBuffer, 'buffer']);93test('Can use generators with subprocess.stdin and encoding "buffer", noop transform', testGeneratorInputPipe, true, false, true, 'generator', [foobarBuffer, 'buffer']);94test('Can use generators with subprocess.stdio[0] and encoding "hex", noop transform', testGeneratorInputPipe, false, false, true, 'generator', [foobarHex, 'hex']);95test('Can use generators with subprocess.stdin and encoding "hex", noop transform', testGeneratorInputPipe, true, false, true, 'generator', [foobarHex, 'hex']);96test('Can use generators with subprocess.stdio[0], objectMode, noop transform', testGeneratorInputPipe, false, true, true, 'generator', [foobarObject]);97test('Can use generators with subprocess.stdin, objectMode, noop transform', testGeneratorInputPipe, true, true, true, 'generator', [foobarObject]);98test('Can use duplexes with subprocess.stdio[0] and default encoding', testGeneratorInputPipe, false, false, false, 'duplex', [foobarString, 'utf8']);99test('Can use duplexes with subprocess.stdin and default encoding', testGeneratorInputPipe, true, false, false, 'duplex', [foobarString, 'utf8']);100test('Can use duplexes with subprocess.stdio[0] and encoding "utf16le"', testGeneratorInputPipe, false, false, false, 'duplex', [foobarString, 'utf16le']);101test('Can use duplexes with subprocess.stdin and encoding "utf16le"', testGeneratorInputPipe, true, false, false, 'duplex', [foobarString, 'utf16le']);102test('Can use duplexes with subprocess.stdio[0] and encoding "buffer"', testGeneratorInputPipe, false, false, false, 'duplex', [foobarBuffer, 'buffer']);103test('Can use duplexes with subprocess.stdin and encoding "buffer"', testGeneratorInputPipe, true, false, false, 'duplex', [foobarBuffer, 'buffer']);104test('Can use duplexes with subprocess.stdio[0] and encoding "hex"', testGeneratorInputPipe, false, false, false, 'duplex', [foobarHex, 'hex']);105test('Can use duplexes with subprocess.stdin and encoding "hex"', testGeneratorInputPipe, true, false, false, 'duplex', [foobarHex, 'hex']);106test('Can use duplexes with subprocess.stdio[0], objectMode', testGeneratorInputPipe, false, true, false, 'duplex', [foobarObject]);107test('Can use duplexes with subprocess.stdin, objectMode', testGeneratorInputPipe, true, true, false, 'duplex', [foobarObject]);108test('Can use duplexes with subprocess.stdio[0] and default encoding, noop transform', testGeneratorInputPipe, false, false, true, 'duplex', [foobarString, 'utf8']);109test('Can use duplexes with subprocess.stdin and default encoding, noop transform', testGeneratorInputPipe, true, false, true, 'duplex', [foobarString, 'utf8']);110test('Can use duplexes with subprocess.stdio[0] and encoding "utf16le", noop transform', testGeneratorInputPipe, false, false, true, 'duplex', [foobarString, 'utf16le']);111test('Can use duplexes with subprocess.stdin and encoding "utf16le", noop transform', testGeneratorInputPipe, true, false, true, 'duplex', [foobarString, 'utf16le']);112test('Can use duplexes with subprocess.stdio[0] and encoding "buffer", noop transform', testGeneratorInputPipe, false, false, true, 'duplex', [foobarBuffer, 'buffer']);113test('Can use duplexes with subprocess.stdin and encoding "buffer", noop transform', testGeneratorInputPipe, true, false, true, 'duplex', [foobarBuffer, 'buffer']);114test('Can use duplexes with subprocess.stdio[0] and encoding "hex", noop transform', testGeneratorInputPipe, false, false, true, 'duplex', [foobarHex, 'hex']);115test('Can use duplexes with subprocess.stdin and encoding "hex", noop transform', testGeneratorInputPipe, true, false, true, 'duplex', [foobarHex, 'hex']);116test('Can use duplexes with subprocess.stdio[0], objectMode, noop transform', testGeneratorInputPipe, false, true, true, 'duplex', [foobarObject]);117test('Can use duplexes with subprocess.stdin, objectMode, noop transform', testGeneratorInputPipe, true, true, true, 'duplex', [foobarObject]);118test('Can use webTransforms with subprocess.stdio[0] and default encoding', testGeneratorInputPipe, false, false, false, 'webTransform', [foobarString, 'utf8']);119test('Can use webTransforms with subprocess.stdin and default encoding', testGeneratorInputPipe, true, false, false, 'webTransform', [foobarString, 'utf8']);120test('Can use webTransforms with subprocess.stdio[0] and encoding "utf16le"', testGeneratorInputPipe, false, false, false, 'webTransform', [foobarString, 'utf16le']);121test('Can use webTransforms with subprocess.stdin and encoding "utf16le"', testGeneratorInputPipe, true, false, false, 'webTransform', [foobarString, 'utf16le']);122test('Can use webTransforms with subprocess.stdio[0] and encoding "buffer"', testGeneratorInputPipe, false, false, false, 'webTransform', [foobarBuffer, 'buffer']);123test('Can use webTransforms with subprocess.stdin and encoding "buffer"', testGeneratorInputPipe, true, false, false, 'webTransform', [foobarBuffer, 'buffer']);124test('Can use webTransforms with subprocess.stdio[0] and encoding "hex"', testGeneratorInputPipe, false, false, false, 'webTransform', [foobarHex, 'hex']);125test('Can use webTransforms with subprocess.stdin and encoding "hex"', testGeneratorInputPipe, true, false, false, 'webTransform', [foobarHex, 'hex']);126test('Can use webTransforms with subprocess.stdio[0], objectMode', testGeneratorInputPipe, false, true, false, 'webTransform', [foobarObject]);127test('Can use webTransforms with subprocess.stdin, objectMode', testGeneratorInputPipe, true, true, false, 'webTransform', [foobarObject]);128test('Can use webTransforms with subprocess.stdio[0] and default encoding, noop transform', testGeneratorInputPipe, false, false, true, 'webTransform', [foobarString, 'utf8']);129test('Can use webTransforms with subprocess.stdin and default encoding, noop transform', testGeneratorInputPipe, true, false, true, 'webTransform', [foobarString, 'utf8']);130test('Can use webTransforms with subprocess.stdio[0] and encoding "utf16le", noop transform', testGeneratorInputPipe, false, false, true, 'webTransform', [foobarString, 'utf16le']);131test('Can use webTransforms with subprocess.stdin and encoding "utf16le", noop transform', testGeneratorInputPipe, true, false, true, 'webTransform', [foobarString, 'utf16le']);132test('Can use webTransforms with subprocess.stdio[0] and encoding "buffer", noop transform', testGeneratorInputPipe, false, false, true, 'webTransform', [foobarBuffer, 'buffer']);133test('Can use webTransforms with subprocess.stdin and encoding "buffer", noop transform', testGeneratorInputPipe, true, false, true, 'webTransform', [foobarBuffer, 'buffer']);134test('Can use webTransforms with subprocess.stdio[0] and encoding "hex", noop transform', testGeneratorInputPipe, false, false, true, 'webTransform', [foobarHex, 'hex']);135test('Can use webTransforms with subprocess.stdin and encoding "hex", noop transform', testGeneratorInputPipe, true, false, true, 'webTransform', [foobarHex, 'hex']);136test('Can use webTransforms with subprocess.stdio[0], objectMode, noop transform', testGeneratorInputPipe, false, true, true, 'webTransform', [foobarObject]);137test('Can use webTransforms with subprocess.stdin, objectMode, noop transform', testGeneratorInputPipe, true, true, true, 'webTransform', [foobarObject]);138139const 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};146147test('Can use generators with subprocess.stdio[*] as input', testGeneratorStdioInputPipe, false, false, 'generator');148test('Can use generators with subprocess.stdio[*] as input, objectMode', testGeneratorStdioInputPipe, true, false, 'generator');149test('Can use generators with subprocess.stdio[*] as input, noop transform', testGeneratorStdioInputPipe, false, true, 'generator');150test('Can use generators with subprocess.stdio[*] as input, objectMode, noop transform', testGeneratorStdioInputPipe, true, true, 'generator');151test('Can use duplexes with subprocess.stdio[*] as input', testGeneratorStdioInputPipe, false, false, 'duplex');152test('Can use duplexes with subprocess.stdio[*] as input, objectMode', testGeneratorStdioInputPipe, true, false, 'duplex');153test('Can use duplexes with subprocess.stdio[*] as input, noop transform', testGeneratorStdioInputPipe, false, true, 'duplex');154test('Can use duplexes with subprocess.stdio[*] as input, objectMode, noop transform', testGeneratorStdioInputPipe, true, true, 'duplex');155test('Can use webTransforms with subprocess.stdio[*] as input', testGeneratorStdioInputPipe, false, false, 'webTransform');156test('Can use webTransforms with subprocess.stdio[*] as input, objectMode', testGeneratorStdioInputPipe, true, false, 'webTransform');157test('Can use webTransforms with subprocess.stdio[*] as input, noop transform', testGeneratorStdioInputPipe, false, true, 'webTransform');158test('Can use webTransforms with subprocess.stdio[*] as input, objectMode, noop transform', testGeneratorStdioInputPipe, true, true, 'webTransform');
deleted:test/stdio/transform-mixed.js-104 removed
1import {readFile, writeFile, rm} from 'node:fs/promises';2import {PassThrough} from 'node:stream';3import test from 'ava';4import getStream from 'get-stream';5import tempfile from 'tempfile';6import {execa, execaSync} from '../../index.js';7import {setFixtureDir} from '../helpers/fixtures-dir.js';8import {foobarString, foobarUppercase, foobarUint8Array} from '../helpers/input.js';9import {uppercaseGenerator} from '../helpers/generator.js';10import {uppercaseBufferDuplex} from '../helpers/duplex.js';11import {uppercaseBufferWebTransform} from '../helpers/web-transform.js';12import {generatorsMap} from '../helpers/map.js';1314setFixtureDir();1516const 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};2021test('Can use generators with input option', testInputOption, 'generator', execa);22test('Can use generators with input option, sync', testInputOption, 'generator', execaSync);23test('Can use duplexes with input option', testInputOption, 'duplex', execa);24test('Can use webTransforms with input option', testInputOption, 'webTransform', execa);2526// eslint-disable-next-line max-params27const 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};3839test('Can use generators with a file as input', testInputFile, uppercaseGenerator(), false, false, execa);40test('Can use generators with a file as input, reversed', testInputFile, uppercaseGenerator(), false, true, execa);41test('Can use generators with inputFile option', testInputFile, uppercaseGenerator(), true, false, execa);42test('Can use generators with a file as input, sync', testInputFile, uppercaseGenerator(), false, false, execaSync);43test('Can use generators with a file as input, reversed, sync', testInputFile, uppercaseGenerator(), false, true, execaSync);44test('Can use generators with inputFile option, sync', testInputFile, uppercaseGenerator(), true, false, execaSync);45test('Can use duplexes with a file as input', testInputFile, uppercaseBufferDuplex(), false, false, execa);46test('Can use duplexes with a file as input, reversed', testInputFile, uppercaseBufferDuplex(), false, true, execa);47test('Can use duplexes with inputFile option', testInputFile, uppercaseBufferDuplex(), true, false, execa);48test('Can use webTransforms with a file as input', testInputFile, uppercaseBufferWebTransform(), false, false, execa);49test('Can use webTransforms with a file as input, reversed', testInputFile, uppercaseBufferWebTransform(), false, true, execa);50test('Can use webTransforms with inputFile option', testInputFile, uppercaseBufferWebTransform(), true, false, execa);5152const 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};6162test('Can use generators with a file as output', testOutputFile, false, 'generator', execa);63test('Can use generators with a file as output, reversed', testOutputFile, true, 'generator', execa);64test('Can use generators with a file as output, sync', testOutputFile, false, 'generator', execaSync);65test('Can use generators with a file as output, reversed, sync', testOutputFile, true, 'generator', execaSync);66test('Can use duplexes with a file as output', testOutputFile, false, 'duplex', execa);67test('Can use duplexes with a file as output, reversed', testOutputFile, true, 'duplex', execa);68test('Can use webTransforms with a file as output', testOutputFile, false, 'webTransform', execa);69test('Can use webTransforms with a file as output, reversed', testOutputFile, true, 'webTransform', execa);7071const 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};8081test('Can use generators to a Writable stream', testWritableDestination, 'generator');82test('Can use duplexes to a Writable stream', testWritableDestination, 'duplex');83test('Can use webTransforms to a Writable stream', testWritableDestination, 'webTransform');8485const 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};9293test('Can use generators from a Readable stream', testReadableSource, 'generator');94test('Can use duplexes from a Readable stream', testReadableSource, 'duplex');95test('Can use webTransforms from a Readable stream', testReadableSource, 'webTransform');9697const testInherit = async (t, type) => {98 const {stdout} = await execa('nested-inherit.js', [type]);99 t.is(stdout, foobarUppercase);100};101102test('Can use generators with "inherit"', testInherit, 'generator');103test('Can use duplexes with "inherit"', testInherit, 'duplex');104test('Can use webTransforms with "inherit"', testInherit, 'webTransform');
deleted:test/stdio/transform-output.js-261 removed
1import test from 'ava';2import getStream, {getStreamAsArray} from 'get-stream';3import {execa, execaSync} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';5import {getStdio} from '../helpers/stdio.js';6import {foobarString, foobarUppercase, foobarObject} from '../helpers/input.js';7import {generatorsMap} from '../helpers/map.js';89setFixtureDir();1011const 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 };2223// eslint-disable-next-line max-params24const 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};3132test('Can use generators with result.stdio[1]', testGeneratorOutput, 1, true, false, false, false, 'generator', execa);33test('Can use generators with result.stdout', testGeneratorOutput, 1, true, true, false, false, 'generator', execa);34test('Can use generators with result.stdio[2]', testGeneratorOutput, 2, true, false, false, false, 'generator', execa);35test('Can use generators with result.stderr', testGeneratorOutput, 2, true, true, false, false, 'generator', execa);36test('Can use generators with result.stdio[*] as output', testGeneratorOutput, 3, true, false, false, false, 'generator', execa);37test('Can use generators with error.stdio[1]', testGeneratorOutput, 1, false, false, false, false, 'generator', execa);38test('Can use generators with error.stdout', testGeneratorOutput, 1, false, true, false, false, 'generator', execa);39test('Can use generators with error.stdio[2]', testGeneratorOutput, 2, false, false, false, false, 'generator', execa);40test('Can use generators with error.stderr', testGeneratorOutput, 2, false, true, false, false, 'generator', execa);41test('Can use generators with error.stdio[*] as output', testGeneratorOutput, 3, false, false, false, false, 'generator', execa);42test('Can use generators with result.stdio[1], objectMode', testGeneratorOutput, 1, true, false, true, false, 'generator', execa);43test('Can use generators with result.stdout, objectMode', testGeneratorOutput, 1, true, true, true, false, 'generator', execa);44test('Can use generators with result.stdio[2], objectMode', testGeneratorOutput, 2, true, false, true, false, 'generator', execa);45test('Can use generators with result.stderr, objectMode', testGeneratorOutput, 2, true, true, true, false, 'generator', execa);46test('Can use generators with result.stdio[*] as output, objectMode', testGeneratorOutput, 3, true, false, true, false, 'generator', execa);47test('Can use generators with error.stdio[1], objectMode', testGeneratorOutput, 1, false, false, true, false, 'generator', execa);48test('Can use generators with error.stdout, objectMode', testGeneratorOutput, 1, false, true, true, false, 'generator', execa);49test('Can use generators with error.stdio[2], objectMode', testGeneratorOutput, 2, false, false, true, false, 'generator', execa);50test('Can use generators with error.stderr, objectMode', testGeneratorOutput, 2, false, true, true, false, 'generator', execa);51test('Can use generators with error.stdio[*] as output, objectMode', testGeneratorOutput, 3, false, false, true, false, 'generator', execa);52test('Can use generators with result.stdio[1], noop transform', testGeneratorOutput, 1, true, false, false, true, 'generator', execa);53test('Can use generators with result.stdout, noop transform', testGeneratorOutput, 1, true, true, false, true, 'generator', execa);54test('Can use generators with result.stdio[2], noop transform', testGeneratorOutput, 2, true, false, false, true, 'generator', execa);55test('Can use generators with result.stderr, noop transform', testGeneratorOutput, 2, true, true, false, true, 'generator', execa);56test('Can use generators with result.stdio[*] as output, noop transform', testGeneratorOutput, 3, true, false, false, true, 'generator', execa);57test('Can use generators with error.stdio[1], noop transform', testGeneratorOutput, 1, false, false, false, true, 'generator', execa);58test('Can use generators with error.stdout, noop transform', testGeneratorOutput, 1, false, true, false, true, 'generator', execa);59test('Can use generators with error.stdio[2], noop transform', testGeneratorOutput, 2, false, false, false, true, 'generator', execa);60test('Can use generators with error.stderr, noop transform', testGeneratorOutput, 2, false, true, false, true, 'generator', execa);61test('Can use generators with error.stdio[*] as output, noop transform', testGeneratorOutput, 3, false, false, false, true, 'generator', execa);62test('Can use generators with result.stdio[1], objectMode, noop transform', testGeneratorOutput, 1, true, false, true, true, 'generator', execa);63test('Can use generators with result.stdout, objectMode, noop transform', testGeneratorOutput, 1, true, true, true, true, 'generator', execa);64test('Can use generators with result.stdio[2], objectMode, noop transform', testGeneratorOutput, 2, true, false, true, true, 'generator', execa);65test('Can use generators with result.stderr, objectMode, noop transform', testGeneratorOutput, 2, true, true, true, true, 'generator', execa);66test('Can use generators with result.stdio[*] as output, objectMode, noop transform', testGeneratorOutput, 3, true, false, true, true, 'generator', execa);67test('Can use generators with error.stdio[1], objectMode, noop transform', testGeneratorOutput, 1, false, false, true, true, 'generator', execa);68test('Can use generators with error.stdout, objectMode, noop transform', testGeneratorOutput, 1, false, true, true, true, 'generator', execa);69test('Can use generators with error.stdio[2], objectMode, noop transform', testGeneratorOutput, 2, false, false, true, true, 'generator', execa);70test('Can use generators with error.stderr, objectMode, noop transform', testGeneratorOutput, 2, false, true, true, true, 'generator', execa);71test('Can use generators with error.stdio[*] as output, objectMode, noop transform', testGeneratorOutput, 3, false, false, true, true, 'generator', execa);72test('Can use generators with result.stdio[1], sync', testGeneratorOutput, 1, true, false, false, false, 'generator', execaSync);73test('Can use generators with result.stdout, sync', testGeneratorOutput, 1, true, true, false, false, 'generator', execaSync);74test('Can use generators with result.stdio[2], sync', testGeneratorOutput, 2, true, false, false, false, 'generator', execaSync);75test('Can use generators with result.stderr, sync', testGeneratorOutput, 2, true, true, false, false, 'generator', execaSync);76test('Can use generators with result.stdio[*] as output, sync', testGeneratorOutput, 3, true, false, false, false, 'generator', execaSync);77test('Can use generators with error.stdio[1], sync', testGeneratorOutput, 1, false, false, false, false, 'generator', execaSync);78test('Can use generators with error.stdout, sync', testGeneratorOutput, 1, false, true, false, false, 'generator', execaSync);79test('Can use generators with error.stdio[2], sync', testGeneratorOutput, 2, false, false, false, false, 'generator', execaSync);80test('Can use generators with error.stderr, sync', testGeneratorOutput, 2, false, true, false, false, 'generator', execaSync);81test('Can use generators with error.stdio[*] as output, sync', testGeneratorOutput, 3, false, false, false, false, 'generator', execaSync);82test('Can use generators with result.stdio[1], objectMode, sync', testGeneratorOutput, 1, true, false, true, false, 'generator', execaSync);83test('Can use generators with result.stdout, objectMode, sync', testGeneratorOutput, 1, true, true, true, false, 'generator', execaSync);84test('Can use generators with result.stdio[2], objectMode, sync', testGeneratorOutput, 2, true, false, true, false, 'generator', execaSync);85test('Can use generators with result.stderr, objectMode, sync', testGeneratorOutput, 2, true, true, true, false, 'generator', execaSync);86test('Can use generators with result.stdio[*] as output, objectMode, sync', testGeneratorOutput, 3, true, false, true, false, 'generator', execaSync);87test('Can use generators with error.stdio[1], objectMode, sync', testGeneratorOutput, 1, false, false, true, false, 'generator', execaSync);88test('Can use generators with error.stdout, objectMode, sync', testGeneratorOutput, 1, false, true, true, false, 'generator', execaSync);89test('Can use generators with error.stdio[2], objectMode, sync', testGeneratorOutput, 2, false, false, true, false, 'generator', execaSync);90test('Can use generators with error.stderr, objectMode, sync', testGeneratorOutput, 2, false, true, true, false, 'generator', execaSync);91test('Can use generators with error.stdio[*] as output, objectMode, sync', testGeneratorOutput, 3, false, false, true, false, 'generator', execaSync);92test('Can use generators with result.stdio[1], noop transform, sync', testGeneratorOutput, 1, true, false, false, true, 'generator', execaSync);93test('Can use generators with result.stdout, noop transform, sync', testGeneratorOutput, 1, true, true, false, true, 'generator', execaSync);94test('Can use generators with result.stdio[2], noop transform, sync', testGeneratorOutput, 2, true, false, false, true, 'generator', execaSync);95test('Can use generators with result.stderr, noop transform, sync', testGeneratorOutput, 2, true, true, false, true, 'generator', execaSync);96test('Can use generators with result.stdio[*] as output, noop transform, sync', testGeneratorOutput, 3, true, false, false, true, 'generator', execaSync);97test('Can use generators with error.stdio[1], noop transform, sync', testGeneratorOutput, 1, false, false, false, true, 'generator', execaSync);98test('Can use generators with error.stdout, noop transform, sync', testGeneratorOutput, 1, false, true, false, true, 'generator', execaSync);99test('Can use generators with error.stdio[2], noop transform, sync', testGeneratorOutput, 2, false, false, false, true, 'generator', execaSync);100test('Can use generators with error.stderr, noop transform, sync', testGeneratorOutput, 2, false, true, false, true, 'generator', execaSync);101test('Can use generators with error.stdio[*] as output, noop transform, sync', testGeneratorOutput, 3, false, false, false, true, 'generator', execaSync);102test('Can use generators with result.stdio[1], objectMode, noop transform, sync', testGeneratorOutput, 1, true, false, true, true, 'generator', execaSync);103test('Can use generators with result.stdout, objectMode, noop transform, sync', testGeneratorOutput, 1, true, true, true, true, 'generator', execaSync);104test('Can use generators with result.stdio[2], objectMode, noop transform, sync', testGeneratorOutput, 2, true, false, true, true, 'generator', execaSync);105test('Can use generators with result.stderr, objectMode, noop transform, sync', testGeneratorOutput, 2, true, true, true, true, 'generator', execaSync);106test('Can use generators with result.stdio[*] as output, objectMode, noop transform, sync', testGeneratorOutput, 3, true, false, true, true, 'generator', execaSync);107test('Can use generators with error.stdio[1], objectMode, noop transform, sync', testGeneratorOutput, 1, false, false, true, true, 'generator', execaSync);108test('Can use generators with error.stdout, objectMode, noop transform, sync', testGeneratorOutput, 1, false, true, true, true, 'generator', execaSync);109test('Can use generators with error.stdio[2], objectMode, noop transform, sync', testGeneratorOutput, 2, false, false, true, true, 'generator', execaSync);110test('Can use generators with error.stderr, objectMode, noop transform, sync', testGeneratorOutput, 2, false, true, true, true, 'generator', execaSync);111test('Can use generators with error.stdio[*] as output, objectMode, noop transform, sync', testGeneratorOutput, 3, false, false, true, true, 'generator', execaSync);112test('Can use duplexes with result.stdio[1]', testGeneratorOutput, 1, true, false, false, false, 'duplex', execa);113test('Can use duplexes with result.stdout', testGeneratorOutput, 1, true, true, false, false, 'duplex', execa);114test('Can use duplexes with result.stdio[2]', testGeneratorOutput, 2, true, false, false, false, 'duplex', execa);115test('Can use duplexes with result.stderr', testGeneratorOutput, 2, true, true, false, false, 'duplex', execa);116test('Can use duplexes with result.stdio[*] as output', testGeneratorOutput, 3, true, false, false, false, 'duplex', execa);117test('Can use duplexes with error.stdio[1]', testGeneratorOutput, 1, false, false, false, false, 'duplex', execa);118test('Can use duplexes with error.stdout', testGeneratorOutput, 1, false, true, false, false, 'duplex', execa);119test('Can use duplexes with error.stdio[2]', testGeneratorOutput, 2, false, false, false, false, 'duplex', execa);120test('Can use duplexes with error.stderr', testGeneratorOutput, 2, false, true, false, false, 'duplex', execa);121test('Can use duplexes with error.stdio[*] as output', testGeneratorOutput, 3, false, false, false, false, 'duplex', execa);122test('Can use duplexes with result.stdio[1], objectMode', testGeneratorOutput, 1, true, false, true, false, 'duplex', execa);123test('Can use duplexes with result.stdout, objectMode', testGeneratorOutput, 1, true, true, true, false, 'duplex', execa);124test('Can use duplexes with result.stdio[2], objectMode', testGeneratorOutput, 2, true, false, true, false, 'duplex', execa);125test('Can use duplexes with result.stderr, objectMode', testGeneratorOutput, 2, true, true, true, false, 'duplex', execa);126test('Can use duplexes with result.stdio[*] as output, objectMode', testGeneratorOutput, 3, true, false, true, false, 'duplex', execa);127test('Can use duplexes with error.stdio[1], objectMode', testGeneratorOutput, 1, false, false, true, false, 'duplex', execa);128test('Can use duplexes with error.stdout, objectMode', testGeneratorOutput, 1, false, true, true, false, 'duplex', execa);129test('Can use duplexes with error.stdio[2], objectMode', testGeneratorOutput, 2, false, false, true, false, 'duplex', execa);130test('Can use duplexes with error.stderr, objectMode', testGeneratorOutput, 2, false, true, true, false, 'duplex', execa);131test('Can use duplexes with error.stdio[*] as output, objectMode', testGeneratorOutput, 3, false, false, true, false, 'duplex', execa);132test('Can use duplexes with result.stdio[1], noop transform', testGeneratorOutput, 1, true, false, false, true, 'duplex', execa);133test('Can use duplexes with result.stdout, noop transform', testGeneratorOutput, 1, true, true, false, true, 'duplex', execa);134test('Can use duplexes with result.stdio[2], noop transform', testGeneratorOutput, 2, true, false, false, true, 'duplex', execa);135test('Can use duplexes with result.stderr, noop transform', testGeneratorOutput, 2, true, true, false, true, 'duplex', execa);136test('Can use duplexes with result.stdio[*] as output, noop transform', testGeneratorOutput, 3, true, false, false, true, 'duplex', execa);137test('Can use duplexes with error.stdio[1], noop transform', testGeneratorOutput, 1, false, false, false, true, 'duplex', execa);138test('Can use duplexes with error.stdout, noop transform', testGeneratorOutput, 1, false, true, false, true, 'duplex', execa);139test('Can use duplexes with error.stdio[2], noop transform', testGeneratorOutput, 2, false, false, false, true, 'duplex', execa);140test('Can use duplexes with error.stderr, noop transform', testGeneratorOutput, 2, false, true, false, true, 'duplex', execa);141test('Can use duplexes with error.stdio[*] as output, noop transform', testGeneratorOutput, 3, false, false, false, true, 'duplex', execa);142test('Can use duplexes with result.stdio[1], objectMode, noop transform', testGeneratorOutput, 1, true, false, true, true, 'duplex', execa);143test('Can use duplexes with result.stdout, objectMode, noop transform', testGeneratorOutput, 1, true, true, true, true, 'duplex', execa);144test('Can use duplexes with result.stdio[2], objectMode, noop transform', testGeneratorOutput, 2, true, false, true, true, 'duplex', execa);145test('Can use duplexes with result.stderr, objectMode, noop transform', testGeneratorOutput, 2, true, true, true, true, 'duplex', execa);146test('Can use duplexes with result.stdio[*] as output, objectMode, noop transform', testGeneratorOutput, 3, true, false, true, true, 'duplex', execa);147test('Can use duplexes with error.stdio[1], objectMode, noop transform', testGeneratorOutput, 1, false, false, true, true, 'duplex', execa);148test('Can use duplexes with error.stdout, objectMode, noop transform', testGeneratorOutput, 1, false, true, true, true, 'duplex', execa);149test('Can use duplexes with error.stdio[2], objectMode, noop transform', testGeneratorOutput, 2, false, false, true, true, 'duplex', execa);150test('Can use duplexes with error.stderr, objectMode, noop transform', testGeneratorOutput, 2, false, true, true, true, 'duplex', execa);151test('Can use duplexes with error.stdio[*] as output, objectMode, noop transform', testGeneratorOutput, 3, false, false, true, true, 'duplex', execa);152test('Can use webTransforms with result.stdio[1]', testGeneratorOutput, 1, true, false, false, false, 'webTransform', execa);153test('Can use webTransforms with result.stdout', testGeneratorOutput, 1, true, true, false, false, 'webTransform', execa);154test('Can use webTransforms with result.stdio[2]', testGeneratorOutput, 2, true, false, false, false, 'webTransform', execa);155test('Can use webTransforms with result.stderr', testGeneratorOutput, 2, true, true, false, false, 'webTransform', execa);156test('Can use webTransforms with result.stdio[*] as output', testGeneratorOutput, 3, true, false, false, false, 'webTransform', execa);157test('Can use webTransforms with error.stdio[1]', testGeneratorOutput, 1, false, false, false, false, 'webTransform', execa);158test('Can use webTransforms with error.stdout', testGeneratorOutput, 1, false, true, false, false, 'webTransform', execa);159test('Can use webTransforms with error.stdio[2]', testGeneratorOutput, 2, false, false, false, false, 'webTransform', execa);160test('Can use webTransforms with error.stderr', testGeneratorOutput, 2, false, true, false, false, 'webTransform', execa);161test('Can use webTransforms with error.stdio[*] as output', testGeneratorOutput, 3, false, false, false, false, 'webTransform', execa);162test('Can use webTransforms with result.stdio[1], objectMode', testGeneratorOutput, 1, true, false, true, false, 'webTransform', execa);163test('Can use webTransforms with result.stdout, objectMode', testGeneratorOutput, 1, true, true, true, false, 'webTransform', execa);164test('Can use webTransforms with result.stdio[2], objectMode', testGeneratorOutput, 2, true, false, true, false, 'webTransform', execa);165test('Can use webTransforms with result.stderr, objectMode', testGeneratorOutput, 2, true, true, true, false, 'webTransform', execa);166test('Can use webTransforms with result.stdio[*] as output, objectMode', testGeneratorOutput, 3, true, false, true, false, 'webTransform', execa);167test('Can use webTransforms with error.stdio[1], objectMode', testGeneratorOutput, 1, false, false, true, false, 'webTransform', execa);168test('Can use webTransforms with error.stdout, objectMode', testGeneratorOutput, 1, false, true, true, false, 'webTransform', execa);169test('Can use webTransforms with error.stdio[2], objectMode', testGeneratorOutput, 2, false, false, true, false, 'webTransform', execa);170test('Can use webTransforms with error.stderr, objectMode', testGeneratorOutput, 2, false, true, true, false, 'webTransform', execa);171test('Can use webTransforms with error.stdio[*] as output, objectMode', testGeneratorOutput, 3, false, false, true, false, 'webTransform', execa);172test('Can use webTransforms with result.stdio[1], noop transform', testGeneratorOutput, 1, true, false, false, true, 'webTransform', execa);173test('Can use webTransforms with result.stdout, noop transform', testGeneratorOutput, 1, true, true, false, true, 'webTransform', execa);174test('Can use webTransforms with result.stdio[2], noop transform', testGeneratorOutput, 2, true, false, false, true, 'webTransform', execa);175test('Can use webTransforms with result.stderr, noop transform', testGeneratorOutput, 2, true, true, false, true, 'webTransform', execa);176test('Can use webTransforms with result.stdio[*] as output, noop transform', testGeneratorOutput, 3, true, false, false, true, 'webTransform', execa);177test('Can use webTransforms with error.stdio[1], noop transform', testGeneratorOutput, 1, false, false, false, true, 'webTransform', execa);178test('Can use webTransforms with error.stdout, noop transform', testGeneratorOutput, 1, false, true, false, true, 'webTransform', execa);179test('Can use webTransforms with error.stdio[2], noop transform', testGeneratorOutput, 2, false, false, false, true, 'webTransform', execa);180test('Can use webTransforms with error.stderr, noop transform', testGeneratorOutput, 2, false, true, false, true, 'webTransform', execa);181test('Can use webTransforms with error.stdio[*] as output, noop transform', testGeneratorOutput, 3, false, false, false, true, 'webTransform', execa);182test('Can use webTransforms with result.stdio[1], objectMode, noop transform', testGeneratorOutput, 1, true, false, true, true, 'webTransform', execa);183test('Can use webTransforms with result.stdout, objectMode, noop transform', testGeneratorOutput, 1, true, true, true, true, 'webTransform', execa);184test('Can use webTransforms with result.stdio[2], objectMode, noop transform', testGeneratorOutput, 2, true, false, true, true, 'webTransform', execa);185test('Can use webTransforms with result.stderr, objectMode, noop transform', testGeneratorOutput, 2, true, true, true, true, 'webTransform', execa);186test('Can use webTransforms with result.stdio[*] as output, objectMode, noop transform', testGeneratorOutput, 3, true, false, true, true, 'webTransform', execa);187test('Can use webTransforms with error.stdio[1], objectMode, noop transform', testGeneratorOutput, 1, false, false, true, true, 'webTransform', execa);188test('Can use webTransforms with error.stdout, objectMode, noop transform', testGeneratorOutput, 1, false, true, true, true, 'webTransform', execa);189test('Can use webTransforms with error.stdio[2], objectMode, noop transform', testGeneratorOutput, 2, false, false, true, true, 'webTransform', execa);190test('Can use webTransforms with error.stderr, objectMode, noop transform', testGeneratorOutput, 2, false, true, true, true, 'webTransform', execa);191test('Can use webTransforms with error.stdio[*] as output, objectMode, noop transform', testGeneratorOutput, 3, false, false, true, true, 'webTransform', execa);192193// eslint-disable-next-line max-params194const 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};201202test('Can use generators with subprocess.stdio[1]', testGeneratorOutputPipe, 1, false, false, false, 'generator');203test('Can use generators with subprocess.stdout', testGeneratorOutputPipe, 1, true, false, false, 'generator');204test('Can use generators with subprocess.stdio[2]', testGeneratorOutputPipe, 2, false, false, false, 'generator');205test('Can use generators with subprocess.stderr', testGeneratorOutputPipe, 2, true, false, false, 'generator');206test('Can use generators with subprocess.stdio[*] as output', testGeneratorOutputPipe, 3, false, false, false, 'generator');207test('Can use generators with subprocess.stdio[1], objectMode', testGeneratorOutputPipe, 1, false, true, false, 'generator');208test('Can use generators with subprocess.stdout, objectMode', testGeneratorOutputPipe, 1, true, true, false, 'generator');209test('Can use generators with subprocess.stdio[2], objectMode', testGeneratorOutputPipe, 2, false, true, false, 'generator');210test('Can use generators with subprocess.stderr, objectMode', testGeneratorOutputPipe, 2, true, true, false, 'generator');211test('Can use generators with subprocess.stdio[*] as output, objectMode', testGeneratorOutputPipe, 3, false, true, false, 'generator');212test('Can use generators with subprocess.stdio[1], noop transform', testGeneratorOutputPipe, 1, false, false, true, 'generator');213test('Can use generators with subprocess.stdout, noop transform', testGeneratorOutputPipe, 1, true, false, true, 'generator');214test('Can use generators with subprocess.stdio[2], noop transform', testGeneratorOutputPipe, 2, false, false, true, 'generator');215test('Can use generators with subprocess.stderr, noop transform', testGeneratorOutputPipe, 2, true, false, true, 'generator');216test('Can use generators with subprocess.stdio[*] as output, noop transform', testGeneratorOutputPipe, 3, false, false, true, 'generator');217test('Can use generators with subprocess.stdio[1], objectMode, noop transform', testGeneratorOutputPipe, 1, false, true, true, 'generator');218test('Can use generators with subprocess.stdout, objectMode, noop transform', testGeneratorOutputPipe, 1, true, true, true, 'generator');219test('Can use generators with subprocess.stdio[2], objectMode, noop transform', testGeneratorOutputPipe, 2, false, true, true, 'generator');220test('Can use generators with subprocess.stderr, objectMode, noop transform', testGeneratorOutputPipe, 2, true, true, true, 'generator');221test('Can use generators with subprocess.stdio[*] as output, objectMode, noop transform', testGeneratorOutputPipe, 3, false, true, true, 'generator');222test('Can use duplexes with subprocess.stdio[1]', testGeneratorOutputPipe, 1, false, false, false, 'duplex');223test('Can use duplexes with subprocess.stdout', testGeneratorOutputPipe, 1, true, false, false, 'duplex');224test('Can use duplexes with subprocess.stdio[2]', testGeneratorOutputPipe, 2, false, false, false, 'duplex');225test('Can use duplexes with subprocess.stderr', testGeneratorOutputPipe, 2, true, false, false, 'duplex');226test('Can use duplexes with subprocess.stdio[*] as output', testGeneratorOutputPipe, 3, false, false, false, 'duplex');227test('Can use duplexes with subprocess.stdio[1], objectMode', testGeneratorOutputPipe, 1, false, true, false, 'duplex');228test('Can use duplexes with subprocess.stdout, objectMode', testGeneratorOutputPipe, 1, true, true, false, 'duplex');229test('Can use duplexes with subprocess.stdio[2], objectMode', testGeneratorOutputPipe, 2, false, true, false, 'duplex');230test('Can use duplexes with subprocess.stderr, objectMode', testGeneratorOutputPipe, 2, true, true, false, 'duplex');231test('Can use duplexes with subprocess.stdio[*] as output, objectMode', testGeneratorOutputPipe, 3, false, true, false, 'duplex');232test('Can use duplexes with subprocess.stdio[1], noop transform', testGeneratorOutputPipe, 1, false, false, true, 'duplex');233test('Can use duplexes with subprocess.stdout, noop transform', testGeneratorOutputPipe, 1, true, false, true, 'duplex');234test('Can use duplexes with subprocess.stdio[2], noop transform', testGeneratorOutputPipe, 2, false, false, true, 'duplex');235test('Can use duplexes with subprocess.stderr, noop transform', testGeneratorOutputPipe, 2, true, false, true, 'duplex');236test('Can use duplexes with subprocess.stdio[*] as output, noop transform', testGeneratorOutputPipe, 3, false, false, true, 'duplex');237test('Can use duplexes with subprocess.stdio[1], objectMode, noop transform', testGeneratorOutputPipe, 1, false, true, true, 'duplex');238test('Can use duplexes with subprocess.stdout, objectMode, noop transform', testGeneratorOutputPipe, 1, true, true, true, 'duplex');239test('Can use duplexes with subprocess.stdio[2], objectMode, noop transform', testGeneratorOutputPipe, 2, false, true, true, 'duplex');240test('Can use duplexes with subprocess.stderr, objectMode, noop transform', testGeneratorOutputPipe, 2, true, true, true, 'duplex');241test('Can use duplexes with subprocess.stdio[*] as output, objectMode, noop transform', testGeneratorOutputPipe, 3, false, true, true, 'duplex');242test('Can use webTransforms with subprocess.stdio[1]', testGeneratorOutputPipe, 1, false, false, false, 'webTransform');243test('Can use webTransforms with subprocess.stdout', testGeneratorOutputPipe, 1, true, false, false, 'webTransform');244test('Can use webTransforms with subprocess.stdio[2]', testGeneratorOutputPipe, 2, false, false, false, 'webTransform');245test('Can use webTransforms with subprocess.stderr', testGeneratorOutputPipe, 2, true, false, false, 'webTransform');246test('Can use webTransforms with subprocess.stdio[*] as output', testGeneratorOutputPipe, 3, false, false, false, 'webTransform');247test('Can use webTransforms with subprocess.stdio[1], objectMode', testGeneratorOutputPipe, 1, false, true, false, 'webTransform');248test('Can use webTransforms with subprocess.stdout, objectMode', testGeneratorOutputPipe, 1, true, true, false, 'webTransform');249test('Can use webTransforms with subprocess.stdio[2], objectMode', testGeneratorOutputPipe, 2, false, true, false, 'webTransform');250test('Can use webTransforms with subprocess.stderr, objectMode', testGeneratorOutputPipe, 2, true, true, false, 'webTransform');251test('Can use webTransforms with subprocess.stdio[*] as output, objectMode', testGeneratorOutputPipe, 3, false, true, false, 'webTransform');252test('Can use webTransforms with subprocess.stdio[1], noop transform', testGeneratorOutputPipe, 1, false, false, true, 'webTransform');253test('Can use webTransforms with subprocess.stdout, noop transform', testGeneratorOutputPipe, 1, true, false, true, 'webTransform');254test('Can use webTransforms with subprocess.stdio[2], noop transform', testGeneratorOutputPipe, 2, false, false, true, 'webTransform');255test('Can use webTransforms with subprocess.stderr, noop transform', testGeneratorOutputPipe, 2, true, false, true, 'webTransform');256test('Can use webTransforms with subprocess.stdio[*] as output, noop transform', testGeneratorOutputPipe, 3, false, false, true, 'webTransform');257test('Can use webTransforms with subprocess.stdio[1], objectMode, noop transform', testGeneratorOutputPipe, 1, false, true, true, 'webTransform');258test('Can use webTransforms with subprocess.stdout, objectMode, noop transform', testGeneratorOutputPipe, 1, true, true, true, 'webTransform');259test('Can use webTransforms with subprocess.stdio[2], objectMode, noop transform', testGeneratorOutputPipe, 2, false, true, true, 'webTransform');260test('Can use webTransforms with subprocess.stderr, objectMode, noop transform', testGeneratorOutputPipe, 2, true, true, true, 'webTransform');261test('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
1import {Buffer} from 'node:buffer';2import {scheduler} from 'node:timers/promises';3import test from 'ava';4import {getStreamAsArray} from 'get-stream';5import {execa, execaSync} from '../../index.js';6import {foobarString} from '../helpers/input.js';7import {8 noopGenerator,9 outputObjectGenerator,10 convertTransformToFinal,11 prefix,12 suffix,13} from '../helpers/generator.js';14import {generatorsMap} from '../helpers/map.js';15import {defaultHighWaterMark} from '../helpers/stream.js';16import {setFixtureDir} from '../helpers/fixtures-dir.js';17import {maxBuffer, assertErrorMessage} from '../helpers/max-buffer.js';1819setFixtureDir();2021const repeatCount = defaultHighWaterMark * 3;2223const writerGenerator = function * () {24 for (let index = 0; index < repeatCount; index += 1) {25 yield '\n';26 }27};2829const getLengthGenerator = function * (t, chunk) {30 t.is(chunk.length, 1);31 yield chunk;32};3334// eslint-disable-next-line max-params35const 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};4748test('Synchronous yields are not buffered, no passThrough', testHighWaterMark, false, false, false, execa);49test('Synchronous yields are not buffered, line-wise passThrough', testHighWaterMark, true, false, false, execa);50test('Synchronous yields are not buffered, binary passThrough', testHighWaterMark, true, true, false, execa);51test('Synchronous yields are not buffered, objectMode as input but not output', testHighWaterMark, false, false, true, execa);52test('Synchronous yields are not buffered, no passThrough, sync', testHighWaterMark, false, false, false, execaSync);53test('Synchronous yields are not buffered, line-wise passThrough, sync', testHighWaterMark, true, false, false, execaSync);54test('Synchronous yields are not buffered, binary passThrough, sync', testHighWaterMark, true, true, false, execaSync);55test('Synchronous yields are not buffered, objectMode as input but not output, sync', testHighWaterMark, false, false, true, execaSync);5657// eslint-disable-next-line max-params58const 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};6263test('Generator can filter "transform" by not calling yield', testNoYield, 'generator', false, false, '', execa);64test('Generator can filter "transform" by not calling yield, objectMode', testNoYield, 'generator', true, false, [], execa);65test('Generator can filter "final" by not calling yield', testNoYield, 'generator', false, true, '', execa);66test('Generator can filter "final" by not calling yield, objectMode', testNoYield, 'generator', true, true, [], execa);67test('Generator can filter "transform" by not calling yield, sync', testNoYield, 'generator', false, false, '', execaSync);68test('Generator can filter "transform" by not calling yield, objectMode, sync', testNoYield, 'generator', true, false, [], execaSync);69test('Generator can filter "final" by not calling yield, sync', testNoYield, 'generator', false, true, '', execaSync);70test('Generator can filter "final" by not calling yield, objectMode, sync', testNoYield, 'generator', true, true, [], execaSync);71test('Duplex can filter by not calling push', testNoYield, 'duplex', false, false, '', execa);72test('Duplex can filter by not calling push, objectMode', testNoYield, 'duplex', true, false, [], execa);73test('WebTransform can filter by not calling push', testNoYield, 'webTransform', false, false, '', execa);74test('WebTransform can filter by not calling push, objectMode', testNoYield, 'webTransform', true, false, [], execa);7576const 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};8182test('Generator can yield "transform" multiple times at different moments', testMultipleYields, 'generator', false, false);83test('Generator can yield "final" multiple times at different moments', testMultipleYields, 'generator', true, false);84test('Duplex can push multiple times at different moments', testMultipleYields, 'duplex', false, true);85test('WebTransform can push multiple times at different moments', testMultipleYields, 'webTransform', false, true);8687const partsPerChunk = 4;88const chunksPerCall = 10;89const callCount = 5;90const fullString = '\n'.repeat(defaultHighWaterMark / partsPerChunk);9192const yieldFullStrings = function * () {93 yield * Array.from({length: partsPerChunk * chunksPerCall}).fill(fullString);94};9596const 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};103104const 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};111112test('Generator "transform" yields are sent right away', testManyYields, false);113test('Generator "final" yields are sent right away', testManyYields, true);114115const 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);122123 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};130131test('Generators take "maxBuffer" into account', testMaxBuffer, 'generator');132test('Duplexes take "maxBuffer" into account', testMaxBuffer, 'duplex');133test('WebTransforms take "maxBuffer" into account', testMaxBuffer, 'webTransform');134135test('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});144145const 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);152153 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};160161test('Generators take "maxBuffer" into account, objectMode', testMaxBufferObject, 'generator');162test('Duplexes take "maxBuffer" into account, objectMode', testMaxBufferObject, 'duplex');163test('WebTransforms take "maxBuffer" into account, objectMode', testMaxBufferObject, 'webTransform');164165test('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});174175const 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};181182test('Generators "transform" is awaited on success', testAsyncGenerators, 'generator', false);183test('Generators "final" is awaited on success', testAsyncGenerators, 'generator', true);184test('Duplex is awaited on success', testAsyncGenerators, 'duplex', false);185test('WebTransform is awaited on success', testAsyncGenerators, 'webTransform', false);
deleted:test/stdio/validate.js-95 removed
1import {Buffer} from 'node:buffer';2import test from 'ava';3import {execa, execaSync} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';5import {getStdio} from '../helpers/stdio.js';6import {foobarUint8Array, foobarBuffer, foobarObject} from '../helpers/input.js';7import {serializeGenerator, getOutputGenerator, convertTransformToFinal} from '../helpers/generator.js';89setFixtureDir();1011const getMessage = input => {12 if (input === null || input === undefined) {13 return 'not be called at all';14 }1516 if (Buffer.isBuffer(input)) {17 return 'not a buffer';18 }1920 return 'a string or an Uint8Array';21};2223const lastInputGenerator = input => objectMode => [foobarUint8Array, getOutputGenerator(input)(objectMode)];24const inputGenerator = input => objectMode => [...lastInputGenerator(input)(objectMode), serializeGenerator(true)];2526// eslint-disable-next-line max-params27const 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};3233test('Generators with result.stdin cannot return an object if not in objectMode', testGeneratorReturn, 0, inputGenerator, foobarObject, false, true);34test('Generators with result.stdio[*] as input cannot return an object if not in objectMode', testGeneratorReturn, 3, inputGenerator, foobarObject, false, true);35test('The last generator with result.stdin cannot return an object even in objectMode', testGeneratorReturn, 0, lastInputGenerator, foobarObject, true, true);36test('The last generator with result.stdio[*] as input cannot return an object even in objectMode', testGeneratorReturn, 3, lastInputGenerator, foobarObject, true, true);37test('Generators with result.stdout cannot return an object if not in objectMode', testGeneratorReturn, 1, getOutputGenerator, foobarObject, false, false);38test('Generators with result.stderr cannot return an object if not in objectMode', testGeneratorReturn, 2, getOutputGenerator, foobarObject, false, false);39test('Generators with result.stdio[*] as output cannot return an object if not in objectMode', testGeneratorReturn, 3, getOutputGenerator, foobarObject, false, false);40test('Generators with result.stdin cannot return a Buffer if not in objectMode', testGeneratorReturn, 0, inputGenerator, foobarBuffer, false, true);41test('Generators with result.stdio[*] as input cannot return a Buffer if not in objectMode', testGeneratorReturn, 3, inputGenerator, foobarBuffer, false, true);42test('The last generator with result.stdin cannot return a Buffer even in objectMode', testGeneratorReturn, 0, lastInputGenerator, foobarBuffer, true, true);43test('The last generator with result.stdio[*] as input cannot return a Buffer even in objectMode', testGeneratorReturn, 3, lastInputGenerator, foobarBuffer, true, true);44test('Generators with result.stdout cannot return a Buffer if not in objectMode', testGeneratorReturn, 1, getOutputGenerator, foobarBuffer, false, false);45test('Generators with result.stderr cannot return a Buffer if not in objectMode', testGeneratorReturn, 2, getOutputGenerator, foobarBuffer, false, false);46test('Generators with result.stdio[*] as output cannot return a Buffer if not in objectMode', testGeneratorReturn, 3, getOutputGenerator, foobarBuffer, false, false);47test('Generators with result.stdin cannot return null if not in objectMode', testGeneratorReturn, 0, inputGenerator, null, false, true);48test('Generators with result.stdin cannot return null if in objectMode', testGeneratorReturn, 0, inputGenerator, null, true, true);49test('Generators with result.stdout cannot return null if not in objectMode', testGeneratorReturn, 1, getOutputGenerator, null, false, false);50test('Generators with result.stdout cannot return null if in objectMode', testGeneratorReturn, 1, getOutputGenerator, null, true, false);51test('Generators with result.stdin cannot return undefined if not in objectMode', testGeneratorReturn, 0, inputGenerator, undefined, false, true);52test('Generators with result.stdin cannot return undefined if in objectMode', testGeneratorReturn, 0, inputGenerator, undefined, true, true);53test('Generators with result.stdout cannot return undefined if not in objectMode', testGeneratorReturn, 1, getOutputGenerator, undefined, false, false);54test('Generators with result.stdout cannot return undefined if in objectMode', testGeneratorReturn, 1, getOutputGenerator, undefined, true, false);5556// eslint-disable-next-line max-params57const 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};6465test('Generators with result.stdin cannot return an object if not in objectMode, sync', testGeneratorReturnSync, 0, inputGenerator, foobarObject, false, true);66test('The last generator with result.stdin cannot return an object even in objectMode, sync', testGeneratorReturnSync, 0, lastInputGenerator, foobarObject, true, true);67test('Generators with result.stdout cannot return an object if not in objectMode, sync', testGeneratorReturnSync, 1, getOutputGenerator, foobarObject, false, false);68test('Generators with result.stderr cannot return an object if not in objectMode, sync', testGeneratorReturnSync, 2, getOutputGenerator, foobarObject, false, false);69test('Generators with result.stdio[*] as output cannot return an object if not in objectMode, sync', testGeneratorReturnSync, 3, getOutputGenerator, foobarObject, false, false);70test('Generators with result.stdin cannot return a Buffer if not in objectMode, sync', testGeneratorReturnSync, 0, inputGenerator, foobarBuffer, false, true);71test('The last generator with result.stdin cannot return a Buffer even in objectMode, sync', testGeneratorReturnSync, 0, lastInputGenerator, foobarBuffer, true, true);72test('Generators with result.stdout cannot return a Buffer if not in objectMode, sync', testGeneratorReturnSync, 1, getOutputGenerator, foobarBuffer, false, false);73test('Generators with result.stderr cannot return a Buffer if not in objectMode, sync', testGeneratorReturnSync, 2, getOutputGenerator, foobarBuffer, false, false);74test('Generators with result.stdio[*] as output cannot return a Buffer if not in objectMode, sync', testGeneratorReturnSync, 3, getOutputGenerator, foobarBuffer, false, false);75test('Generators with result.stdin cannot return null if not in objectMode, sync', testGeneratorReturnSync, 0, inputGenerator, null, false, true);76test('Generators with result.stdin cannot return null if in objectMode, sync', testGeneratorReturnSync, 0, inputGenerator, null, true, true);77test('Generators with result.stdout cannot return null if not in objectMode, sync', testGeneratorReturnSync, 1, getOutputGenerator, null, false, false);78test('Generators with result.stdout cannot return null if in objectMode, sync', testGeneratorReturnSync, 1, getOutputGenerator, null, true, false);79test('Generators with result.stdin cannot return undefined if not in objectMode, sync', testGeneratorReturnSync, 0, inputGenerator, undefined, false, true);80test('Generators with result.stdin cannot return undefined if in objectMode, sync', testGeneratorReturnSync, 0, inputGenerator, undefined, true, true);81test('Generators with result.stdout cannot return undefined if not in objectMode, sync', testGeneratorReturnSync, 1, getOutputGenerator, undefined, false, false);82test('Generators with result.stdout cannot return undefined if in objectMode, sync', testGeneratorReturnSync, 1, getOutputGenerator, undefined, true, false);8384test('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});9091test('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
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {defaultHighWaterMark} from '../helpers/stream.js';5import {foobarString} from '../helpers/input.js';67setFixtureDir();89const textEncoder = new TextEncoder();10const foobarStringFull = `${foobarString}\n`;11const doubleFoobarStringFull = `${foobarStringFull}${foobarStringFull}`;12const doubleFoobarString = `${foobarStringFull}${foobarString}`;13const doubleFoobarUint8ArrayFull = textEncoder.encode(doubleFoobarStringFull);14const doubleFoobarUint8Array = textEncoder.encode(doubleFoobarString);15const doubleFoobarArrayFull = [foobarStringFull, foobarStringFull];16const doubleFoobarArray = [foobarString, foobarString];1718// eslint-disable-next-line max-params19const 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};2526const fdOne = {stderr: true};27const fdBoth = {stdout: true, stderr: true};2829test('result.all is defined', testAllBoth, doubleFoobarStringFull, 'utf8', false, false, false, execa);30test('result.all is defined, encoding "buffer"', testAllBoth, doubleFoobarUint8ArrayFull, 'buffer', false, false, false, execa);31test('result.all is defined, lines', testAllBoth, doubleFoobarArrayFull, 'utf8', true, false, false, execa);32test('result.all is defined, lines, fd-specific one', testAllBoth, doubleFoobarArrayFull, 'utf8', fdOne, false, false, execa);33test('result.all is defined, lines, fd-specific both', testAllBoth, doubleFoobarArrayFull, 'utf8', fdBoth, false, false, execa);34test('result.all is defined, stripFinalNewline', testAllBoth, doubleFoobarString, 'utf8', false, true, false, execa);35test('result.all is defined, stripFinalNewline, fd-specific one', testAllBoth, doubleFoobarString, 'utf8', false, fdOne, false, execa);36test('result.all is defined, stripFinalNewline, fd-specific both', testAllBoth, doubleFoobarString, 'utf8', false, fdBoth, false, execa);37test('result.all is defined, encoding "buffer", stripFinalNewline', testAllBoth, doubleFoobarUint8Array, 'buffer', false, true, false, execa);38test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific one', testAllBoth, doubleFoobarUint8Array, 'buffer', false, fdOne, false, execa);39test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific both', testAllBoth, doubleFoobarUint8Array, 'buffer', false, fdBoth, false, execa);40test('result.all is defined, lines, stripFinalNewline', testAllBoth, doubleFoobarArray, 'utf8', true, true, false, execa);41test('result.all is defined, lines, fd-specific one, stripFinalNewline', testAllBoth, doubleFoobarArray, 'utf8', fdOne, true, false, execa);42test('result.all is defined, lines, fd-specific both, stripFinalNewline', testAllBoth, doubleFoobarArray, 'utf8', fdBoth, true, false, execa);43test('result.all is defined, lines, stripFinalNewline, fd-specific one', testAllBoth, doubleFoobarArray, 'utf8', true, fdOne, false, execa);44test('result.all is defined, lines, stripFinalNewline, fd-specific both', testAllBoth, doubleFoobarArray, 'utf8', true, fdBoth, false, execa);45test('result.all is defined, failure', testAllBoth, doubleFoobarStringFull, 'utf8', false, false, true, execa);46test('result.all is defined, encoding "buffer", failure', testAllBoth, doubleFoobarUint8ArrayFull, 'buffer', false, false, true, execa);47test('result.all is defined, lines, failure', testAllBoth, doubleFoobarArrayFull, 'utf8', true, false, true, execa);48test('result.all is defined, lines, fd-specific one, failure', testAllBoth, doubleFoobarArrayFull, 'utf8', fdOne, false, true, execa);49test('result.all is defined, lines, fd-specific both, failure', testAllBoth, doubleFoobarArrayFull, 'utf8', fdBoth, false, true, execa);50test('result.all is defined, stripFinalNewline, failure', testAllBoth, doubleFoobarString, 'utf8', false, true, true, execa);51test('result.all is defined, stripFinalNewline, fd-specific one, failure', testAllBoth, doubleFoobarString, 'utf8', false, fdOne, true, execa);52test('result.all is defined, stripFinalNewline, fd-specific both, failure', testAllBoth, doubleFoobarString, 'utf8', false, fdBoth, true, execa);53test('result.all is defined, encoding "buffer", stripFinalNewline, failure', testAllBoth, doubleFoobarUint8Array, 'buffer', false, true, true, execa);54test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific one, failure', testAllBoth, doubleFoobarUint8Array, 'buffer', false, fdOne, true, execa);55test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific both, failure', testAllBoth, doubleFoobarUint8Array, 'buffer', false, fdBoth, true, execa);56test('result.all is defined, lines, stripFinalNewline, failure', testAllBoth, doubleFoobarArray, 'utf8', true, true, true, execa);57test('result.all is defined, lines, fd-specific one, stripFinalNewline, failure', testAllBoth, doubleFoobarArray, 'utf8', fdOne, true, true, execa);58test('result.all is defined, lines, fd-specific both, stripFinalNewline, failure', testAllBoth, doubleFoobarArray, 'utf8', fdBoth, true, true, execa);59test('result.all is defined, lines, stripFinalNewline, fd-specific one, failure', testAllBoth, doubleFoobarArray, 'utf8', true, fdOne, true, execa);60test('result.all is defined, lines, stripFinalNewline, fd-specific both, failure', testAllBoth, doubleFoobarArray, 'utf8', true, fdBoth, true, execa);61test('result.all is defined, sync', testAllBoth, doubleFoobarStringFull, 'utf8', false, false, false, execaSync);62test('result.all is defined, encoding "buffer", sync', testAllBoth, doubleFoobarUint8ArrayFull, 'buffer', false, false, false, execaSync);63test('result.all is defined, lines, sync', testAllBoth, doubleFoobarArrayFull, 'utf8', true, false, false, execaSync);64test('result.all is defined, lines, fd-specific one, sync', testAllBoth, doubleFoobarArrayFull, 'utf8', fdOne, false, false, execaSync);65test('result.all is defined, lines, fd-specific both, sync', testAllBoth, doubleFoobarArrayFull, 'utf8', fdBoth, false, false, execaSync);66test('result.all is defined, stripFinalNewline, sync', testAllBoth, doubleFoobarString, 'utf8', false, true, false, execaSync);67test('result.all is defined, stripFinalNewline, fd-specific one, sync', testAllBoth, doubleFoobarString, 'utf8', false, fdOne, false, execaSync);68test('result.all is defined, stripFinalNewline, fd-specific both, sync', testAllBoth, doubleFoobarString, 'utf8', false, fdBoth, false, execaSync);69test('result.all is defined, encoding "buffer", stripFinalNewline, sync', testAllBoth, doubleFoobarUint8Array, 'buffer', false, true, false, execaSync);70test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific one, sync', testAllBoth, doubleFoobarUint8Array, 'buffer', false, fdOne, false, execaSync);71test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific both, sync', testAllBoth, doubleFoobarUint8Array, 'buffer', false, fdBoth, false, execaSync);72test('result.all is defined, lines, stripFinalNewline, sync', testAllBoth, doubleFoobarArray, 'utf8', true, true, false, execaSync);73test('result.all is defined, lines, fd-specific one, stripFinalNewline, sync', testAllBoth, doubleFoobarArray, 'utf8', fdOne, true, false, execaSync);74test('result.all is defined, lines, fd-specific both, stripFinalNewline, sync', testAllBoth, doubleFoobarArray, 'utf8', fdBoth, true, false, execaSync);75test('result.all is defined, lines, stripFinalNewline, fd-specific one, sync', testAllBoth, doubleFoobarArray, 'utf8', true, fdOne, false, execaSync);76test('result.all is defined, lines, stripFinalNewline, fd-specific both, sync', testAllBoth, doubleFoobarArray, 'utf8', true, fdBoth, false, execaSync);77test('result.all is defined, failure, sync', testAllBoth, doubleFoobarStringFull, 'utf8', false, false, true, execaSync);78test('result.all is defined, encoding "buffer", failure, sync', testAllBoth, doubleFoobarUint8ArrayFull, 'buffer', false, false, true, execaSync);79test('result.all is defined, lines, failure, sync', testAllBoth, doubleFoobarArrayFull, 'utf8', true, false, true, execaSync);80test('result.all is defined, lines, fd-specific one, failure, sync', testAllBoth, doubleFoobarArrayFull, 'utf8', fdOne, false, true, execaSync);81test('result.all is defined, lines, fd-specific both, failure, sync', testAllBoth, doubleFoobarArrayFull, 'utf8', fdBoth, false, true, execaSync);82test('result.all is defined, stripFinalNewline, failure, sync', testAllBoth, doubleFoobarString, 'utf8', false, true, true, execaSync);83test('result.all is defined, stripFinalNewline, fd-specific one, failure, sync', testAllBoth, doubleFoobarString, 'utf8', false, fdOne, true, execaSync);84test('result.all is defined, stripFinalNewline, fd-specific both, failure, sync', testAllBoth, doubleFoobarString, 'utf8', false, fdBoth, true, execaSync);85test('result.all is defined, encoding "buffer", stripFinalNewline, failure, sync', testAllBoth, doubleFoobarUint8Array, 'buffer', false, true, true, execaSync);86test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific one, failure, sync', testAllBoth, doubleFoobarUint8Array, 'buffer', false, fdOne, true, execaSync);87test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific both, failure, sync', testAllBoth, doubleFoobarUint8Array, 'buffer', false, fdBoth, true, execaSync);88test('result.all is defined, lines, stripFinalNewline, failure, sync', testAllBoth, doubleFoobarArray, 'utf8', true, true, true, execaSync);89test('result.all is defined, lines, fd-specific one, stripFinalNewline, failure, sync', testAllBoth, doubleFoobarArray, 'utf8', fdOne, true, true, execaSync);90test('result.all is defined, lines, fd-specific both, stripFinalNewline, failure, sync', testAllBoth, doubleFoobarArray, 'utf8', fdBoth, true, true, execaSync);91test('result.all is defined, lines, stripFinalNewline, fd-specific one, failure, sync', testAllBoth, doubleFoobarArray, 'utf8', true, fdOne, true, execaSync);92test('result.all is defined, lines, stripFinalNewline, fd-specific both, failure, sync', testAllBoth, doubleFoobarArray, 'utf8', true, fdBoth, true, execaSync);9394test.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});9899test.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});103104const testAllIgnored = async (t, options, execaMethod) => {105 const {all} = await execaMethod('noop.js');106 t.is(all, undefined);107};108109test('result.all is undefined unless opts.all is true', testAllIgnored, {}, execa);110test('result.all is undefined if opts.all is false', testAllIgnored, {all: false}, execa);111test('result.all is undefined if ignored', testAllIgnored, {stdio: 'ignore', all: true}, execa);112test('result.all is undefined unless opts.all is true, sync', testAllIgnored, {}, execaSync);113test('result.all is undefined if opts.all is false, sync', testAllIgnored, {all: false}, execaSync);114test('result.all is undefined if ignored, sync', testAllIgnored, {stdio: 'ignore', all: true}, execaSync);115116const 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};122123test('subprocess.all has the right objectMode and highWaterMark - stdout + stderr', testAllProperties, {});124test('subprocess.all has the right objectMode and highWaterMark - stdout only', testAllProperties, {stderr: 'ignore'});125test('subprocess.all has the right objectMode and highWaterMark - stderr only', testAllProperties, {stdout: 'ignore'});126127const 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);134135 const result = await subprocess;136 t.is(result[otherStreamName], undefined);137 t.is(result[streamName], foobarString);138 t.is(result.all, foobarString);139};140141test('can use all: true with stdout: ignore', testAllIgnore, 'stderr', 'stdout');142test('can use all: true with stderr: ignore', testAllIgnore, 'stdout', 'stderr');143144const 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};150151test('can use all: true with stdout: ignore, sync', testAllIgnoreSync, 'stderr', 'stdout');152test('can use all: true with stderr: ignore, sync', testAllIgnoreSync, 'stdout', 'stderr');153154test('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);159160 const {stdout, stderr, all} = await subprocess;161 t.is(stdout, undefined);162 t.is(stderr, undefined);163 t.is(all, undefined);164});165166test('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
1import {once} from 'node:events';2import {setTimeout} from 'node:timers/promises';3import test from 'ava';4import {execa} from '../../index.js';5import {setFixtureDir} from '../helpers/fixtures-dir.js';6import {fullStdio, getStdio} from '../helpers/stdio.js';78setFixtureDir();910const testBufferIgnore = async (t, fdNumber, all) => {11 await t.notThrowsAsync(execa('max-buffer.js', [`${fdNumber}`], {...getStdio(fdNumber, 'ignore'), buffer: false, all}));12};1314test('Subprocess buffers stdout, which does not prevent exit if ignored', testBufferIgnore, 1, false);15test('Subprocess buffers stderr, which does not prevent exit if ignored', testBufferIgnore, 2, false);16test('Subprocess buffers all, which does not prevent exit if ignored', testBufferIgnore, 1, true);1718const testBufferNotRead = async (t, fdNumber, all) => {19 const subprocess = execa('max-buffer.js', [`${fdNumber}`], {...fullStdio, buffer: false, all});20 await t.notThrowsAsync(subprocess);21};2223test('Subprocess buffers stdout, which does not prevent exit if not read and buffer is false', testBufferNotRead, 1, false);24test('Subprocess buffers stderr, which does not prevent exit if not read and buffer is false', testBufferNotRead, 2, false);25test('Subprocess buffers stdio[*], which does not prevent exit if not read and buffer is false', testBufferNotRead, 3, false);26test('Subprocess buffers all, which does not prevent exit if not read and buffer is false', testBufferNotRead, 1, true);2728const 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};3435test('Subprocess buffers stdout, which does not prevent exit if read and buffer is false', testBufferRead, 1, false);36test('Subprocess buffers stderr, which does not prevent exit if read and buffer is false', testBufferRead, 2, false);37test('Subprocess buffers stdio[*], which does not prevent exit if read and buffer is false', testBufferRead, 3, false);38test('Subprocess buffers all, which does not prevent exit if read and buffer is false', testBufferRead, 1, true);3940const 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};4647test('Subprocess buffers stdout before it is read', testBufferExit, 1, 'noop-delay.js', true);48test('Subprocess buffers stderr before it is read', testBufferExit, 2, 'noop-delay.js', true);49test('Subprocess buffers stdio[*] before it is read', testBufferExit, 3, 'noop-delay.js', true);50test('Subprocess buffers stdout right away, on successfully exit', testBufferExit, 1, 'noop-fd.js', true);51test('Subprocess buffers stderr right away, on successfully exit', testBufferExit, 2, 'noop-fd.js', true);52test('Subprocess buffers stdio[*] right away, on successfully exit', testBufferExit, 3, 'noop-fd.js', true);53test('Subprocess buffers stdout right away, on failure', testBufferExit, 1, 'noop-fail.js', false);54test('Subprocess buffers stderr right away, on failure', testBufferExit, 2, 'noop-fail.js', false);55test('Subprocess buffers stdio[*] right away, on failure', testBufferExit, 3, 'noop-fail.js', false);5657const 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};6465test('Subprocess buffers stdout right away, even if directly read', testBufferDirect, 1);66test('Subprocess buffers stderr right away, even if directly read', testBufferDirect, 2);67test('Subprocess buffers stdio[*] right away, even if directly read', testBufferDirect, 3);6869const 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};7576test('subprocess.stdout must be read right away', testBufferDestroyOnEnd, 1);77test('subprocess.stderr must be read right away', testBufferDestroyOnEnd, 2);78test('subprocess.stdio[*] must be read right away', testBufferDestroyOnEnd, 3);
deleted:test/stream/exit.js-85 removed
1import process from 'node:process';2import test from 'ava';3import {execa} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';56const isWindows = process.platform === 'win32';78setFixtureDir();910test('exitCode is 0 on success', async t => {11 const {exitCode} = await execa('noop.js', ['foo']);12 t.is(exitCode, 0);13});1415const 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};2425test('exitCode is 2', testExitCode, 2);26test('exitCode is 3', testExitCode, 3);27test('exitCode is 4', testExitCode, 4);2829if (!isWindows) {30 test('error.signal is SIGINT', async t => {31 const subprocess = execa('forever.js');3233 process.kill(subprocess.pid, 'SIGINT');3435 const {signal} = await t.throwsAsync(subprocess, {message: /was killed with SIGINT/});36 t.is(signal, 'SIGINT');37 });3839 test('error.signalDescription is defined', async t => {40 const subprocess = execa('forever.js');4142 process.kill(subprocess.pid, 'SIGINT');4344 const {signalDescription} = await t.throwsAsync(subprocess, {message: /User interruption with CTRL-C/});45 t.is(signalDescription, 'User interruption with CTRL-C');46 });4748 test('error.signal is SIGTERM', async t => {49 const subprocess = execa('forever.js');5051 process.kill(subprocess.pid, 'SIGTERM');5253 const {signal} = await t.throwsAsync(subprocess, {message: /was killed with SIGTERM/});54 t.is(signal, 'SIGTERM');55 });5657 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 });6162 test('exitCode is undefined on signal termination', async t => {63 const subprocess = execa('forever.js');6465 process.kill(subprocess.pid);6667 const {exitCode} = await t.throwsAsync(subprocess);68 t.is(exitCode, undefined);69 });70}7172test('result.signal is undefined for successful execution', async t => {73 const {signal} = await execa('noop.js');74 t.is(signal, undefined);75});7677test('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});8182test('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
1import {Buffer} from 'node:buffer';2import test from 'ava';3import getStream from 'get-stream';4import {execa, execaSync} from '../../index.js';5import {setFixtureDir} from '../helpers/fixtures-dir.js';6import {fullStdio} from '../helpers/stdio.js';7import {getEarlyErrorSubprocess, getEarlyErrorSubprocessSync} from '../helpers/early-error.js';8import {maxBuffer, assertErrorMessage} from '../helpers/max-buffer.js';910setFixtureDir();1112const maxBufferMessage = {message: /maxBuffer exceeded/};13const maxBufferCodeSync = {code: 'ENOBUFS'};1415const 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};2526const getMaxBufferSubprocess = (execaMethod, fdNumber, {length = maxBuffer, ...options} = {}) =>27 execaMethod('max-buffer.js', [`${fdNumber}`, `${length + 1}`], {...fullStdio, maxBuffer, ...options});2829const getExpectedOutput = (length = maxBuffer) => '.'.repeat(length);3031const testMaxBufferSuccess = async (t, execaMethod, fdNumber, all) => {32 const {isMaxBuffer} = await getMaxBufferSubprocess(execaMethod, fdNumber, {all, length: maxBuffer - 1});33 t.false(isMaxBuffer);34};3536test('maxBuffer does not affect stdout if too high', testMaxBufferSuccess, execa, 1, false);37test('maxBuffer does not affect stderr if too high', testMaxBufferSuccess, execa, 2, false);38test('maxBuffer does not affect stdio[*] if too high', testMaxBufferSuccess, execa, 3, false);39test('maxBuffer does not affect all if too high', testMaxBufferSuccess, execa, 1, true);40test('maxBuffer does not affect stdout if too high, sync', testMaxBufferSuccess, execaSync, 1, false);41test('maxBuffer does not affect stderr if too high, sync', testMaxBufferSuccess, execaSync, 2, false);42test('maxBuffer does not affect stdio[*] if too high, sync', testMaxBufferSuccess, execaSync, 3, false);43test('maxBuffer does not affect all if too high, sync', testMaxBufferSuccess, execaSync, 1, true);4445const 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};5657test('maxBuffer terminates stream gracefully, more writes', testGracefulExit, 'noop-repeat.js', 1);58test('maxBuffer terminates stream gracefully, no more writes', testGracefulExit, 'noop-fd.js', 0);5960const 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};7071test('maxBuffer terminate stream with killSignal, more writes, sync', testGracefulExitSync, 'noop-repeat.js');72test('maxBuffer terminate stream with killSignal, no more writes, sync', testGracefulExitSync, 'noop-fd.js');7374const 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};8081test('maxBuffer truncates stdout', testMaxBufferLimit, execa, 1, false);82test('maxBuffer truncates stderr', testMaxBufferLimit, execa, 2, false);83test('maxBuffer truncates stdio[*]', testMaxBufferLimit, execa, 3, false);84test('maxBuffer truncates all', testMaxBufferLimit, execa, 1, true);85test('maxBuffer truncates stdout, sync', testMaxBufferLimit, execaSync, 1, false);86test('maxBuffer truncates stderr, sync', testMaxBufferLimit, execaSync, 2, false);87test('maxBuffer truncates stdio[*], sync', testMaxBufferLimit, execaSync, 3, false);88test('maxBuffer truncates all, sync', testMaxBufferLimit, execaSync, 1, true);8990const MAX_BUFFER_DEFAULT = 1e8;9192const 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};9899test('maxBuffer has a default value with stdout', testMaxBufferDefault, execa, 1, undefined);100test('maxBuffer has a default value with stderr', testMaxBufferDefault, execa, 2, undefined);101test('maxBuffer has a default value with stdio[*]', testMaxBufferDefault, execa, 3, undefined);102test('maxBuffer has a default value with stdout, sync', testMaxBufferDefault, execaSync, 1, undefined);103test('maxBuffer has a default value with stderr, sync', testMaxBufferDefault, execaSync, 2, undefined);104test('maxBuffer has a default value with stdio[*], sync', testMaxBufferDefault, execaSync, 3, undefined);105test('maxBuffer has a default value with stdout with fd-specific options', testMaxBufferDefault, execa, 1, {stderr: 1e9});106test('maxBuffer has a default value with stderr with fd-specific options', testMaxBufferDefault, execa, 2, {stdout: 1e9});107test('maxBuffer has a default value with stdio[*] with fd-specific options', testMaxBufferDefault, execa, 3, {stdout: 1e9});108test('maxBuffer has a default value with stdout with empty fd-specific options', testMaxBufferDefault, execa, 1, {});109110const 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};116117test('maxBuffer truncates file descriptors with fd-specific options, stdout', testFdSpecific, 1, 'stdout', execa);118test('maxBuffer truncates file descriptors with fd-specific options, fd1', testFdSpecific, 1, 'fd1', execa);119test('maxBuffer truncates file descriptors with fd-specific options, stderr', testFdSpecific, 2, 'stderr', execa);120test('maxBuffer truncates file descriptors with fd-specific options, fd2', testFdSpecific, 2, 'fd2', execa);121test('maxBuffer truncates file descriptors with fd-specific options, stdout, all', testFdSpecific, 1, 'all', execa);122test('maxBuffer truncates file descriptors with fd-specific options, stderr, all', testFdSpecific, 2, 'all', execa);123test('maxBuffer truncates file descriptors with fd-specific options, fd3', testFdSpecific, 3, 'fd3', execa);124test('maxBuffer.stdout is used for stdout with fd-specific options, stdout, sync', testFdSpecific, 1, 'stdout', execaSync);125126test('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});130131test('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});137138const 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 }151152 t.is(stdout, '\n'.repeat(maxBufferStdout));153 t.is(stderr, '\n'.repeat(maxBufferStderr));154 t.is(all, '\n'.repeat(maxBufferStdout + maxBufferStderr));155};156157test('maxBuffer.stdout can differ from maxBuffer.stderr, combined with all, below threshold', testAll, false);158test('maxBuffer.stdout can differ from maxBuffer.stderr, combined with all, above threshold', testAll, true);159160const 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};166167test('maxBuffer.stdin is invalid', testInvalidFd, 'stdin', execa);168test('maxBuffer.fd0 is invalid', testInvalidFd, 'fd0', execa);169test('maxBuffer.other is invalid', testInvalidFd, 'other', execa);170test('maxBuffer.fd10 is invalid', testInvalidFd, 'fd10', execa);171test('maxBuffer.stdin is invalid, sync', testInvalidFd, 'stdin', execaSync);172test('maxBuffer.fd0 is invalid, sync', testInvalidFd, 'fd0', execaSync);173test('maxBuffer.other is invalid, sync', testInvalidFd, 'other', execaSync);174test('maxBuffer.fd10 is invalid, sync', testInvalidFd, 'fd10', execaSync);175176const 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};183184test('maxBuffer works with encoding buffer and stdout', testMaxBufferEncoding, execa, 1);185test('maxBuffer works with encoding buffer and stderr', testMaxBufferEncoding, execa, 2);186test('maxBuffer works with encoding buffer and stdio[*]', testMaxBufferEncoding, execa, 3);187test('maxBuffer works with encoding buffer and stdout, sync', testMaxBufferEncoding, execaSync, 1);188test('maxBuffer works with encoding buffer and stderr, sync', testMaxBufferEncoding, execaSync, 2);189test('maxBuffer works with encoding buffer and stdio[*], sync', testMaxBufferEncoding, execaSync, 3);190191const 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};197198test('maxBuffer works with other encodings and stdout', testMaxBufferHex, 1);199test('maxBuffer works with other encodings and stderr', testMaxBufferHex, 2);200test('maxBuffer works with other encodings and stdio[*]', testMaxBufferHex, 3);201202const 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};208209test('maxBuffer ignores other encodings and stdout, sync', testMaxBufferHexSync, 1);210test('maxBuffer ignores other encodings and stderr, sync', testMaxBufferHexSync, 2);211test('maxBuffer ignores other encodings and stdio[*], sync', testMaxBufferHexSync, 3);212213const 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};223224test('do not buffer stdout when `buffer` set to `false`', testNoMaxBuffer, 1, false);225test('do not buffer stdout when `buffer` set to `false`, fd-specific', testNoMaxBuffer, 1, {stdout: false});226test('do not buffer stderr when `buffer` set to `false`', testNoMaxBuffer, 2, false);227test('do not buffer stderr when `buffer` set to `false`, fd-specific', testNoMaxBuffer, 2, {stderr: false});228test('do not buffer stdio[*] when `buffer` set to `false`', testNoMaxBuffer, 3, false);229test('do not buffer stdio[*] when `buffer` set to `false`, fd-specific', testNoMaxBuffer, 3, {fd3: false});230231const testNoMaxBufferSync = (t, fdNumber, buffer) => {232 const {isMaxBuffer, stdio} = getMaxBufferSubprocess(execaSync, fdNumber, {buffer});233 t.false(isMaxBuffer);234 t.is(stdio[fdNumber], undefined);235};236237// @todo: add tests for fd3 once the following Node.js bug is fixed.238// https://github.com/nodejs/node/issues/52422239test('do not buffer stdout when `buffer` set to `false`, sync', testNoMaxBufferSync, 1, false);240test('do not buffer stdout when `buffer` set to `false`, fd-specific, sync', testNoMaxBufferSync, 1, {stdout: false});241test('do not buffer stderr when `buffer` set to `false`, sync', testNoMaxBufferSync, 2, false);242test('do not buffer stderr when `buffer` set to `false`, fd-specific, sync', testNoMaxBufferSync, 2, {stderr: false});243244const 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};253254test('abort stream when hitting maxBuffer with stdout', testMaxBufferAbort, 1);255test('abort stream when hitting maxBuffer with stderr', testMaxBufferAbort, 2);256test('abort stream when hitting maxBuffer with stdio[*]', testMaxBufferAbort, 3);257258const testEarlyError = async (t, getSubprocess) => {259 const {failed, isMaxBuffer} = await getSubprocess({reject: false, maxBuffer: 1});260 t.true(failed);261 t.false(isMaxBuffer);262};263264test('error.isMaxBuffer is false on early errors', testEarlyError, getEarlyErrorSubprocess);265test('error.isMaxBuffer is false on early errors, sync', testEarlyError, getEarlyErrorSubprocessSync);
deleted:test/stream/no-buffer.js-192 removed
1import {once} from 'node:events';2import test from 'ava';3import getStream from 'get-stream';4import {execa, execaSync} from '../../index.js';5import {setFixtureDir} from '../helpers/fixtures-dir.js';6import {fullStdio, getStdio} from '../helpers/stdio.js';7import {foobarString, foobarUppercase, foobarUppercaseUint8Array} from '../helpers/input.js';8import {resultGenerator, uppercaseGenerator, uppercaseBufferGenerator} from '../helpers/generator.js';910setFixtureDir();1112const 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 ]);2021 t.is(output, '');2223 if (all) {24 t.is(allOutput, '');25 }26};2728test('Lacks some data when stdout is read too late `buffer` set to `false`', testLateStream, 1, false);29test('Lacks some data when stderr is read too late `buffer` set to `false`', testLateStream, 2, false);30test('Lacks some data when stdio[*] is read too late `buffer` set to `false`', testLateStream, 3, false);31test('Lacks some data when all is read too late `buffer` set to `false`', testLateStream, 1, true);3233const getFirstDataEvent = async stream => {34 const [output] = await once(stream, 'data');35 return output.toString();36};3738// eslint-disable-next-line max-params39const 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 ]);4748 const expectedResult = buffer ? foobarString : undefined;4950 t.is(result.stdio[fdNumber], expectedResult);51 t.is(output, foobarString);5253 if (all) {54 t.is(result.all, expectedResult);55 t.is(allOutput, foobarString);56 }57};5859test('Can iterate stdout when `buffer` set to `false`', testIterationBuffer, 1, false, false, false);60test('Can iterate stderr when `buffer` set to `false`', testIterationBuffer, 2, false, false, false);61test('Can iterate stdio[*] when `buffer` set to `false`', testIterationBuffer, 3, false, false, false);62test('Can iterate all when `buffer` set to `false`', testIterationBuffer, 1, false, false, true);63test('Can iterate stdout when `buffer` set to `true`', testIterationBuffer, 1, true, false, false);64test('Can iterate stderr when `buffer` set to `true`', testIterationBuffer, 2, true, false, false);65test('Can iterate stdio[*] when `buffer` set to `true`', testIterationBuffer, 3, true, false, false);66test('Can iterate all when `buffer` set to `true`', testIterationBuffer, 1, true, false, true);67test('Can listen to `data` events on stdout when `buffer` set to `false`', testIterationBuffer, 1, false, true, false);68test('Can listen to `data` events on stderr when `buffer` set to `false`', testIterationBuffer, 2, false, true, false);69test('Can listen to `data` events on stdio[*] when `buffer` set to `false`', testIterationBuffer, 3, false, true, false);70test('Can listen to `data` events on all when `buffer` set to `false`', testIterationBuffer, 1, false, true, true);71test('Can listen to `data` events on stdout when `buffer` set to `true`', testIterationBuffer, 1, true, true, false);72test('Can listen to `data` events on stderr when `buffer` set to `true`', testIterationBuffer, 2, true, true, false);73test('Can listen to `data` events on stdio[*] when `buffer` set to `true`', testIterationBuffer, 3, true, true, false);74test('Can listen to `data` events on all when `buffer` set to `true`', testIterationBuffer, 1, true, true, true);7576const 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};8384test('Listen to stdout errors even when `buffer` is `false`', testNoBufferStreamError, 1, false);85test('Listen to stderr errors even when `buffer` is `false`', testNoBufferStreamError, 2, false);86test('Listen to stdio[*] errors even when `buffer` is `false`', testNoBufferStreamError, 3, false);87test('Listen to all errors even when `buffer` is `false`', testNoBufferStreamError, 1, true);8889const testOutput = async (t, buffer, execaMethod) => {90 const {stdout} = await execaMethod('noop-fd.js', ['1', foobarString], {buffer});91 t.is(stdout, foobarString);92};9394test('buffer: true returns output', testOutput, true, execa);95test('buffer: true returns output, fd-specific', testOutput, {stderr: false}, execa);96test('buffer: default returns output', testOutput, undefined, execa);97test('buffer: default returns output, fd-specific', testOutput, {}, execa);9899const testNoOutput = async (t, stdioOption, buffer, execaMethod) => {100 const {stdout} = await execaMethod('noop.js', {stdout: stdioOption, buffer});101 t.is(stdout, undefined);102};103104test('buffer: false does not return output', testNoOutput, 'pipe', false, execa);105test('buffer: false does not return output, fd-specific', testNoOutput, 'pipe', {stdout: false}, execa);106test('buffer: false does not return output, stdout undefined', testNoOutput, undefined, false, execa);107test('buffer: false does not return output, stdout null', testNoOutput, null, false, execa);108test('buffer: false does not return output, stdout ["pipe"]', testNoOutput, ['pipe'], false, execa);109test('buffer: false does not return output, stdout [undefined]', testNoOutput, [undefined], false, execa);110test('buffer: false does not return output, stdout [null]', testNoOutput, [null], false, execa);111test('buffer: false does not return output, stdout ["pipe", undefined]', testNoOutput, ['pipe', undefined], false, execa);112test('buffer: false does not return output, sync', testNoOutput, 'pipe', false, execaSync);113test('buffer: false does not return output, fd-specific, sync', testNoOutput, 'pipe', {stdout: false}, execaSync);114test('buffer: false does not return output, stdout undefined, sync', testNoOutput, undefined, false, execaSync);115test('buffer: false does not return output, stdout null, sync', testNoOutput, null, false, execaSync);116test('buffer: false does not return output, stdout ["pipe"], sync', testNoOutput, ['pipe'], false, execaSync);117test('buffer: false does not return output, stdout [undefined], sync', testNoOutput, [undefined], false, execaSync);118test('buffer: false does not return output, stdout [null], sync', testNoOutput, [null], false, execaSync);119test('buffer: false does not return output, stdout ["pipe", undefined], sync', testNoOutput, ['pipe', undefined], false, execaSync);120121const 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};126127test('buffer: false does not return output, failure', testNoOutputFail, execa);128test('buffer: false does not return output, failure, sync', testNoOutputFail, execaSync);129130// eslint-disable-next-line max-params131const 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};138139test('buffer: {}, all: true', testNoOutputAll, {}, true, true, execa);140test('buffer: {stdout: false}, all: true', testNoOutputAll, {stdout: false}, false, true, execa);141test('buffer: {stderr: false}, all: true', testNoOutputAll, {stderr: false}, true, false, execa);142test('buffer: {all: false}, all: true', testNoOutputAll, {all: false}, false, false, execa);143test('buffer: {}, all: true, sync', testNoOutputAll, {}, true, true, execaSync);144test('buffer: {stdout: false}, all: true, sync', testNoOutputAll, {stdout: false}, false, true, execaSync);145test('buffer: {stderr: false}, all: true, sync', testNoOutputAll, {stderr: false}, true, false, execaSync);146test('buffer: {all: false}, all: true, sync', testNoOutputAll, {all: false}, false, false, execaSync);147148const 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};157158test('buffer: false still runs transforms', testTransform, false, execa);159test('buffer: false still runs transforms, objectMode', testTransform, true, execa);160test('buffer: false still runs transforms, sync', testTransform, false, execaSync);161test('buffer: false still runs transforms, objectMode, sync', testTransform, true, execaSync);162163const 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};173174test('buffer: false still runs transforms, encoding "buffer"', testTransformBinary, false, execa);175test('buffer: false still runs transforms, encoding "buffer", objectMode', testTransformBinary, true, execa);176test('buffer: false still runs transforms, encoding "buffer", sync', testTransformBinary, false, execaSync);177test('buffer: false still runs transforms, encoding "buffer", objectMode, sync', testTransformBinary, true, execaSync);178179const 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};186187test('buffer: false > emits end event on stdout when promise is rejected', testStreamEnd, 1, false);188test('buffer: false > emits end event on stderr when promise is rejected', testStreamEnd, 2, false);189test('buffer: false > emits end event on stdio[*] when promise is rejected', testStreamEnd, 3, false);190test('buffer: true > emits end event on stdout when promise is rejected', testStreamEnd, 1, true);191test('buffer: true > emits end event on stderr when promise is rejected', testStreamEnd, 2, true);192test('buffer: true > emits end event on stdio[*] when promise is rejected', testStreamEnd, 3, true);
deleted:test/stream/resolve.js-49 removed
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {getStdio} from '../helpers/stdio.js';56setFixtureDir();78const testIgnore = async (t, fdNumber, execaMethod) => {9 const result = await execaMethod('noop.js', getStdio(fdNumber, 'ignore'));10 t.is(result.stdio[fdNumber], undefined);11};1213test('stdout is undefined if ignored', testIgnore, 1, execa);14test('stderr is undefined if ignored', testIgnore, 2, execa);15test('stdio[*] is undefined if ignored', testIgnore, 3, execa);16test('stdout is undefined if ignored - sync', testIgnore, 1, execaSync);17test('stderr is undefined if ignored - sync', testIgnore, 2, execaSync);18test('stdio[*] is undefined if ignored - sync', testIgnore, 3, execaSync);1920const 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};2627test('subprocess listeners are cleaned up on success', testSubprocessEventsCleanup, 'empty.js');28test('subprocess listeners are cleaned up on failure', testSubprocessEventsCleanup, 'fail.js');2930test('Aborting stdout should not abort stderr nor all', async t => {31 const subprocess = execa('empty.js', {all: true});3233 subprocess.stdout.destroy();34 t.false(subprocess.stdout.readable);35 t.true(subprocess.stderr.readable);36 t.true(subprocess.all.readable);3738 await subprocess;3940 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
1import {setTimeout} from 'node:timers/promises';2import test from 'ava';3import {execa} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';5import {fullStdio, getStdio, prematureClose, assertEpipe} from '../helpers/stdio.js';6import {infiniteGenerator} from '../helpers/generator.js';78setFixtureDir();910const getStreamInputSubprocess = fdNumber => execa('stdin-fd.js', [`${fdNumber}`], fdNumber === 311 ? getStdio(3, [new Uint8Array(), infiniteGenerator()])12 : {});13const getStreamOutputSubprocess = fdNumber => execa('noop-repeat.js', [`${fdNumber}`], fdNumber === 3 ? fullStdio : {});1415const 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};2122const assertStreamOutputError = (t, fdNumber, {exitCode, signal, isTerminated, failed, stderr}) => {23 if (fdNumber !== 3) {24 t.is(exitCode, 1);25 }2627 t.is(signal, undefined);28 t.false(isTerminated);29 t.true(failed);3031 assertEpipe(t, stderr, fdNumber);32};3334const 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};4041test('Aborting stdin should not make the subprocess exit', testStreamInputAbort, 0);42test('Aborting input stdio[*] should not make the subprocess exit', testStreamInputAbort, 3);4344const 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};5051test('Aborting stdout should not make the subprocess exit', testStreamOutputAbort, 1);52test('Aborting stderr should not make the subprocess exit', testStreamOutputAbort, 2);53test('Aborting output stdio[*] should not make the subprocess exit', testStreamOutputAbort, 3);5455const 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};6364test('Destroying stdin should not make the subprocess exit', testStreamInputDestroy, 0);65test('Destroying input stdio[*] should not make the subprocess exit', testStreamInputDestroy, 3);6667const 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};7576test('Destroying stdout should not make the subprocess exit', testStreamOutputDestroy, 1);77test('Destroying stderr should not make the subprocess exit', testStreamOutputDestroy, 2);78test('Destroying output stdio[*] should not make the subprocess exit', testStreamOutputDestroy, 3);7980const 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};9091test('Errors on stdin should not make the subprocess exit', testStreamInputError, 0);92test('Errors on input stdio[*] should not make the subprocess exit', testStreamInputError, 3);9394const 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};103104test('Errors on stdout should make the subprocess exit', testStreamOutputError, 1);105test('Errors on stderr should make the subprocess exit', testStreamOutputError, 2);106test('Errors on output stdio[*] should make the subprocess exit', testStreamOutputError, 3);107108const 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};115116test('Subprocess waits on stdin before exiting', testWaitOnStreamEnd, 0);117test('Subprocess waits on stdio[*] before exiting', testWaitOnStreamEnd, 3);
deleted:test/stream/wait-abort.js-99 removed
1import {setImmediate} from 'node:timers/promises';2import test from 'ava';3import {execa} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';5import {prematureClose} from '../helpers/stdio.js';6import {noopReadable, noopWritable, noopDuplex} from '../helpers/stream.js';7import {endOptionStream, destroyOptionStream, destroySubprocessStream, getStreamStdio} from '../helpers/wait.js';89setFixtureDir();1011const noop = () => {};1213// eslint-disable-next-line max-params14const 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();2021 const {stdout} = await subprocess;22 t.is(stdout, '');23 t.true(stream.destroyed);24};2526test('Keeps running when stdin option is used and subprocess.stdin ends', testStreamAbortWait, noop, noopReadable(), 0, false);27test('Keeps running when stdin option is used and subprocess.stdin Duplex ends', testStreamAbortWait, noop, noopDuplex(), 0, false);28test('Keeps running when input stdio[*] option is used and input subprocess.stdio[*] ends', testStreamAbortWait, noop, noopReadable(), 3, false);29test('Keeps running when stdin option is used and subprocess.stdin ends, with a transform', testStreamAbortWait, noop, noopReadable(), 0, true);30test('Keeps running when stdin option is used and subprocess.stdin Duplex ends, with a transform', testStreamAbortWait, noop, noopDuplex(), 0, true);31test('Keeps running when input stdio[*] option is used and input subprocess.stdio[*] ends, with a transform', testStreamAbortWait, noop, noopReadable(), 3, true);3233// eslint-disable-next-line max-params34const 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();3839 const {stdout} = await subprocess;40 t.is(stdout, '');41 t.true(stream.destroyed);42};4344test('Passes when stdin option aborts', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 0, false);45test('Passes when stdin option Duplex aborts', testStreamAbortSuccess, destroyOptionStream, noopDuplex(), 0, false);46test('Passes when input stdio[*] option aborts', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 3, false);47test('Passes when stdout option ends with no more writes', testStreamAbortSuccess, endOptionStream, noopWritable(), 1, false);48test('Passes when stderr option ends with no more writes', testStreamAbortSuccess, endOptionStream, noopWritable(), 2, false);49test('Passes when output stdio[*] option ends with no more writes', testStreamAbortSuccess, endOptionStream, noopWritable(), 3, false);50test('Passes when subprocess.stdout aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 1, false);51test('Passes when subprocess.stdout Duplex aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 1, false);52test('Passes when subprocess.stderr aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 2, false);53test('Passes when subprocess.stderr Duplex aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 2, false);54test('Passes when output subprocess.stdio[*] aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 3, false);55test('Passes when output subprocess.stdio[*] Duplex aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 3, false);56test('Passes when stdin option aborts, with a transform', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 0, true);57test('Passes when stdin option Duplex aborts, with a transform', testStreamAbortSuccess, destroyOptionStream, noopDuplex(), 0, true);58test('Passes when input stdio[*] option aborts, with a transform', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 3, true);59test('Passes when stdout option ends with no more writes, with a transform', testStreamAbortSuccess, endOptionStream, noopWritable(), 1, true);60test('Passes when stderr option ends with no more writes, with a transform', testStreamAbortSuccess, endOptionStream, noopWritable(), 2, true);61test('Passes when output stdio[*] option ends with no more writes, with a transform', testStreamAbortSuccess, endOptionStream, noopWritable(), 3, true);62test('Passes when subprocess.stdout aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 1, true);63test('Passes when subprocess.stdout Duplex aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 1, true);64test('Passes when subprocess.stderr aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 2, true);65test('Passes when subprocess.stderr Duplex aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 2, true);66test('Passes when output subprocess.stdio[*] aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 3, true);67test('Passes when output subprocess.stdio[*] Duplex aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 3, true);6869// eslint-disable-next-line max-params70const 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 }7677 const error = await t.throwsAsync(subprocess);78 t.like(error, {...prematureClose, exitCode: 0});79 t.true(stream.destroyed);80};8182test('Throws abort error when subprocess.stdin aborts', testStreamAbortFail, destroySubprocessStream, noopReadable(), 0, false);83test('Throws abort error when subprocess.stdin Duplex aborts', testStreamAbortFail, destroySubprocessStream, noopDuplex(), 0, false);84test('Throws abort error when input subprocess.stdio[*] aborts', testStreamAbortFail, destroySubprocessStream, noopReadable(), 3, false);85test('Throws abort error when stdout option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopWritable(), 1, false);86test('Throws abort error when stdout option Duplex aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopDuplex(), 1, false);87test('Throws abort error when stderr option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopWritable(), 2, false);88test('Throws abort error when stderr option Duplex aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopDuplex(), 2, false);89test('Throws abort error when output stdio[*] option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopWritable(), 3, false);90test('Throws abort error when output stdio[*] Duplex option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopDuplex(), 3, false);91test('Throws abort error when subprocess.stdin aborts, with a transform', testStreamAbortFail, destroySubprocessStream, noopReadable(), 0, true);92test('Throws abort error when subprocess.stdin Duplex aborts, with a transform', testStreamAbortFail, destroySubprocessStream, noopDuplex(), 0, true);93test('Throws abort error when input subprocess.stdio[*] aborts, with a transform', testStreamAbortFail, destroySubprocessStream, noopReadable(), 3, true);94test('Throws abort error when stdout option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopWritable(), 1, true);95test('Throws abort error when stdout option Duplex aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopDuplex(), 1, true);96test('Throws abort error when stderr option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopWritable(), 2, true);97test('Throws abort error when stderr option Duplex aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopDuplex(), 2, true);98test('Throws abort error when output stdio[*] option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopWritable(), 3, true);99test('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
1import {setImmediate} from 'node:timers/promises';2import test from 'ava';3import {execa} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';5import {assertEpipe} from '../helpers/stdio.js';6import {foobarString} from '../helpers/input.js';7import {noopWritable, noopDuplex} from '../helpers/stream.js';8import {endOptionStream, destroyOptionStream, destroySubprocessStream, getStreamStdio} from '../helpers/wait.js';910setFixtureDir();1112// eslint-disable-next-line max-params13const 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);1819 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};2526test('Throws EPIPE when stdout option ends with more writes', testStreamEpipeFail, endOptionStream, noopWritable(), 1, false);27test('Throws EPIPE when stdout option aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopWritable(), 1, false);28test('Throws EPIPE when stdout option Duplex aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 1, false);29test('Throws EPIPE when stderr option ends with more writes', testStreamEpipeFail, endOptionStream, noopWritable(), 2, false);30test('Throws EPIPE when stderr option aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopWritable(), 2, false);31test('Throws EPIPE when stderr option Duplex aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 2, false);32test('Throws EPIPE when output stdio[*] option ends with more writes', testStreamEpipeFail, endOptionStream, noopWritable(), 3, false);33test('Throws EPIPE when output stdio[*] option aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopWritable(), 3, false);34test('Throws EPIPE when output stdio[*] option Duplex aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 3, false);35test('Throws EPIPE when subprocess.stdout aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 1, false);36test('Throws EPIPE when subprocess.stdout Duplex aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 1, false);37test('Throws EPIPE when subprocess.stderr aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 2, false);38test('Throws EPIPE when subprocess.stderr Duplex aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 2, false);39test('Throws EPIPE when output subprocess.stdio[*] aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 3, false);40test('Throws EPIPE when output subprocess.stdio[*] Duplex aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 3, false);41test('Throws EPIPE when stdout option ends with more writes, with a transform', testStreamEpipeFail, endOptionStream, noopWritable(), 1, true);42test('Throws EPIPE when stdout option aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopWritable(), 1, true);43test('Throws EPIPE when stdout option Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 1, true);44test('Throws EPIPE when stderr option ends with more writes, with a transform', testStreamEpipeFail, endOptionStream, noopWritable(), 2, true);45test('Throws EPIPE when stderr option aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopWritable(), 2, true);46test('Throws EPIPE when stderr option Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 2, true);47test('Throws EPIPE when output stdio[*] option ends with more writes, with a transform', testStreamEpipeFail, endOptionStream, noopWritable(), 3, true);48test('Throws EPIPE when output stdio[*] option aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopWritable(), 3, true);49test('Throws EPIPE when output stdio[*] option Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 3, true);50test('Throws EPIPE when subprocess.stdout aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 1, true);51test('Throws EPIPE when subprocess.stdout Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 1, true);52test('Throws EPIPE when subprocess.stderr aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 2, true);53test('Throws EPIPE when subprocess.stderr Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 2, true);54test('Throws EPIPE when output subprocess.stdio[*] aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 3, true);55test('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
1import test from 'ava';2import {execa} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {noopReadable, noopWritable, noopDuplex} from '../helpers/stream.js';5import {destroyOptionStream, destroySubprocessStream, getStreamStdio} from '../helpers/wait.js';67setFixtureDir();89// eslint-disable-next-line max-params10const 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});1415 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};2324test('Throws stream error when stdin option errors', testStreamError, destroyOptionStream, noopReadable(), 0, false);25test('Throws stream error when stdin option Duplex errors', testStreamError, destroyOptionStream, noopDuplex(), 0, false);26test('Throws stream error when stdout option errors', testStreamError, destroyOptionStream, noopWritable(), 1, false);27test('Throws stream error when stdout option Duplex errors', testStreamError, destroyOptionStream, noopDuplex(), 1, false);28test('Throws stream error when stderr option errors', testStreamError, destroyOptionStream, noopWritable(), 2, false);29test('Throws stream error when stderr option Duplex errors', testStreamError, destroyOptionStream, noopDuplex(), 2, false);30test('Throws stream error when output stdio[*] option errors', testStreamError, destroyOptionStream, noopWritable(), 3, false);31test('Throws stream error when output stdio[*] Duplex option errors', testStreamError, destroyOptionStream, noopDuplex(), 3, false);32test('Throws stream error when input stdio[*] option errors', testStreamError, destroyOptionStream, noopReadable(), 3, false);33test('Throws stream error when subprocess.stdin errors', testStreamError, destroySubprocessStream, noopReadable(), 0, false);34test('Throws stream error when subprocess.stdin Duplex errors', testStreamError, destroySubprocessStream, noopDuplex(), 0, false);35test('Throws stream error when subprocess.stdout errors', testStreamError, destroySubprocessStream, noopWritable(), 1, false);36test('Throws stream error when subprocess.stdout Duplex errors', testStreamError, destroySubprocessStream, noopDuplex(), 1, false);37test('Throws stream error when subprocess.stderr errors', testStreamError, destroySubprocessStream, noopWritable(), 2, false);38test('Throws stream error when subprocess.stderr Duplex errors', testStreamError, destroySubprocessStream, noopDuplex(), 2, false);39test('Throws stream error when output subprocess.stdio[*] errors', testStreamError, destroySubprocessStream, noopWritable(), 3, false);40test('Throws stream error when output subprocess.stdio[*] Duplex errors', testStreamError, destroySubprocessStream, noopDuplex(), 3, false);41test('Throws stream error when input subprocess.stdio[*] errors', testStreamError, destroySubprocessStream, noopReadable(), 3, false);42test('Throws stream error when stdin option errors, with a transform', testStreamError, destroyOptionStream, noopReadable(), 0, true);43test('Throws stream error when stdin option Duplex errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 0, true);44test('Throws stream error when stdout option errors, with a transform', testStreamError, destroyOptionStream, noopWritable(), 1, true);45test('Throws stream error when stdout option Duplex errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 1, true);46test('Throws stream error when stderr option errors, with a transform', testStreamError, destroyOptionStream, noopWritable(), 2, true);47test('Throws stream error when stderr option Duplex errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 2, true);48test('Throws stream error when output stdio[*] option errors, with a transform', testStreamError, destroyOptionStream, noopWritable(), 3, true);49test('Throws stream error when output stdio[*] Duplex option errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 3, true);50test('Throws stream error when input stdio[*] option errors, with a transform', testStreamError, destroyOptionStream, noopReadable(), 3, true);51test('Throws stream error when subprocess.stdin errors, with a transform', testStreamError, destroySubprocessStream, noopReadable(), 0, true);52test('Throws stream error when subprocess.stdin Duplex errors, with a transform', testStreamError, destroySubprocessStream, noopDuplex(), 0, true);53test('Throws stream error when subprocess.stdout errors, with a transform', testStreamError, destroySubprocessStream, noopWritable(), 1, true);54test('Throws stream error when subprocess.stdout Duplex errors, with a transform', testStreamError, destroySubprocessStream, noopDuplex(), 1, true);55test('Throws stream error when subprocess.stderr errors, with a transform', testStreamError, destroySubprocessStream, noopWritable(), 2, true);56test('Throws stream error when subprocess.stderr Duplex errors, with a transform', testStreamError, destroySubprocessStream, noopDuplex(), 2, true);57test('Throws stream error when output subprocess.stdio[*] errors, with a transform', testStreamError, destroySubprocessStream, noopWritable(), 3, true);58test('Throws stream error when output subprocess.stdio[*] Duplex errors, with a transform', testStreamError, destroySubprocessStream, noopDuplex(), 3, true);59test('Throws stream error when input subprocess.stdio[*] errors, with a transform', testStreamError, destroySubprocessStream, noopReadable(), 3, true);
added:test/terminate/cancel.js+92 added
1import {once} from 'node:events';2import test from 'ava';3import {execa, execaSync} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';56setFixtureDir();78test('result.isCanceled is false when abort isn\'t called (success)', async t => {9 const {isCanceled} = await execa('noop.js');10 t.false(isCanceled);11});1213test('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});1718test('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});2223test('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});2930test('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});3738test('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});4546test('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});5556test('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});6263test('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});7172test('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});7980test('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});8687test('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
1import process from 'node:process';2import {setTimeout} from 'node:timers/promises';3import test from 'ava';4import {pEvent} from 'p-event';5import isRunning from 'is-running';6import {execa, execaSync} from '../../index.js';7import {setFixtureDir} from '../helpers/fixtures-dir.js';8import {nestedExecaAsync, nestedWorker} from '../helpers/nested.js';9import {foobarString} from '../helpers/input.js';1011setFixtureDir();1213const isWindows = process.platform === 'win32';1415// When subprocess exits before current process16const spawnAndExit = async (t, execaMethod, cleanup, detached) => {17 const {stdout} = await execaMethod('noop-fd.js', ['1', foobarString], {cleanup, detached});18 t.is(stdout, foobarString);19};2021test('spawnAndExit', spawnAndExit, nestedExecaAsync, false, false);22test('spawnAndExit cleanup', spawnAndExit, nestedExecaAsync, true, false);23test('spawnAndExit detached', spawnAndExit, nestedExecaAsync, false, true);24test('spawnAndExit cleanup detached', spawnAndExit, nestedExecaAsync, true, true);25test('spawnAndExit, worker', spawnAndExit, nestedWorker, false, false);26test('spawnAndExit cleanup, worker', spawnAndExit, nestedWorker, true, false);27test('spawnAndExit detached, worker', spawnAndExit, nestedWorker, false, true);28test('spawnAndExit cleanup detached, worker', spawnAndExit, nestedWorker, true, true);2930// When current process exits before subprocess31const spawnAndKill = async (t, [signal, cleanup, detached, isKilled]) => {32 const subprocess = execa('subprocess.js', [cleanup, detached], {stdio: 'ignore', ipc: true});3334 const pid = await pEvent(subprocess, 'message');35 t.true(Number.isInteger(pid));36 t.true(isRunning(pid));3738 process.kill(subprocess.pid, signal);3940 await t.throwsAsync(subprocess);41 t.false(isRunning(subprocess.pid));4243 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};5455const pollForSubprocessExit = async pid => {56 while (isRunning(pid)) {57 // eslint-disable-next-line no-await-in-loop58 await setTimeout(100);59 }60};6162// 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 handled68test('spawnAndKill SIGTERM', spawnAndKill, ['SIGTERM', false, false, isWindows]);69test('spawnAndKill SIGKILL', spawnAndKill, ['SIGKILL', false, false, isWindows]);70test('spawnAndKill cleanup SIGTERM', spawnAndKill, ['SIGTERM', true, false, true]);71test('spawnAndKill cleanup SIGKILL', spawnAndKill, ['SIGKILL', true, false, isWindows]);72test('spawnAndKill detached SIGTERM', spawnAndKill, ['SIGTERM', false, true, false]);73test('spawnAndKill detached SIGKILL', spawnAndKill, ['SIGKILL', false, true, false]);74test('spawnAndKill cleanup detached SIGTERM', spawnAndKill, ['SIGTERM', true, true, false]);75test('spawnAndKill cleanup detached SIGKILL', spawnAndKill, ['SIGKILL', true, true, false]);7677// See #12878test('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;8182 const subprocess = execa('noop.js');83 const listener = exitListeners.at(-1);8485 await subprocess;86 t.false(exitListeners.includes(listener));87});8889test('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));9495 process.kill(pid, 'SIGKILL');96});9798test('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
1import {once} from 'node:events';2import {setImmediate} from 'node:timers/promises';3import test from 'ava';4import isRunning from 'is-running';5import {execa} from '../../index.js';6import {setFixtureDir} from '../helpers/fixtures-dir.js';78setFixtureDir();910test('.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});2526test('.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});3435test('.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});4344test('.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});5051test('.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});6566test('.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});7677test('.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
1import process from 'node:process';2import {once, defaultMaxListeners} from 'node:events';3import {constants} from 'node:os';4import {setTimeout} from 'node:timers/promises';5import test from 'ava';6import {pEvent} from 'p-event';7import isRunning from 'is-running';8import {execa} from '../../index.js';9import {setFixtureDir} from '../helpers/fixtures-dir.js';10import {assertMaxListeners} from '../helpers/listeners.js';1112setFixtureDir();1314const isWindows = process.platform === 'win32';1516const 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};2526const spawnNoKillableSimple = options => execa('forever.js', {killSignal: 'SIGWINCH', forceKillAfterDelay: 1, ...options});2728test('kill("SIGKILL") should terminate cleanly', async t => {29 const {subprocess} = await spawnNoKillable();3031 subprocess.kill('SIGKILL');3233 const {isTerminated, signal} = await t.throwsAsync(subprocess);34 t.true(isTerminated);35 t.is(signal, 'SIGKILL');36});3738const testInvalidForceKill = async (t, forceKillAfterDelay) => {39 t.throws(() => {40 execa('empty.js', {forceKillAfterDelay});41 }, {instanceOf: TypeError, message: /non-negative integer/});42};4344test('`forceKillAfterDelay` should not be NaN', testInvalidForceKill, Number.NaN);45test('`forceKillAfterDelay` should not be negative', testInvalidForceKill, -1);4647// `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.49if (isWindows) {50 test('Can call `.kill()` with `forceKillAfterDelay` on Windows', async t => {51 const {subprocess} = await spawnNoKillable(1);52 subprocess.kill();5354 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);6162 subprocess.kill(killArgument);6364 await setTimeout(6e3);65 t.true(isRunning(subprocess.pid));66 subprocess.kill('SIGKILL');6768 const {isTerminated, signal} = await t.throwsAsync(subprocess);69 t.true(isTerminated);70 t.is(signal, 'SIGKILL');71 };7273 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});7778 const testForceKill = async (t, forceKillAfterDelay, killArgument, options) => {79 const {subprocess} = await spawnNoKillable(forceKillAfterDelay, options);8081 subprocess.kill(killArgument);8283 const {isTerminated, signal} = await t.throwsAsync(subprocess);84 t.true(isTerminated);85 t.is(signal, 'SIGKILL');86 };8788 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'});9697 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 });107108 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 });115116 test.serial('Can call `.kill()` with `forceKillAfterDelay` many times without triggering the maxListeners warning', async t => {117 const checkMaxListeners = assertMaxListeners(t);118119 const subprocess = spawnNoKillableSimple();120 for (let index = 0; index < defaultMaxListeners + 1; index += 1) {121 subprocess.kill();122 }123124 const {isTerminated, signal} = await t.throwsAsync(subprocess);125 t.true(isTerminated);126 t.is(signal, 'SIGKILL');127128 checkMaxListeners();129 });130131 test('Can call `.kill()` with `forceKillAfterDelay` multiple times', async t => {132 const subprocess = spawnNoKillableSimple();133 subprocess.kill();134 subprocess.kill();135136 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
1import {once} from 'node:events';2import {setImmediate} from 'node:timers/promises';3import test from 'ava';4import {execa} from '../../index.js';5import {setFixtureDir} from '../helpers/fixtures-dir.js';67setFixtureDir();89test('Can call `.kill()` multiple times', async t => {10 const subprocess = execa('forever.js');11 subprocess.kill();12 subprocess.kill();1314 const {isTerminated, signal} = await t.throwsAsync(subprocess);15 t.true(isTerminated);16 t.is(signal, 'SIGTERM');17});1819test('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});2425const 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};3536test('Cannot call .kill(null)', testInvalidKillArgument, null);37test('Cannot call .kill(0n)', testInvalidKillArgument, 0n);38test('Cannot call .kill(true)', testInvalidKillArgument, true);39test('Cannot call .kill(errorObject)', testInvalidKillArgument, {name: '', message: '', stack: ''});40test('Cannot call .kill(errorArray)', testInvalidKillArgument, [new Error('test')]);41test('Cannot call .kill(undefined, true)', testInvalidKillArgument, undefined, true);42test('Cannot call .kill("SIGTERM", true)', testInvalidKillArgument, 'SIGTERM', true);43test('Cannot call .kill(true, error)', testInvalidKillArgument, true, new Error('test'));4445test('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});5657test('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});6970test('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});8485test('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
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDir, FIXTURES_DIR} from '../helpers/fixtures-dir.js';45setFixtureDir();67test('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});1617test('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});2829test('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});3334test('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});4041const INVALID_TIMEOUT_REGEXP = /`timeout` option to be a non-negative integer/;4243const testTimeoutValidation = (t, timeout, execaMethod) => {44 t.throws(() => {45 execaMethod('empty.js', {timeout});46 }, {message: INVALID_TIMEOUT_REGEXP});47};4849test('timeout must not be negative', testTimeoutValidation, -1, execa);50test('timeout must be an integer', testTimeoutValidation, false, execa);51test('timeout must not be negative - sync', testTimeoutValidation, -1, execaSync);52test('timeout must be an integer - sync', testTimeoutValidation, false, execaSync);5354test('timedOut is false if timeout is undefined', async t => {55 const {timedOut} = await execa('noop.js');56 t.false(timedOut);57});5859test('timedOut is false if timeout is 0', async t => {60 const {timedOut} = await execa('noop.js', {timeout: 0});61 t.false(timedOut);62});6364test('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});6869test('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
1import {Buffer} from 'node:buffer';2import {exec} from 'node:child_process';3import {promisify} from 'node:util';4import test from 'ava';5import getStream from 'get-stream';6import {execa, execaSync} from '../../index.js';7import {setFixtureDir, FIXTURES_DIR} from '../helpers/fixtures-dir.js';8import {fullStdio} from '../helpers/stdio.js';9import {foobarString, foobarUint8Array, foobarHex} from '../helpers/input.js';1011const pExec = promisify(exec);1213setFixtureDir();1415const 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);1819 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 }2526 if (fdNumber === 3) {27 return;28 }2930 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};3334const 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};4243// This string gives different outputs with each encoding type44const STRING_TO_ENCODE = '\u1000.';45const BUFFER_TO_ENCODE = Buffer.from(STRING_TO_ENCODE);4647test('can pass encoding "buffer" to stdout', checkEncoding, 'buffer', 1, execa);48test('can pass encoding "utf8" to stdout', checkEncoding, 'utf8', 1, execa);49test('can pass encoding "utf16le" to stdout', checkEncoding, 'utf16le', 1, execa);50test('can pass encoding "latin1" to stdout', checkEncoding, 'latin1', 1, execa);51test('can pass encoding "ascii" to stdout', checkEncoding, 'ascii', 1, execa);52test('can pass encoding "hex" to stdout', checkEncoding, 'hex', 1, execa);53test('can pass encoding "base64" to stdout', checkEncoding, 'base64', 1, execa);54test('can pass encoding "base64url" to stdout', checkEncoding, 'base64url', 1, execa);55test('can pass encoding "buffer" to stderr', checkEncoding, 'buffer', 2, execa);56test('can pass encoding "utf8" to stderr', checkEncoding, 'utf8', 2, execa);57test('can pass encoding "utf16le" to stderr', checkEncoding, 'utf16le', 2, execa);58test('can pass encoding "latin1" to stderr', checkEncoding, 'latin1', 2, execa);59test('can pass encoding "ascii" to stderr', checkEncoding, 'ascii', 2, execa);60test('can pass encoding "hex" to stderr', checkEncoding, 'hex', 2, execa);61test('can pass encoding "base64" to stderr', checkEncoding, 'base64', 2, execa);62test('can pass encoding "base64url" to stderr', checkEncoding, 'base64url', 2, execa);63test('can pass encoding "buffer" to stdio[*]', checkEncoding, 'buffer', 3, execa);64test('can pass encoding "utf8" to stdio[*]', checkEncoding, 'utf8', 3, execa);65test('can pass encoding "utf16le" to stdio[*]', checkEncoding, 'utf16le', 3, execa);66test('can pass encoding "latin1" to stdio[*]', checkEncoding, 'latin1', 3, execa);67test('can pass encoding "ascii" to stdio[*]', checkEncoding, 'ascii', 3, execa);68test('can pass encoding "hex" to stdio[*]', checkEncoding, 'hex', 3, execa);69test('can pass encoding "base64" to stdio[*]', checkEncoding, 'base64', 3, execa);70test('can pass encoding "base64url" to stdio[*]', checkEncoding, 'base64url', 3, execa);71test('can pass encoding "buffer" to stdout - sync', checkEncoding, 'buffer', 1, execaSync);72test('can pass encoding "utf8" to stdout - sync', checkEncoding, 'utf8', 1, execaSync);73test('can pass encoding "utf16le" to stdout - sync', checkEncoding, 'utf16le', 1, execaSync);74test('can pass encoding "latin1" to stdout - sync', checkEncoding, 'latin1', 1, execaSync);75test('can pass encoding "ascii" to stdout - sync', checkEncoding, 'ascii', 1, execaSync);76test('can pass encoding "hex" to stdout - sync', checkEncoding, 'hex', 1, execaSync);77test('can pass encoding "base64" to stdout - sync', checkEncoding, 'base64', 1, execaSync);78test('can pass encoding "base64url" to stdout - sync', checkEncoding, 'base64url', 1, execaSync);79test('can pass encoding "buffer" to stderr - sync', checkEncoding, 'buffer', 2, execaSync);80test('can pass encoding "utf8" to stderr - sync', checkEncoding, 'utf8', 2, execaSync);81test('can pass encoding "utf16le" to stderr - sync', checkEncoding, 'utf16le', 2, execaSync);82test('can pass encoding "latin1" to stderr - sync', checkEncoding, 'latin1', 2, execaSync);83test('can pass encoding "ascii" to stderr - sync', checkEncoding, 'ascii', 2, execaSync);84test('can pass encoding "hex" to stderr - sync', checkEncoding, 'hex', 2, execaSync);85test('can pass encoding "base64" to stderr - sync', checkEncoding, 'base64', 2, execaSync);86test('can pass encoding "base64url" to stderr - sync', checkEncoding, 'base64url', 2, execaSync);87test('can pass encoding "buffer" to stdio[*] - sync', checkEncoding, 'buffer', 3, execaSync);88test('can pass encoding "utf8" to stdio[*] - sync', checkEncoding, 'utf8', 3, execaSync);89test('can pass encoding "utf16le" to stdio[*] - sync', checkEncoding, 'utf16le', 3, execaSync);90test('can pass encoding "latin1" to stdio[*] - sync', checkEncoding, 'latin1', 3, execaSync);91test('can pass encoding "ascii" to stdio[*] - sync', checkEncoding, 'ascii', 3, execaSync);92test('can pass encoding "hex" to stdio[*] - sync', checkEncoding, 'hex', 3, execaSync);93test('can pass encoding "base64" to stdio[*] - sync', checkEncoding, 'base64', 3, execaSync);94test('can pass encoding "base64url" to stdio[*] - sync', checkEncoding, 'base64url', 3, execaSync);9596// eslint-disable-next-line max-params97const testEncodingInput = async (t, input, expectedStdout, encoding, execaMethod) => {98 const {stdout} = await execaMethod('stdin.js', {input, encoding});99 t.deepEqual(stdout, expectedStdout);100};101102test('Can use string input', testEncodingInput, foobarString, foobarString, 'utf8', execa);103test('Can use Uint8Array input', testEncodingInput, foobarUint8Array, foobarString, 'utf8', execa);104test('Can use string input, encoding "buffer"', testEncodingInput, foobarString, foobarUint8Array, 'buffer', execa);105test('Can use Uint8Array input, encoding "buffer"', testEncodingInput, foobarUint8Array, foobarUint8Array, 'buffer', execa);106test('Can use string input, encoding "hex"', testEncodingInput, foobarString, foobarHex, 'hex', execa);107test('Can use Uint8Array input, encoding "hex"', testEncodingInput, foobarUint8Array, foobarHex, 'hex', execa);108test('Can use string input, sync', testEncodingInput, foobarString, foobarString, 'utf8', execaSync);109test('Can use Uint8Array input, sync', testEncodingInput, foobarUint8Array, foobarString, 'utf8', execaSync);110test('Can use string input, encoding "buffer", sync', testEncodingInput, foobarString, foobarUint8Array, 'buffer', execaSync);111test('Can use Uint8Array input, encoding "buffer", sync', testEncodingInput, foobarUint8Array, foobarUint8Array, 'buffer', execaSync);112test('Can use string input, encoding "hex", sync', testEncodingInput, foobarString, foobarHex, 'hex', execaSync);113test('Can use Uint8Array input, encoding "hex", sync', testEncodingInput, foobarUint8Array, foobarHex, 'hex', execaSync);114115const 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};121122test('Does not modify subprocess.std* encoding, "utf8"', testSubprocessEncoding, 'utf8');123test('Does not modify subprocess.std* encoding, "utf16le"', testSubprocessEncoding, 'utf16le');124test('Does not modify subprocess.std* encoding, "buffer"', testSubprocessEncoding, 'buffer');125test('Does not modify subprocess.std* encoding, "hex"', testSubprocessEncoding, 'hex');126test('Does not modify subprocess.std* encoding, "base64"', testSubprocessEncoding, 'base64');127test('Does not modify subprocess.std* encoding, "base64url"', testSubprocessEncoding, 'base64url');128test('Does not modify subprocess.std* encoding, "latin1"', testSubprocessEncoding, 'latin1');129test('Does not modify subprocess.std* encoding, "ascii"', testSubprocessEncoding, 'ascii');
added:test/transform/encoding-ignored.js+92 added
1import process from 'node:process';2import test from 'ava';3import {execa, execaSync} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';5import {outputObjectGenerator, addNoopGenerator} from '../helpers/generator.js';6import {foobarObject} from '../helpers/input.js';78setFixtureDir();910const 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};1718test('Other encodings work with transforms that return objects', testObjectMode, false, execa);19test('Other encodings work with transforms that return objects, noop transform', testObjectMode, true, execa);20test('Other encodings work with transforms that return objects, sync', testObjectMode, false, execaSync);21test('Other encodings work with transforms that return objects, noop transform, sync', testObjectMode, true, execaSync);2223// eslint-disable-next-line max-params24const testIgnoredEncoding = async (t, stdoutOption, isUndefined, options, execaMethod) => {25 const {stdout} = await execaMethod('empty.js', {stdout: stdoutOption, ...options});26 t.is(stdout === undefined, isUndefined);27};2829const base64Options = {encoding: 'base64'};30const linesOptions = {lines: true};31test('Is ignored with other encodings and "ignore"', testIgnoredEncoding, 'ignore', true, base64Options, execa);32test('Is ignored with other encodings and ["ignore"]', testIgnoredEncoding, ['ignore'], true, base64Options, execa);33test('Is ignored with other encodings and "ipc"', testIgnoredEncoding, 'ipc', true, base64Options, execa);34test('Is ignored with other encodings and ["ipc"]', testIgnoredEncoding, ['ipc'], true, base64Options, execa);35test('Is ignored with other encodings and "inherit"', testIgnoredEncoding, 'inherit', true, base64Options, execa);36test('Is ignored with other encodings and ["inherit"]', testIgnoredEncoding, ['inherit'], true, base64Options, execa);37test('Is ignored with other encodings and 1', testIgnoredEncoding, 1, true, base64Options, execa);38test('Is ignored with other encodings and [1]', testIgnoredEncoding, [1], true, base64Options, execa);39test('Is ignored with other encodings and process.stdout', testIgnoredEncoding, process.stdout, true, base64Options, execa);40test('Is ignored with other encodings and [process.stdout]', testIgnoredEncoding, [process.stdout], true, base64Options, execa);41test('Is not ignored with other encodings and "pipe"', testIgnoredEncoding, 'pipe', false, base64Options, execa);42test('Is not ignored with other encodings and ["pipe"]', testIgnoredEncoding, ['pipe'], false, base64Options, execa);43test('Is not ignored with other encodings and "overlapped"', testIgnoredEncoding, 'overlapped', false, base64Options, execa);44test('Is not ignored with other encodings and ["overlapped"]', testIgnoredEncoding, ['overlapped'], false, base64Options, execa);45test('Is not ignored with other encodings and ["inherit", "pipe"]', testIgnoredEncoding, ['inherit', 'pipe'], false, base64Options, execa);46test('Is not ignored with other encodings and undefined', testIgnoredEncoding, undefined, false, base64Options, execa);47test('Is not ignored with other encodings and null', testIgnoredEncoding, null, false, base64Options, execa);48test('Is ignored with "lines: true" and "ignore"', testIgnoredEncoding, 'ignore', true, linesOptions, execa);49test('Is ignored with "lines: true" and ["ignore"]', testIgnoredEncoding, ['ignore'], true, linesOptions, execa);50test('Is ignored with "lines: true" and "ipc"', testIgnoredEncoding, 'ipc', true, linesOptions, execa);51test('Is ignored with "lines: true" and ["ipc"]', testIgnoredEncoding, ['ipc'], true, linesOptions, execa);52test('Is ignored with "lines: true" and "inherit"', testIgnoredEncoding, 'inherit', true, linesOptions, execa);53test('Is ignored with "lines: true" and ["inherit"]', testIgnoredEncoding, ['inherit'], true, linesOptions, execa);54test('Is ignored with "lines: true" and 1', testIgnoredEncoding, 1, true, linesOptions, execa);55test('Is ignored with "lines: true" and [1]', testIgnoredEncoding, [1], true, linesOptions, execa);56test('Is ignored with "lines: true" and process.stdout', testIgnoredEncoding, process.stdout, true, linesOptions, execa);57test('Is ignored with "lines: true" and [process.stdout]', testIgnoredEncoding, [process.stdout], true, linesOptions, execa);58test('Is not ignored with "lines: true" and "pipe"', testIgnoredEncoding, 'pipe', false, linesOptions, execa);59test('Is not ignored with "lines: true" and ["pipe"]', testIgnoredEncoding, ['pipe'], false, linesOptions, execa);60test('Is not ignored with "lines: true" and "overlapped"', testIgnoredEncoding, 'overlapped', false, linesOptions, execa);61test('Is not ignored with "lines: true" and ["overlapped"]', testIgnoredEncoding, ['overlapped'], false, linesOptions, execa);62test('Is not ignored with "lines: true" and ["inherit", "pipe"]', testIgnoredEncoding, ['inherit', 'pipe'], false, linesOptions, execa);63test('Is not ignored with "lines: true" and undefined', testIgnoredEncoding, undefined, false, linesOptions, execa);64test('Is not ignored with "lines: true" and null', testIgnoredEncoding, null, false, linesOptions, execa);65test('Is ignored with "lines: true", other encodings and "ignore"', testIgnoredEncoding, 'ignore', true, {...base64Options, ...linesOptions}, execa);66test('Is not ignored with "lines: true", other encodings and "pipe"', testIgnoredEncoding, 'pipe', false, {...base64Options, ...linesOptions}, execa);67test('Is ignored with other encodings and "ignore", sync', testIgnoredEncoding, 'ignore', true, base64Options, execaSync);68test('Is ignored with other encodings and ["ignore"], sync', testIgnoredEncoding, ['ignore'], true, base64Options, execaSync);69test('Is ignored with other encodings and "inherit", sync', testIgnoredEncoding, 'inherit', true, base64Options, execaSync);70test('Is ignored with other encodings and ["inherit"], sync', testIgnoredEncoding, ['inherit'], true, base64Options, execaSync);71test('Is ignored with other encodings and 1, sync', testIgnoredEncoding, 1, true, base64Options, execaSync);72test('Is ignored with other encodings and [1], sync', testIgnoredEncoding, [1], true, base64Options, execaSync);73test('Is ignored with other encodings and process.stdout, sync', testIgnoredEncoding, process.stdout, true, base64Options, execaSync);74test('Is ignored with other encodings and [process.stdout], sync', testIgnoredEncoding, [process.stdout], true, base64Options, execaSync);75test('Is not ignored with other encodings and "pipe", sync', testIgnoredEncoding, 'pipe', false, base64Options, execaSync);76test('Is not ignored with other encodings and ["pipe"], sync', testIgnoredEncoding, ['pipe'], false, base64Options, execaSync);77test('Is not ignored with other encodings and undefined, sync', testIgnoredEncoding, undefined, false, base64Options, execaSync);78test('Is not ignored with other encodings and null, sync', testIgnoredEncoding, null, false, base64Options, execaSync);79test('Is ignored with "lines: true" and "ignore", sync', testIgnoredEncoding, 'ignore', true, linesOptions, execaSync);80test('Is ignored with "lines: true" and ["ignore"], sync', testIgnoredEncoding, ['ignore'], true, linesOptions, execaSync);81test('Is ignored with "lines: true" and "inherit", sync', testIgnoredEncoding, 'inherit', true, linesOptions, execaSync);82test('Is ignored with "lines: true" and ["inherit"], sync', testIgnoredEncoding, ['inherit'], true, linesOptions, execaSync);83test('Is ignored with "lines: true" and 1, sync', testIgnoredEncoding, 1, true, linesOptions, execaSync);84test('Is ignored with "lines: true" and [1], sync', testIgnoredEncoding, [1], true, linesOptions, execaSync);85test('Is ignored with "lines: true" and process.stdout, sync', testIgnoredEncoding, process.stdout, true, linesOptions, execaSync);86test('Is ignored with "lines: true" and [process.stdout], sync', testIgnoredEncoding, [process.stdout], true, linesOptions, execaSync);87test('Is not ignored with "lines: true" and "pipe", sync', testIgnoredEncoding, 'pipe', false, linesOptions, execaSync);88test('Is not ignored with "lines: true" and ["pipe"], sync', testIgnoredEncoding, ['pipe'], false, linesOptions, execaSync);89test('Is not ignored with "lines: true" and undefined, sync', testIgnoredEncoding, undefined, false, linesOptions, execaSync);90test('Is not ignored with "lines: true" and null, sync', testIgnoredEncoding, null, false, linesOptions, execaSync);91test('Is ignored with "lines: true", other encodings and "ignore", sync', testIgnoredEncoding, 'ignore', true, {...base64Options, ...linesOptions}, execaSync);92test('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
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {noopGenerator, getOutputsGenerator, addNoopGenerator} from '../helpers/generator.js';5import {multibyteChar, multibyteString, multibyteUint8Array, breakingLength, brokenSymbol} from '../helpers/encoding.js';67setFixtureDir();89const foobarArray = ['fo', 'ob', 'ar', '..'];1011const 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};2223test('Handle multibyte characters', testMultibyteCharacters, false, false, execa);24test('Handle multibyte characters, noop transform', testMultibyteCharacters, false, true, execa);25test('Handle multibyte characters, with objectMode', testMultibyteCharacters, true, false, execa);26test('Handle multibyte characters, with objectMode, noop transform', testMultibyteCharacters, true, true, execa);27test('Handle multibyte characters, sync', testMultibyteCharacters, false, false, execaSync);28test('Handle multibyte characters, noop transform, sync', testMultibyteCharacters, false, true, execaSync);29test('Handle multibyte characters, with objectMode, sync', testMultibyteCharacters, true, false, execaSync);30test('Handle multibyte characters, with objectMode, noop transform, sync', testMultibyteCharacters, true, true, execaSync);3132const 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};4142test('Generator handles multibyte characters with Uint8Array', testMultibyte, false, execa);43test('Generator handles multibyte characters with Uint8Array, objectMode', testMultibyte, true, execa);44test('Generator handles multibyte characters with Uint8Array, sync', testMultibyte, false, execaSync);45test('Generator handles multibyte characters with Uint8Array, objectMode, sync', testMultibyte, true, execaSync);4647const 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};5657test('Generator handles partial multibyte characters with Uint8Array', testMultibytePartial, false, execa);58test('Generator handles partial multibyte characters with Uint8Array, objectMode', testMultibytePartial, true, execa);59test('Generator handles partial multibyte characters with Uint8Array, sync', testMultibytePartial, false, execaSync);60test('Generator handles partial multibyte characters with Uint8Array, objectMode, sync', testMultibytePartial, true, execaSync);6162const 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};7172test('Generator handles output multibyte characters with Uint8Array', testMultibytePartialOutput, execa);73test('Generator handles output multibyte characters with Uint8Array, sync', testMultibytePartialOutput, execaSync);
added:test/transform/encoding-transform.js+172 added
1import {Buffer} from 'node:buffer';2import test from 'ava';3import {execa, execaSync} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';5import {getStdio} from '../helpers/stdio.js';6import {foobarString, foobarUint8Array, foobarBuffer, foobarObject} from '../helpers/input.js';7import {noopGenerator, getOutputGenerator} from '../helpers/generator.js';89setFixtureDir();1011const getTypeofGenerator = lines => (objectMode, binary) => ({12 * transform(line) {13 lines.push(Object.prototype.toString.call(line));14 yield '';15 },16 objectMode,17 binary,18});1920const assertTypeofChunk = (t, lines, expectedType) => {21 t.deepEqual(lines, [`[object ${expectedType}]`]);22};2324// eslint-disable-next-line max-params25const 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};3233test('First generator argument is string with default encoding, with string writes', testGeneratorFirstEncoding, foobarString, 'utf8', 'String', false, undefined);34test('First generator argument is string with default encoding, with Buffer writes', testGeneratorFirstEncoding, foobarBuffer, 'utf8', 'String', false, undefined);35test('First generator argument is string with default encoding, with Uint8Array writes', testGeneratorFirstEncoding, foobarUint8Array, 'utf8', 'String', false, undefined);36test('First generator argument is string with default encoding, with string writes, "binary: false"', testGeneratorFirstEncoding, foobarString, 'utf8', 'String', false, false);37test('First generator argument is Uint8Array with default encoding, with string writes, "binary: true"', testGeneratorFirstEncoding, foobarString, 'utf8', 'Uint8Array', false, true);38test('First generator argument is string with encoding "utf16le", with string writes', testGeneratorFirstEncoding, foobarString, 'utf16le', 'String', false, undefined);39test('First generator argument is string with encoding "utf16le", with Buffer writes', testGeneratorFirstEncoding, foobarBuffer, 'utf16le', 'String', false, undefined);40test('First generator argument is string with encoding "utf16le", with Uint8Array writes', testGeneratorFirstEncoding, foobarUint8Array, 'utf16le', 'String', false, undefined);41test('First generator argument is string with encoding "utf16le", with string writes, "binary: false"', testGeneratorFirstEncoding, foobarString, 'utf16le', 'String', false, false);42test('First generator argument is Uint8Array with encoding "utf16le", with string writes, "binary: true"', testGeneratorFirstEncoding, foobarString, 'utf16le', 'Uint8Array', false, true);43test('First generator argument is Uint8Array with encoding "buffer", with string writes', testGeneratorFirstEncoding, foobarString, 'buffer', 'Uint8Array', false, undefined);44test('First generator argument is Uint8Array with encoding "buffer", with Buffer writes', testGeneratorFirstEncoding, foobarBuffer, 'buffer', 'Uint8Array', false, undefined);45test('First generator argument is Uint8Array with encoding "buffer", with Uint8Array writes', testGeneratorFirstEncoding, foobarUint8Array, 'buffer', 'Uint8Array', false, undefined);46test('First generator argument is Uint8Array with encoding "buffer", with string writes, "binary: false"', testGeneratorFirstEncoding, foobarString, 'buffer', 'Uint8Array', false, false);47test('First generator argument is Uint8Array with encoding "buffer", with string writes, "binary: true"', testGeneratorFirstEncoding, foobarString, 'buffer', 'Uint8Array', false, true);48test('First generator argument is Uint8Array with encoding "hex", with string writes', testGeneratorFirstEncoding, foobarString, 'hex', 'Uint8Array', false, undefined);49test('First generator argument is Uint8Array with encoding "hex", with Buffer writes', testGeneratorFirstEncoding, foobarBuffer, 'hex', 'Uint8Array', false, undefined);50test('First generator argument is Uint8Array with encoding "hex", with Uint8Array writes', testGeneratorFirstEncoding, foobarUint8Array, 'hex', 'Uint8Array', false, undefined);51test('First generator argument is Uint8Array with encoding "hex", with string writes, "binary: false"', testGeneratorFirstEncoding, foobarString, 'hex', 'Uint8Array', false, false);52test('First generator argument is Uint8Array with encoding "hex", with string writes, "binary: true"', testGeneratorFirstEncoding, foobarString, 'hex', 'Uint8Array', false, true);53test('First generator argument can be string with objectMode', testGeneratorFirstEncoding, foobarString, 'utf8', 'String', true, undefined);54test('First generator argument can be string with objectMode, "binary: false"', testGeneratorFirstEncoding, foobarString, 'utf8', 'String', true, false);55test('First generator argument can be string with objectMode, "binary: true"', testGeneratorFirstEncoding, foobarString, 'utf8', 'String', true, true);56test('First generator argument can be objects with objectMode', testGeneratorFirstEncoding, foobarObject, 'utf8', 'Object', true, undefined);57test('First generator argument can be objects with objectMode, "binary: false"', testGeneratorFirstEncoding, foobarObject, 'utf8', 'Object', true, false);58test('First generator argument can be objects with objectMode, "binary: true"', testGeneratorFirstEncoding, foobarObject, 'utf8', 'Object', true, true);5960// eslint-disable-next-line max-params61const 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};6667test('First generator argument is string with default encoding, with string writes, sync', testGeneratorFirstEncodingSync, foobarString, 'utf8', 'String', false, undefined);68test('First generator argument is string with default encoding, with Uint8Array writes, sync', testGeneratorFirstEncodingSync, foobarUint8Array, 'utf8', 'String', false, undefined);69test('First generator argument is string with default encoding, with string writes, "binary: false", sync', testGeneratorFirstEncodingSync, foobarString, 'utf8', 'String', false, false);70test('First generator argument is Uint8Array with default encoding, with string writes, "binary: true", sync', testGeneratorFirstEncodingSync, foobarString, 'utf8', 'Uint8Array', false, true);71test('First generator argument is string with encoding "utf16le", with string writes, sync', testGeneratorFirstEncodingSync, foobarString, 'utf16le', 'String', false, undefined);72test('First generator argument is string with encoding "utf16le", with Uint8Array writes, sync', testGeneratorFirstEncodingSync, foobarUint8Array, 'utf16le', 'String', false, undefined);73test('First generator argument is string with encoding "utf16le", with string writes, "binary: false", sync', testGeneratorFirstEncodingSync, foobarString, 'utf16le', 'String', false, false);74test('First generator argument is Uint8Array with encoding "utf16le", with string writes, "binary: true", sync', testGeneratorFirstEncodingSync, foobarString, 'utf16le', 'Uint8Array', false, true);75test('First generator argument is Uint8Array with encoding "buffer", with string writes, sync', testGeneratorFirstEncodingSync, foobarString, 'buffer', 'Uint8Array', false, undefined);76test('First generator argument is Uint8Array with encoding "buffer", with Uint8Array writes, sync', testGeneratorFirstEncodingSync, foobarUint8Array, 'buffer', 'Uint8Array', false, undefined);77test('First generator argument is Uint8Array with encoding "buffer", with string writes, "binary: false", sync', testGeneratorFirstEncodingSync, foobarString, 'buffer', 'Uint8Array', false, false);78test('First generator argument is Uint8Array with encoding "buffer", with string writes, "binary: true", sync', testGeneratorFirstEncodingSync, foobarString, 'buffer', 'Uint8Array', false, true);79test('First generator argument is Uint8Array with encoding "hex", with string writes, sync', testGeneratorFirstEncodingSync, foobarString, 'hex', 'Uint8Array', false, undefined);80test('First generator argument is Uint8Array with encoding "hex", with Uint8Array writes, sync', testGeneratorFirstEncodingSync, foobarUint8Array, 'hex', 'Uint8Array', false, undefined);81test('First generator argument is Uint8Array with encoding "hex", with string writes, "binary: false", sync', testGeneratorFirstEncodingSync, foobarString, 'hex', 'Uint8Array', false, false);82test('First generator argument is Uint8Array with encoding "hex", with string writes, "binary: true", sync', testGeneratorFirstEncodingSync, foobarString, 'hex', 'Uint8Array', false, true);83test('First generator argument can be string with objectMode, sync', testGeneratorFirstEncodingSync, foobarString, 'utf8', 'String', true, undefined);84test('First generator argument can be string with objectMode, "binary: false", sync', testGeneratorFirstEncodingSync, foobarString, 'utf8', 'String', true, false);85test('First generator argument can be string with objectMode, "binary: true", sync', testGeneratorFirstEncodingSync, foobarString, 'utf8', 'String', true, true);86test('First generator argument can be objects with objectMode, sync', testGeneratorFirstEncodingSync, foobarObject, 'utf8', 'Object', true, undefined);87test('First generator argument can be objects with objectMode, "binary: false", sync', testGeneratorFirstEncodingSync, foobarObject, 'utf8', 'Object', true, false);88test('First generator argument can be objects with objectMode, "binary: true", sync', testGeneratorFirstEncodingSync, foobarObject, 'utf8', 'Object', true, true);8990const 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};9798test('Write call encoding "utf8" is ignored with objectMode', testEncodingIgnored, 'utf8');99test('Write call encoding "utf16le" is ignored with objectMode', testEncodingIgnored, 'utf16le');100test('Write call encoding "hex" is ignored with objectMode', testEncodingIgnored, 'hex');101test('Write call encoding "base64" is ignored with objectMode', testEncodingIgnored, 'base64');102103// eslint-disable-next-line max-params104const 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};115116test('Next generator argument is string with default encoding, with string writes', testGeneratorNextEncoding, foobarString, 'utf8', false, false, 'String', execa);117test('Next generator argument is string with default encoding, with string writes, objectMode first', testGeneratorNextEncoding, foobarString, 'utf8', true, false, 'String', execa);118test('Next generator argument is string with default encoding, with string writes, objectMode both', testGeneratorNextEncoding, foobarString, 'utf8', true, true, 'String', execa);119test('Next generator argument is string with default encoding, with Uint8Array writes', testGeneratorNextEncoding, foobarUint8Array, 'utf8', false, false, 'String', execa);120test('Next generator argument is Uint8Array with default encoding, with Uint8Array writes, objectMode first', testGeneratorNextEncoding, foobarUint8Array, 'utf8', true, false, 'Uint8Array', execa);121test('Next generator argument is string with default encoding, with Uint8Array writes, objectMode both', testGeneratorNextEncoding, foobarUint8Array, 'utf8', true, true, 'Uint8Array', execa);122test('Next generator argument is string with encoding "utf16le", with string writes', testGeneratorNextEncoding, foobarString, 'utf16le', false, false, 'String', execa);123test('Next generator argument is string with encoding "utf16le",, with string writes, objectMode first', testGeneratorNextEncoding, foobarString, 'utf16le', true, false, 'String', execa);124test('Next generator argument is string with encoding "utf16le",, with string writes, objectMode both', testGeneratorNextEncoding, foobarString, 'utf16le', true, true, 'String', execa);125test('Next generator argument is string with encoding "utf16le",, with Uint8Array writes', testGeneratorNextEncoding, foobarUint8Array, 'utf16le', false, false, 'String', execa);126test('Next generator argument is Uint8Array with encoding "utf16le",, with Uint8Array writes, objectMode first', testGeneratorNextEncoding, foobarUint8Array, 'utf16le', true, false, 'Uint8Array', execa);127test('Next generator argument is string with encoding "utf16le",, with Uint8Array writes, objectMode both', testGeneratorNextEncoding, foobarUint8Array, 'utf16le', true, true, 'Uint8Array', execa);128test('Next generator argument is Uint8Array with encoding "buffer", with string writes', testGeneratorNextEncoding, foobarString, 'buffer', false, false, 'Uint8Array', execa);129test('Next generator argument is string with encoding "buffer", with string writes, objectMode first', testGeneratorNextEncoding, foobarString, 'buffer', true, false, 'String', execa);130test('Next generator argument is string with encoding "buffer", with string writes, objectMode both', testGeneratorNextEncoding, foobarString, 'buffer', true, true, 'String', execa);131test('Next generator argument is Uint8Array with encoding "buffer", with Uint8Array writes', testGeneratorNextEncoding, foobarUint8Array, 'buffer', false, false, 'Uint8Array', execa);132test('Next generator argument is Uint8Array with encoding "buffer", with Uint8Array writes, objectMode first', testGeneratorNextEncoding, foobarUint8Array, 'buffer', true, false, 'Uint8Array', execa);133test('Next generator argument is Uint8Array with encoding "buffer", with Uint8Array writes, objectMode both', testGeneratorNextEncoding, foobarUint8Array, 'buffer', true, true, 'Uint8Array', execa);134test('Next generator argument is Uint8Array with encoding "hex", with string writes', testGeneratorNextEncoding, foobarString, 'hex', false, false, 'Uint8Array', execa);135test('Next generator argument is Uint8Array with encoding "hex", with Uint8Array writes', testGeneratorNextEncoding, foobarUint8Array, 'hex', false, false, 'Uint8Array', execa);136test('Next generator argument is object with default encoding, with object writes, objectMode first', testGeneratorNextEncoding, foobarObject, 'utf8', true, false, 'Object', execa);137test('Next generator argument is object with default encoding, with object writes, objectMode both', testGeneratorNextEncoding, foobarObject, 'utf8', true, true, 'Object', execa);138test('Next generator argument is string with default encoding, with string writes, sync', testGeneratorNextEncoding, foobarString, 'utf8', false, false, 'String', execaSync);139test('Next generator argument is string with default encoding, with string writes, objectMode first, sync', testGeneratorNextEncoding, foobarString, 'utf8', true, false, 'String', execaSync);140test('Next generator argument is string with default encoding, with string writes, objectMode both, sync', testGeneratorNextEncoding, foobarString, 'utf8', true, true, 'String', execaSync);141test('Next generator argument is string with default encoding, with Uint8Array writes, sync', testGeneratorNextEncoding, foobarUint8Array, 'utf8', false, false, 'String', execaSync);142test('Next generator argument is Uint8Array with default encoding, with Uint8Array writes, objectMode first, sync', testGeneratorNextEncoding, foobarUint8Array, 'utf8', true, false, 'Uint8Array', execaSync);143test('Next generator argument is string with default encoding, with Uint8Array writes, objectMode both, sync', testGeneratorNextEncoding, foobarUint8Array, 'utf8', true, true, 'Uint8Array', execaSync);144test('Next generator argument is string with encoding "utf16le", with string writes, sync', testGeneratorNextEncoding, foobarString, 'utf16le', false, false, 'String', execaSync);145test('Next generator argument is string with encoding "utf16le",, with string writes, objectMode first, sync', testGeneratorNextEncoding, foobarString, 'utf16le', true, false, 'String', execaSync);146test('Next generator argument is string with encoding "utf16le",, with string writes, objectMode both, sync', testGeneratorNextEncoding, foobarString, 'utf16le', true, true, 'String', execaSync);147test('Next generator argument is string with encoding "utf16le",, with Uint8Array writes, sync', testGeneratorNextEncoding, foobarUint8Array, 'utf16le', false, false, 'String', execaSync);148test('Next generator argument is Uint8Array with encoding "utf16le",, with Uint8Array writes, objectMode first, sync', testGeneratorNextEncoding, foobarUint8Array, 'utf16le', true, false, 'Uint8Array', execaSync);149test('Next generator argument is string with encoding "utf16le",, with Uint8Array writes, objectMode both, sync', testGeneratorNextEncoding, foobarUint8Array, 'utf16le', true, true, 'Uint8Array', execaSync);150test('Next generator argument is Uint8Array with encoding "buffer", with string writes, sync', testGeneratorNextEncoding, foobarString, 'buffer', false, false, 'Uint8Array', execaSync);151test('Next generator argument is string with encoding "buffer", with string writes, objectMode first, sync', testGeneratorNextEncoding, foobarString, 'buffer', true, false, 'String', execaSync);152test('Next generator argument is string with encoding "buffer", with string writes, objectMode both, sync', testGeneratorNextEncoding, foobarString, 'buffer', true, true, 'String', execaSync);153test('Next generator argument is Uint8Array with encoding "buffer", with Uint8Array writes, sync', testGeneratorNextEncoding, foobarUint8Array, 'buffer', false, false, 'Uint8Array', execaSync);154test('Next generator argument is Uint8Array with encoding "buffer", with Uint8Array writes, objectMode first, sync', testGeneratorNextEncoding, foobarUint8Array, 'buffer', true, false, 'Uint8Array', execaSync);155test('Next generator argument is Uint8Array with encoding "buffer", with Uint8Array writes, objectMode both, sync', testGeneratorNextEncoding, foobarUint8Array, 'buffer', true, true, 'Uint8Array', execaSync);156test('Next generator argument is Uint8Array with encoding "hex", with string writes, sync', testGeneratorNextEncoding, foobarString, 'hex', false, false, 'Uint8Array', execaSync);157test('Next generator argument is Uint8Array with encoding "hex", with Uint8Array writes, sync', testGeneratorNextEncoding, foobarUint8Array, 'hex', false, false, 'Uint8Array', execaSync);158test('Next generator argument is object with default encoding, with object writes, objectMode first, sync', testGeneratorNextEncoding, foobarObject, 'utf8', true, false, 'Object', execaSync);159test('Next generator argument is object with default encoding, with object writes, objectMode both, sync', testGeneratorNextEncoding, foobarObject, 'utf8', true, true, 'Object', execaSync);160161const 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};166167test('The first generator with result.stdout does not receive an object argument even in objectMode', testFirstOutputGeneratorArgument, 1, execa);168test('The first generator with result.stderr does not receive an object argument even in objectMode', testFirstOutputGeneratorArgument, 2, execa);169test('The first generator with result.stdio[*] does not receive an object argument even in objectMode', testFirstOutputGeneratorArgument, 3, execa);170test('The first generator with result.stdout does not receive an object argument even in objectMode, sync', testFirstOutputGeneratorArgument, 1, execaSync);171test('The first generator with result.stderr does not receive an object argument even in objectMode, sync', testFirstOutputGeneratorArgument, 2, execaSync);172test('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
1import {Buffer} from 'node:buffer';2import test from 'ava';3import {execa, execaSync} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';5import {foobarObject} from '../helpers/input.js';6import {7 outputObjectGenerator,8 uppercaseGenerator,9 uppercaseBufferGenerator,10} from '../helpers/generator.js';1112setFixtureDir();1314const textEncoder = new TextEncoder();1516const getAllStdioOption = (stdioOption, encoding, objectMode) => {17 if (stdioOption) {18 return 'pipe';19 }2021 if (objectMode) {22 return outputObjectGenerator();23 }2425 return encoding === 'utf8' ? uppercaseGenerator() : uppercaseBufferGenerator();26};2728const getStdoutStderrOutput = ({output, stdioOption, encoding, objectMode, lines}) => {29 if (objectMode && !stdioOption) {30 return encoding === 'utf8' ? [foobarObject, foobarObject] : [foobarObject];31 }3233 const stdioOutput = stdioOption ? output : output.toUpperCase();3435 if (encoding === 'hex') {36 return Buffer.from(stdioOutput).toString('hex');37 }3839 if (encoding === 'buffer') {40 return textEncoder.encode(stdioOutput);41 }4243 return lines ? stdioOutput.trim().split('\n').map(string => `${string}\n`) : stdioOutput;44};4546const getAllOutput = ({stdoutOutput, stderrOutput, encoding, objectMode, lines}) => {47 if (objectMode || (lines && encoding === 'utf8')) {48 return [stdoutOutput, stderrOutput].flat();49 }5051 return encoding === 'buffer'52 ? new Uint8Array([...stdoutOutput, ...stderrOutput])53 : `${stdoutOutput}${stderrOutput}`;54};5556// eslint-disable-next-line max-params57const 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 });6869 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};8081test('Can use generators with result.all = transform + transform', testGeneratorAll, true, 'utf8', false, false, false, false, execa);82test('Can use generators with error.all = transform + transform', testGeneratorAll, false, 'utf8', false, false, false, false, execa);83test('Can use generators with result.all = transform + transform, encoding "buffer"', testGeneratorAll, true, 'buffer', false, false, false, false, execa);84test('Can use generators with error.all = transform + transform, encoding "buffer"', testGeneratorAll, false, 'buffer', false, false, false, false, execa);85test('Can use generators with result.all = transform + transform, encoding "hex"', testGeneratorAll, true, 'hex', false, false, false, false, execa);86test('Can use generators with error.all = transform + transform, encoding "hex"', testGeneratorAll, false, 'hex', false, false, false, false, execa);87test('Can use generators with result.all = transform + pipe', testGeneratorAll, true, 'utf8', false, false, true, false, execa);88test('Can use generators with error.all = transform + pipe', testGeneratorAll, false, 'utf8', false, false, true, false, execa);89test('Can use generators with result.all = transform + pipe, encoding "buffer"', testGeneratorAll, true, 'buffer', false, false, true, false, execa);90test('Can use generators with error.all = transform + pipe, encoding "buffer"', testGeneratorAll, false, 'buffer', false, false, true, false, execa);91test('Can use generators with result.all = transform + pipe, encoding "hex"', testGeneratorAll, true, 'hex', false, false, true, false, execa);92test('Can use generators with error.all = transform + pipe, encoding "hex"', testGeneratorAll, false, 'hex', false, false, true, false, execa);93test('Can use generators with result.all = pipe + transform', testGeneratorAll, true, 'utf8', false, true, false, false, execa);94test('Can use generators with error.all = pipe + transform', testGeneratorAll, false, 'utf8', false, true, false, false, execa);95test('Can use generators with result.all = pipe + transform, encoding "buffer"', testGeneratorAll, true, 'buffer', false, true, false, false, execa);96test('Can use generators with error.all = pipe + transform, encoding "buffer"', testGeneratorAll, false, 'buffer', false, true, false, false, execa);97test('Can use generators with result.all = pipe + transform, encoding "hex"', testGeneratorAll, true, 'hex', false, true, false, false, execa);98test('Can use generators with error.all = pipe + transform, encoding "hex"', testGeneratorAll, false, 'hex', false, true, false, false, execa);99test('Can use generators with result.all = transform + transform, objectMode', testGeneratorAll, true, 'utf8', true, false, false, false, execa);100test('Can use generators with error.all = transform + transform, objectMode', testGeneratorAll, false, 'utf8', true, false, false, false, execa);101test('Can use generators with result.all = transform + transform, objectMode, encoding "buffer"', testGeneratorAll, true, 'buffer', true, false, false, false, execa);102test('Can use generators with error.all = transform + transform, objectMode, encoding "buffer"', testGeneratorAll, false, 'buffer', true, false, false, false, execa);103test('Can use generators with result.all = transform + transform, objectMode, encoding "hex"', testGeneratorAll, true, 'hex', true, false, false, false, execa);104test('Can use generators with error.all = transform + transform, objectMode, encoding "hex"', testGeneratorAll, false, 'hex', true, false, false, false, execa);105test('Can use generators with result.all = transform + pipe, objectMode', testGeneratorAll, true, 'utf8', true, false, true, false, execa);106test('Can use generators with error.all = transform + pipe, objectMode', testGeneratorAll, false, 'utf8', true, false, true, false, execa);107test('Can use generators with result.all = transform + pipe, objectMode, encoding "buffer"', testGeneratorAll, true, 'buffer', true, false, true, false, execa);108test('Can use generators with error.all = transform + pipe, objectMode, encoding "buffer"', testGeneratorAll, false, 'buffer', true, false, true, false, execa);109test('Can use generators with result.all = transform + pipe, objectMode, encoding "hex"', testGeneratorAll, true, 'hex', true, false, true, false, execa);110test('Can use generators with error.all = transform + pipe, objectMode, encoding "hex"', testGeneratorAll, false, 'hex', true, false, true, false, execa);111test('Can use generators with result.all = pipe + transform, objectMode', testGeneratorAll, true, 'utf8', true, true, false, false, execa);112test('Can use generators with error.all = pipe + transform, objectMode', testGeneratorAll, false, 'utf8', true, true, false, false, execa);113test('Can use generators with result.all = pipe + transform, objectMode, encoding "buffer"', testGeneratorAll, true, 'buffer', true, true, false, false, execa);114test('Can use generators with error.all = pipe + transform, objectMode, encoding "buffer"', testGeneratorAll, false, 'buffer', true, true, false, false, execa);115test('Can use generators with result.all = pipe + transform, objectMode, encoding "hex"', testGeneratorAll, true, 'hex', true, true, false, false, execa);116test('Can use generators with error.all = pipe + transform, objectMode, encoding "hex"', testGeneratorAll, false, 'hex', true, true, false, false, execa);117test('Can use generators with result.all = transform + transform, sync', testGeneratorAll, true, 'utf8', false, false, false, false, execaSync);118test('Can use generators with error.all = transform + transform, sync', testGeneratorAll, false, 'utf8', false, false, false, false, execaSync);119test('Can use generators with result.all = transform + transform, encoding "buffer", sync', testGeneratorAll, true, 'buffer', false, false, false, false, execaSync);120test('Can use generators with error.all = transform + transform, encoding "buffer", sync', testGeneratorAll, false, 'buffer', false, false, false, false, execaSync);121test('Can use generators with result.all = transform + transform, encoding "hex", sync', testGeneratorAll, true, 'hex', false, false, false, false, execaSync);122test('Can use generators with error.all = transform + transform, encoding "hex", sync', testGeneratorAll, false, 'hex', false, false, false, false, execaSync);123test('Can use generators with result.all = transform + pipe, sync', testGeneratorAll, true, 'utf8', false, false, true, false, execaSync);124test('Can use generators with error.all = transform + pipe, sync', testGeneratorAll, false, 'utf8', false, false, true, false, execaSync);125test('Can use generators with result.all = transform + pipe, encoding "buffer", sync', testGeneratorAll, true, 'buffer', false, false, true, false, execaSync);126test('Can use generators with error.all = transform + pipe, encoding "buffer", sync', testGeneratorAll, false, 'buffer', false, false, true, false, execaSync);127test('Can use generators with result.all = transform + pipe, encoding "hex", sync', testGeneratorAll, true, 'hex', false, false, true, false, execaSync);128test('Can use generators with error.all = transform + pipe, encoding "hex", sync', testGeneratorAll, false, 'hex', false, false, true, false, execaSync);129test('Can use generators with result.all = pipe + transform, sync', testGeneratorAll, true, 'utf8', false, true, false, false, execaSync);130test('Can use generators with error.all = pipe + transform, sync', testGeneratorAll, false, 'utf8', false, true, false, false, execaSync);131test('Can use generators with result.all = pipe + transform, encoding "buffer", sync', testGeneratorAll, true, 'buffer', false, true, false, false, execaSync);132test('Can use generators with error.all = pipe + transform, encoding "buffer", sync', testGeneratorAll, false, 'buffer', false, true, false, false, execaSync);133test('Can use generators with result.all = pipe + transform, encoding "hex", sync', testGeneratorAll, true, 'hex', false, true, false, false, execaSync);134test('Can use generators with error.all = pipe + transform, encoding "hex", sync', testGeneratorAll, false, 'hex', false, true, false, false, execaSync);135test('Can use generators with result.all = transform + transform, objectMode, sync', testGeneratorAll, true, 'utf8', true, false, false, false, execaSync);136test('Can use generators with error.all = transform + transform, objectMode, sync', testGeneratorAll, false, 'utf8', true, false, false, false, execaSync);137test('Can use generators with result.all = transform + transform, objectMode, encoding "buffer", sync', testGeneratorAll, true, 'buffer', true, false, false, false, execaSync);138test('Can use generators with error.all = transform + transform, objectMode, encoding "buffer", sync', testGeneratorAll, false, 'buffer', true, false, false, false, execaSync);139test('Can use generators with result.all = transform + transform, objectMode, encoding "hex", sync', testGeneratorAll, true, 'hex', true, false, false, false, execaSync);140test('Can use generators with error.all = transform + transform, objectMode, encoding "hex", sync', testGeneratorAll, false, 'hex', true, false, false, false, execaSync);141test('Can use generators with result.all = transform + pipe, objectMode, sync', testGeneratorAll, true, 'utf8', true, false, true, false, execaSync);142test('Can use generators with error.all = transform + pipe, objectMode, sync', testGeneratorAll, false, 'utf8', true, false, true, false, execaSync);143test('Can use generators with result.all = transform + pipe, objectMode, encoding "buffer", sync', testGeneratorAll, true, 'buffer', true, false, true, false, execaSync);144test('Can use generators with error.all = transform + pipe, objectMode, encoding "buffer", sync', testGeneratorAll, false, 'buffer', true, false, true, false, execaSync);145test('Can use generators with result.all = transform + pipe, objectMode, encoding "hex", sync', testGeneratorAll, true, 'hex', true, false, true, false, execaSync);146test('Can use generators with error.all = transform + pipe, objectMode, encoding "hex", sync', testGeneratorAll, false, 'hex', true, false, true, false, execaSync);147test('Can use generators with result.all = pipe + transform, objectMode, sync', testGeneratorAll, true, 'utf8', true, true, false, false, execaSync);148test('Can use generators with error.all = pipe + transform, objectMode, sync', testGeneratorAll, false, 'utf8', true, true, false, false, execaSync);149test('Can use generators with result.all = pipe + transform, objectMode, encoding "buffer", sync', testGeneratorAll, true, 'buffer', true, true, false, false, execaSync);150test('Can use generators with error.all = pipe + transform, objectMode, encoding "buffer", sync', testGeneratorAll, false, 'buffer', true, true, false, false, execaSync);151test('Can use generators with result.all = pipe + transform, objectMode, encoding "hex", sync', testGeneratorAll, true, 'hex', true, true, false, false, execaSync);152test('Can use generators with error.all = pipe + transform, objectMode, encoding "hex", sync', testGeneratorAll, false, 'hex', true, true, false, false, execaSync);153test('Can use generators with result.all = transform + transform, lines', testGeneratorAll, true, 'utf8', false, false, false, true, execa);154test('Can use generators with error.all = transform + transform, lines', testGeneratorAll, false, 'utf8', false, false, false, true, execa);155test('Can use generators with result.all = transform + transform, encoding "buffer", lines', testGeneratorAll, true, 'buffer', false, false, false, true, execa);156test('Can use generators with error.all = transform + transform, encoding "buffer", lines', testGeneratorAll, false, 'buffer', false, false, false, true, execa);157test('Can use generators with result.all = transform + transform, encoding "hex", lines', testGeneratorAll, true, 'hex', false, false, false, true, execa);158test('Can use generators with error.all = transform + transform, encoding "hex", lines', testGeneratorAll, false, 'hex', false, false, false, true, execa);159test('Can use generators with result.all = transform + pipe, lines', testGeneratorAll, true, 'utf8', false, false, true, true, execa);160test('Can use generators with error.all = transform + pipe, lines', testGeneratorAll, false, 'utf8', false, false, true, true, execa);161test('Can use generators with result.all = transform + pipe, encoding "buffer", lines', testGeneratorAll, true, 'buffer', false, false, true, true, execa);162test('Can use generators with error.all = transform + pipe, encoding "buffer", lines', testGeneratorAll, false, 'buffer', false, false, true, true, execa);163test('Can use generators with result.all = transform + pipe, encoding "hex", lines', testGeneratorAll, true, 'hex', false, false, true, true, execa);164test('Can use generators with error.all = transform + pipe, encoding "hex", lines', testGeneratorAll, false, 'hex', false, false, true, true, execa);165test('Can use generators with result.all = pipe + transform, lines', testGeneratorAll, true, 'utf8', false, true, false, true, execa);166test('Can use generators with error.all = pipe + transform, lines', testGeneratorAll, false, 'utf8', false, true, false, true, execa);167test('Can use generators with result.all = pipe + transform, encoding "buffer", lines', testGeneratorAll, true, 'buffer', false, true, false, true, execa);168test('Can use generators with error.all = pipe + transform, encoding "buffer", lines', testGeneratorAll, false, 'buffer', false, true, false, true, execa);169test('Can use generators with result.all = pipe + transform, encoding "hex", lines', testGeneratorAll, true, 'hex', false, true, false, true, execa);170test('Can use generators with error.all = pipe + transform, encoding "hex", lines', testGeneratorAll, false, 'hex', false, true, false, true, execa);171test('Can use generators with result.all = transform + transform, objectMode, lines', testGeneratorAll, true, 'utf8', true, false, false, true, execa);172test('Can use generators with error.all = transform + transform, objectMode, lines', testGeneratorAll, false, 'utf8', true, false, false, true, execa);173test('Can use generators with result.all = transform + transform, objectMode, encoding "buffer", lines', testGeneratorAll, true, 'buffer', true, false, false, true, execa);174test('Can use generators with error.all = transform + transform, objectMode, encoding "buffer", lines', testGeneratorAll, false, 'buffer', true, false, false, true, execa);175test('Can use generators with result.all = transform + transform, objectMode, encoding "hex", lines', testGeneratorAll, true, 'hex', true, false, false, true, execa);176test('Can use generators with error.all = transform + transform, objectMode, encoding "hex", lines', testGeneratorAll, false, 'hex', true, false, false, true, execa);177test('Can use generators with result.all = transform + pipe, objectMode, lines', testGeneratorAll, true, 'utf8', true, false, true, true, execa);178test('Can use generators with error.all = transform + pipe, objectMode, lines', testGeneratorAll, false, 'utf8', true, false, true, true, execa);179test('Can use generators with result.all = transform + pipe, objectMode, encoding "buffer", lines', testGeneratorAll, true, 'buffer', true, false, true, true, execa);180test('Can use generators with error.all = transform + pipe, objectMode, encoding "buffer", lines', testGeneratorAll, false, 'buffer', true, false, true, true, execa);181test('Can use generators with result.all = transform + pipe, objectMode, encoding "hex", lines', testGeneratorAll, true, 'hex', true, false, true, true, execa);182test('Can use generators with error.all = transform + pipe, objectMode, encoding "hex", lines', testGeneratorAll, false, 'hex', true, false, true, true, execa);183test('Can use generators with result.all = pipe + transform, objectMode, lines', testGeneratorAll, true, 'utf8', true, true, false, true, execa);184test('Can use generators with error.all = pipe + transform, objectMode, lines', testGeneratorAll, false, 'utf8', true, true, false, true, execa);185test('Can use generators with result.all = pipe + transform, objectMode, encoding "buffer", lines', testGeneratorAll, true, 'buffer', true, true, false, true, execa);186test('Can use generators with error.all = pipe + transform, objectMode, encoding "buffer", lines', testGeneratorAll, false, 'buffer', true, true, false, true, execa);187test('Can use generators with result.all = pipe + transform, objectMode, encoding "hex", lines', testGeneratorAll, true, 'hex', true, true, false, true, execa);188test('Can use generators with error.all = pipe + transform, objectMode, encoding "hex", lines', testGeneratorAll, false, 'hex', true, true, false, true, execa);189test('Can use generators with result.all = transform + transform, sync, lines', testGeneratorAll, true, 'utf8', false, false, false, true, execaSync);190test('Can use generators with error.all = transform + transform, sync, lines', testGeneratorAll, false, 'utf8', false, false, false, true, execaSync);191test('Can use generators with result.all = transform + transform, encoding "buffer", sync, lines', testGeneratorAll, true, 'buffer', false, false, false, true, execaSync);192test('Can use generators with error.all = transform + transform, encoding "buffer", sync, lines', testGeneratorAll, false, 'buffer', false, false, false, true, execaSync);193test('Can use generators with result.all = transform + transform, encoding "hex", sync, lines', testGeneratorAll, true, 'hex', false, false, false, true, execaSync);194test('Can use generators with error.all = transform + transform, encoding "hex", sync, lines', testGeneratorAll, false, 'hex', false, false, false, true, execaSync);195test('Can use generators with result.all = transform + pipe, sync, lines', testGeneratorAll, true, 'utf8', false, false, true, true, execaSync);196test('Can use generators with error.all = transform + pipe, sync, lines', testGeneratorAll, false, 'utf8', false, false, true, true, execaSync);197test('Can use generators with result.all = transform + pipe, encoding "buffer", sync, lines', testGeneratorAll, true, 'buffer', false, false, true, true, execaSync);198test('Can use generators with error.all = transform + pipe, encoding "buffer", sync, lines', testGeneratorAll, false, 'buffer', false, false, true, true, execaSync);199test('Can use generators with result.all = transform + pipe, encoding "hex", sync, lines', testGeneratorAll, true, 'hex', false, false, true, true, execaSync);200test('Can use generators with error.all = transform + pipe, encoding "hex", sync, lines', testGeneratorAll, false, 'hex', false, false, true, true, execaSync);201test('Can use generators with result.all = pipe + transform, sync, lines', testGeneratorAll, true, 'utf8', false, true, false, true, execaSync);202test('Can use generators with error.all = pipe + transform, sync, lines', testGeneratorAll, false, 'utf8', false, true, false, true, execaSync);203test('Can use generators with result.all = pipe + transform, encoding "buffer", sync, lines', testGeneratorAll, true, 'buffer', false, true, false, true, execaSync);204test('Can use generators with error.all = pipe + transform, encoding "buffer", sync, lines', testGeneratorAll, false, 'buffer', false, true, false, true, execaSync);205test('Can use generators with result.all = pipe + transform, encoding "hex", sync, lines', testGeneratorAll, true, 'hex', false, true, false, true, execaSync);206test('Can use generators with error.all = pipe + transform, encoding "hex", sync, lines', testGeneratorAll, false, 'hex', false, true, false, true, execaSync);207test('Can use generators with result.all = transform + transform, objectMode, sync, lines', testGeneratorAll, true, 'utf8', true, false, false, true, execaSync);208test('Can use generators with error.all = transform + transform, objectMode, sync, lines', testGeneratorAll, false, 'utf8', true, false, false, true, execaSync);209test('Can use generators with result.all = transform + transform, objectMode, encoding "buffer", sync, lines', testGeneratorAll, true, 'buffer', true, false, false, true, execaSync);210test('Can use generators with error.all = transform + transform, objectMode, encoding "buffer", sync, lines', testGeneratorAll, false, 'buffer', true, false, false, true, execaSync);211test('Can use generators with result.all = transform + transform, objectMode, encoding "hex", sync, lines', testGeneratorAll, true, 'hex', true, false, false, true, execaSync);212test('Can use generators with error.all = transform + transform, objectMode, encoding "hex", sync, lines', testGeneratorAll, false, 'hex', true, false, false, true, execaSync);213test('Can use generators with result.all = transform + pipe, objectMode, sync, lines', testGeneratorAll, true, 'utf8', true, false, true, true, execaSync);214test('Can use generators with error.all = transform + pipe, objectMode, sync, lines', testGeneratorAll, false, 'utf8', true, false, true, true, execaSync);215test('Can use generators with result.all = transform + pipe, objectMode, encoding "buffer", sync, lines', testGeneratorAll, true, 'buffer', true, false, true, true, execaSync);216test('Can use generators with error.all = transform + pipe, objectMode, encoding "buffer", sync, lines', testGeneratorAll, false, 'buffer', true, false, true, true, execaSync);217test('Can use generators with result.all = transform + pipe, objectMode, encoding "hex", sync, lines', testGeneratorAll, true, 'hex', true, false, true, true, execaSync);218test('Can use generators with error.all = transform + pipe, objectMode, encoding "hex", sync, lines', testGeneratorAll, false, 'hex', true, false, true, true, execaSync);219test('Can use generators with result.all = pipe + transform, objectMode, sync, lines', testGeneratorAll, true, 'utf8', true, true, false, true, execaSync);220test('Can use generators with error.all = pipe + transform, objectMode, sync, lines', testGeneratorAll, false, 'utf8', true, true, false, true, execaSync);221test('Can use generators with result.all = pipe + transform, objectMode, encoding "buffer", sync, lines', testGeneratorAll, true, 'buffer', true, true, false, true, execaSync);222test('Can use generators with error.all = pipe + transform, objectMode, encoding "buffer", sync, lines', testGeneratorAll, false, 'buffer', true, true, false, true, execaSync);223test('Can use generators with result.all = pipe + transform, objectMode, encoding "hex", sync, lines', testGeneratorAll, true, 'hex', true, true, false, true, execaSync);224test('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
1import {once} from 'node:events';2import test from 'ava';3import {execa, execaSync} from '../../index.js';4import {foobarString} from '../helpers/input.js';5import {noopGenerator, infiniteGenerator, convertTransformToFinal} from '../helpers/generator.js';6import {generatorsMap} from '../helpers/map.js';7import {setFixtureDir} from '../helpers/fixtures-dir.js';89setFixtureDir();1011const 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};2122const testThrowingGenerator = async (t, type, final, execaMethod) => {23 await assertProcessError(t, type, execaMethod, transform => execaMethod('noop.js', {24 stdout: convertTransformToFinal(transform, final),25 }));26};2728test('Generators "transform" errors make subprocess fail', testThrowingGenerator, 'generator', false, execa);29test('Generators "final" errors make subprocess fail', testThrowingGenerator, 'generator', true, execa);30test('Generators "transform" errors make subprocess fail, sync', testThrowingGenerator, 'generator', false, execaSync);31test('Generators "final" errors make subprocess fail, sync', testThrowingGenerator, 'generator', true, execaSync);32test('Duplexes "transform" errors make subprocess fail', testThrowingGenerator, 'duplex', false, execa);33test('WebTransform "transform" errors make subprocess fail', testThrowingGenerator, 'webTransform', false, execa);3435const 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};4445test('Generators errors make subprocess fail even when other output generators do not throw', testSingleErrorOutput, 'generator', execa);46test('Generators errors make subprocess fail even when other output generators do not throw, sync', testSingleErrorOutput, 'generator', execaSync);47test('Duplexes errors make subprocess fail even when other output generators do not throw', testSingleErrorOutput, 'duplex', execa);48test('WebTransform errors make subprocess fail even when other output generators do not throw', testSingleErrorOutput, 'webTransform', execa);4950const 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};6061test('Generators errors make subprocess fail even when other input generators do not throw', testSingleErrorInput, 'generator', execa);62test('Generators errors make subprocess fail even when other input generators do not throw, sync', testSingleErrorInput, 'generator', execaSync);63test('Duplexes errors make subprocess fail even when other input generators do not throw', testSingleErrorInput, 'duplex', execa);64test('WebTransform errors make subprocess fail even when other input generators do not throw', testSingleErrorInput, 'webTransform', execa);6566const 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};7273test('Running generators are canceled on subprocess abort', testGeneratorCancel, undefined);74test('Running generators are canceled on subprocess error', testGeneratorCancel, new Error('test'));7576const 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};8384test('Generators are destroyed on subprocess error, sync', testGeneratorDestroy, noopGenerator(false));85test('Generators are destroyed on subprocess error, async', testGeneratorDestroy, infiniteGenerator());8687test('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
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {foobarString} from '../helpers/input.js';4import {getOutputAsyncGenerator, getOutputGenerator, convertTransformToFinal} from '../helpers/generator.js';5import {setFixtureDir} from '../helpers/fixtures-dir.js';67setFixtureDir();89const testGeneratorFinal = async (t, fixtureName, execaMethod) => {10 const {stdout} = await execaMethod(fixtureName, {stdout: convertTransformToFinal(getOutputGenerator(foobarString)(), true)});11 t.is(stdout, foobarString);12};1314test('Generators "final" can be used', testGeneratorFinal, 'noop.js', execa);15test('Generators "final" is used even on empty streams', testGeneratorFinal, 'empty.js', execa);16test('Generators "final" can be used, sync', testGeneratorFinal, 'noop.js', execaSync);17test('Generators "final" is used even on empty streams, sync', testGeneratorFinal, 'empty.js', execaSync);1819const 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};2324test('Generators "final" can be used without "transform"', testFinalAlone, getOutputGenerator, execa);25test('Generators "final" can be used without "transform", sync', testFinalAlone, getOutputGenerator, execaSync);26test('Generators "final" can be used without "transform", async', testFinalAlone, getOutputAsyncGenerator, execa);2728const testFinalNoOutput = async (t, final, execaMethod) => {29 const {stdout} = await execaMethod('empty.js', {stdout: {final: final(foobarString)().transform}});30 t.is(stdout, foobarString);31};3233test('Generators "final" can be used without "transform" nor output', testFinalNoOutput, getOutputGenerator, execa);34test('Generators "final" can be used without "transform" nor output, sync', testFinalNoOutput, getOutputGenerator, execaSync);35test('Generators "final" can be used without "transform" nor output, async', testFinalNoOutput, getOutputAsyncGenerator, execa);
added:test/transform/generator-input.js+158 added
1import {Buffer} from 'node:buffer';2import test from 'ava';3import {execa, execaSync} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';5import {getStdio} from '../helpers/stdio.js';6import {7 foobarString,8 foobarUppercase,9 foobarHex,10 foobarUint8Array,11 foobarBuffer,12 foobarObject,13 foobarObjectString,14} from '../helpers/input.js';15import {generatorsMap} from '../helpers/map.js';1617setFixtureDir();1819const 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 };3031// eslint-disable-next-line max-params32const 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};3738test('Can use generators with result.stdin', testGeneratorInput, 0, false, false, 'generator', execa);39test('Can use generators with result.stdio[*] as input', testGeneratorInput, 3, false, false, 'generator', execa);40test('Can use generators with result.stdin, objectMode', testGeneratorInput, 0, true, false, 'generator', execa);41test('Can use generators with result.stdio[*] as input, objectMode', testGeneratorInput, 3, true, false, 'generator', execa);42test('Can use generators with result.stdin, noop transform', testGeneratorInput, 0, false, true, 'generator', execa);43test('Can use generators with result.stdio[*] as input, noop transform', testGeneratorInput, 3, false, true, 'generator', execa);44test('Can use generators with result.stdin, objectMode, noop transform', testGeneratorInput, 0, true, true, 'generator', execa);45test('Can use generators with result.stdio[*] as input, objectMode, noop transform', testGeneratorInput, 3, true, true, 'generator', execa);46test('Can use generators with result.stdin, sync', testGeneratorInput, 0, false, false, 'generator', execaSync);47test('Can use generators with result.stdin, objectMode, sync', testGeneratorInput, 0, true, false, 'generator', execaSync);48test('Can use generators with result.stdin, noop transform, sync', testGeneratorInput, 0, false, true, 'generator', execaSync);49test('Can use generators with result.stdin, objectMode, noop transform, sync', testGeneratorInput, 0, true, true, 'generator', execaSync);50test('Can use duplexes with result.stdin', testGeneratorInput, 0, false, false, 'duplex', execa);51test('Can use duplexes with result.stdio[*] as input', testGeneratorInput, 3, false, false, 'duplex', execa);52test('Can use duplexes with result.stdin, objectMode', testGeneratorInput, 0, true, false, 'duplex', execa);53test('Can use duplexes with result.stdio[*] as input, objectMode', testGeneratorInput, 3, true, false, 'duplex', execa);54test('Can use duplexes with result.stdin, noop transform', testGeneratorInput, 0, false, true, 'duplex', execa);55test('Can use duplexes with result.stdio[*] as input, noop transform', testGeneratorInput, 3, false, true, 'duplex', execa);56test('Can use duplexes with result.stdin, objectMode, noop transform', testGeneratorInput, 0, true, true, 'duplex', execa);57test('Can use duplexes with result.stdio[*] as input, objectMode, noop transform', testGeneratorInput, 3, true, true, 'duplex', execa);58test('Can use webTransforms with result.stdin', testGeneratorInput, 0, false, false, 'webTransform', execa);59test('Can use webTransforms with result.stdio[*] as input', testGeneratorInput, 3, false, false, 'webTransform', execa);60test('Can use webTransforms with result.stdin, objectMode', testGeneratorInput, 0, true, false, 'webTransform', execa);61test('Can use webTransforms with result.stdio[*] as input, objectMode', testGeneratorInput, 3, true, false, 'webTransform', execa);62test('Can use webTransforms with result.stdin, noop transform', testGeneratorInput, 0, false, true, 'webTransform', execa);63test('Can use webTransforms with result.stdio[*] as input, noop transform', testGeneratorInput, 3, false, true, 'webTransform', execa);64test('Can use webTransforms with result.stdin, objectMode, noop transform', testGeneratorInput, 0, true, true, 'webTransform', execa);65test('Can use webTransforms with result.stdio[*] as input, objectMode, noop transform', testGeneratorInput, 3, true, true, 'webTransform', execa);6667// eslint-disable-next-line max-params68const 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};7778test('Can use generators with subprocess.stdio[0] and default encoding', testGeneratorInputPipe, false, false, false, 'generator', [foobarString, 'utf8']);79test('Can use generators with subprocess.stdin and default encoding', testGeneratorInputPipe, true, false, false, 'generator', [foobarString, 'utf8']);80test('Can use generators with subprocess.stdio[0] and encoding "utf16le"', testGeneratorInputPipe, false, false, false, 'generator', [foobarString, 'utf16le']);81test('Can use generators with subprocess.stdin and encoding "utf16le"', testGeneratorInputPipe, true, false, false, 'generator', [foobarString, 'utf16le']);82test('Can use generators with subprocess.stdio[0] and encoding "buffer"', testGeneratorInputPipe, false, false, false, 'generator', [foobarBuffer, 'buffer']);83test('Can use generators with subprocess.stdin and encoding "buffer"', testGeneratorInputPipe, true, false, false, 'generator', [foobarBuffer, 'buffer']);84test('Can use generators with subprocess.stdio[0] and encoding "hex"', testGeneratorInputPipe, false, false, false, 'generator', [foobarHex, 'hex']);85test('Can use generators with subprocess.stdin and encoding "hex"', testGeneratorInputPipe, true, false, false, 'generator', [foobarHex, 'hex']);86test('Can use generators with subprocess.stdio[0], objectMode', testGeneratorInputPipe, false, true, false, 'generator', [foobarObject]);87test('Can use generators with subprocess.stdin, objectMode', testGeneratorInputPipe, true, true, false, 'generator', [foobarObject]);88test('Can use generators with subprocess.stdio[0] and default encoding, noop transform', testGeneratorInputPipe, false, false, true, 'generator', [foobarString, 'utf8']);89test('Can use generators with subprocess.stdin and default encoding, noop transform', testGeneratorInputPipe, true, false, true, 'generator', [foobarString, 'utf8']);90test('Can use generators with subprocess.stdio[0] and encoding "utf16le", noop transform', testGeneratorInputPipe, false, false, true, 'generator', [foobarString, 'utf16le']);91test('Can use generators with subprocess.stdin and encoding "utf16le", noop transform', testGeneratorInputPipe, true, false, true, 'generator', [foobarString, 'utf16le']);92test('Can use generators with subprocess.stdio[0] and encoding "buffer", noop transform', testGeneratorInputPipe, false, false, true, 'generator', [foobarBuffer, 'buffer']);93test('Can use generators with subprocess.stdin and encoding "buffer", noop transform', testGeneratorInputPipe, true, false, true, 'generator', [foobarBuffer, 'buffer']);94test('Can use generators with subprocess.stdio[0] and encoding "hex", noop transform', testGeneratorInputPipe, false, false, true, 'generator', [foobarHex, 'hex']);95test('Can use generators with subprocess.stdin and encoding "hex", noop transform', testGeneratorInputPipe, true, false, true, 'generator', [foobarHex, 'hex']);96test('Can use generators with subprocess.stdio[0], objectMode, noop transform', testGeneratorInputPipe, false, true, true, 'generator', [foobarObject]);97test('Can use generators with subprocess.stdin, objectMode, noop transform', testGeneratorInputPipe, true, true, true, 'generator', [foobarObject]);98test('Can use duplexes with subprocess.stdio[0] and default encoding', testGeneratorInputPipe, false, false, false, 'duplex', [foobarString, 'utf8']);99test('Can use duplexes with subprocess.stdin and default encoding', testGeneratorInputPipe, true, false, false, 'duplex', [foobarString, 'utf8']);100test('Can use duplexes with subprocess.stdio[0] and encoding "utf16le"', testGeneratorInputPipe, false, false, false, 'duplex', [foobarString, 'utf16le']);101test('Can use duplexes with subprocess.stdin and encoding "utf16le"', testGeneratorInputPipe, true, false, false, 'duplex', [foobarString, 'utf16le']);102test('Can use duplexes with subprocess.stdio[0] and encoding "buffer"', testGeneratorInputPipe, false, false, false, 'duplex', [foobarBuffer, 'buffer']);103test('Can use duplexes with subprocess.stdin and encoding "buffer"', testGeneratorInputPipe, true, false, false, 'duplex', [foobarBuffer, 'buffer']);104test('Can use duplexes with subprocess.stdio[0] and encoding "hex"', testGeneratorInputPipe, false, false, false, 'duplex', [foobarHex, 'hex']);105test('Can use duplexes with subprocess.stdin and encoding "hex"', testGeneratorInputPipe, true, false, false, 'duplex', [foobarHex, 'hex']);106test('Can use duplexes with subprocess.stdio[0], objectMode', testGeneratorInputPipe, false, true, false, 'duplex', [foobarObject]);107test('Can use duplexes with subprocess.stdin, objectMode', testGeneratorInputPipe, true, true, false, 'duplex', [foobarObject]);108test('Can use duplexes with subprocess.stdio[0] and default encoding, noop transform', testGeneratorInputPipe, false, false, true, 'duplex', [foobarString, 'utf8']);109test('Can use duplexes with subprocess.stdin and default encoding, noop transform', testGeneratorInputPipe, true, false, true, 'duplex', [foobarString, 'utf8']);110test('Can use duplexes with subprocess.stdio[0] and encoding "utf16le", noop transform', testGeneratorInputPipe, false, false, true, 'duplex', [foobarString, 'utf16le']);111test('Can use duplexes with subprocess.stdin and encoding "utf16le", noop transform', testGeneratorInputPipe, true, false, true, 'duplex', [foobarString, 'utf16le']);112test('Can use duplexes with subprocess.stdio[0] and encoding "buffer", noop transform', testGeneratorInputPipe, false, false, true, 'duplex', [foobarBuffer, 'buffer']);113test('Can use duplexes with subprocess.stdin and encoding "buffer", noop transform', testGeneratorInputPipe, true, false, true, 'duplex', [foobarBuffer, 'buffer']);114test('Can use duplexes with subprocess.stdio[0] and encoding "hex", noop transform', testGeneratorInputPipe, false, false, true, 'duplex', [foobarHex, 'hex']);115test('Can use duplexes with subprocess.stdin and encoding "hex", noop transform', testGeneratorInputPipe, true, false, true, 'duplex', [foobarHex, 'hex']);116test('Can use duplexes with subprocess.stdio[0], objectMode, noop transform', testGeneratorInputPipe, false, true, true, 'duplex', [foobarObject]);117test('Can use duplexes with subprocess.stdin, objectMode, noop transform', testGeneratorInputPipe, true, true, true, 'duplex', [foobarObject]);118test('Can use webTransforms with subprocess.stdio[0] and default encoding', testGeneratorInputPipe, false, false, false, 'webTransform', [foobarString, 'utf8']);119test('Can use webTransforms with subprocess.stdin and default encoding', testGeneratorInputPipe, true, false, false, 'webTransform', [foobarString, 'utf8']);120test('Can use webTransforms with subprocess.stdio[0] and encoding "utf16le"', testGeneratorInputPipe, false, false, false, 'webTransform', [foobarString, 'utf16le']);121test('Can use webTransforms with subprocess.stdin and encoding "utf16le"', testGeneratorInputPipe, true, false, false, 'webTransform', [foobarString, 'utf16le']);122test('Can use webTransforms with subprocess.stdio[0] and encoding "buffer"', testGeneratorInputPipe, false, false, false, 'webTransform', [foobarBuffer, 'buffer']);123test('Can use webTransforms with subprocess.stdin and encoding "buffer"', testGeneratorInputPipe, true, false, false, 'webTransform', [foobarBuffer, 'buffer']);124test('Can use webTransforms with subprocess.stdio[0] and encoding "hex"', testGeneratorInputPipe, false, false, false, 'webTransform', [foobarHex, 'hex']);125test('Can use webTransforms with subprocess.stdin and encoding "hex"', testGeneratorInputPipe, true, false, false, 'webTransform', [foobarHex, 'hex']);126test('Can use webTransforms with subprocess.stdio[0], objectMode', testGeneratorInputPipe, false, true, false, 'webTransform', [foobarObject]);127test('Can use webTransforms with subprocess.stdin, objectMode', testGeneratorInputPipe, true, true, false, 'webTransform', [foobarObject]);128test('Can use webTransforms with subprocess.stdio[0] and default encoding, noop transform', testGeneratorInputPipe, false, false, true, 'webTransform', [foobarString, 'utf8']);129test('Can use webTransforms with subprocess.stdin and default encoding, noop transform', testGeneratorInputPipe, true, false, true, 'webTransform', [foobarString, 'utf8']);130test('Can use webTransforms with subprocess.stdio[0] and encoding "utf16le", noop transform', testGeneratorInputPipe, false, false, true, 'webTransform', [foobarString, 'utf16le']);131test('Can use webTransforms with subprocess.stdin and encoding "utf16le", noop transform', testGeneratorInputPipe, true, false, true, 'webTransform', [foobarString, 'utf16le']);132test('Can use webTransforms with subprocess.stdio[0] and encoding "buffer", noop transform', testGeneratorInputPipe, false, false, true, 'webTransform', [foobarBuffer, 'buffer']);133test('Can use webTransforms with subprocess.stdin and encoding "buffer", noop transform', testGeneratorInputPipe, true, false, true, 'webTransform', [foobarBuffer, 'buffer']);134test('Can use webTransforms with subprocess.stdio[0] and encoding "hex", noop transform', testGeneratorInputPipe, false, false, true, 'webTransform', [foobarHex, 'hex']);135test('Can use webTransforms with subprocess.stdin and encoding "hex", noop transform', testGeneratorInputPipe, true, false, true, 'webTransform', [foobarHex, 'hex']);136test('Can use webTransforms with subprocess.stdio[0], objectMode, noop transform', testGeneratorInputPipe, false, true, true, 'webTransform', [foobarObject]);137test('Can use webTransforms with subprocess.stdin, objectMode, noop transform', testGeneratorInputPipe, true, true, true, 'webTransform', [foobarObject]);138139const 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};146147test('Can use generators with subprocess.stdio[*] as input', testGeneratorStdioInputPipe, false, false, 'generator');148test('Can use generators with subprocess.stdio[*] as input, objectMode', testGeneratorStdioInputPipe, true, false, 'generator');149test('Can use generators with subprocess.stdio[*] as input, noop transform', testGeneratorStdioInputPipe, false, true, 'generator');150test('Can use generators with subprocess.stdio[*] as input, objectMode, noop transform', testGeneratorStdioInputPipe, true, true, 'generator');151test('Can use duplexes with subprocess.stdio[*] as input', testGeneratorStdioInputPipe, false, false, 'duplex');152test('Can use duplexes with subprocess.stdio[*] as input, objectMode', testGeneratorStdioInputPipe, true, false, 'duplex');153test('Can use duplexes with subprocess.stdio[*] as input, noop transform', testGeneratorStdioInputPipe, false, true, 'duplex');154test('Can use duplexes with subprocess.stdio[*] as input, objectMode, noop transform', testGeneratorStdioInputPipe, true, true, 'duplex');155test('Can use webTransforms with subprocess.stdio[*] as input', testGeneratorStdioInputPipe, false, false, 'webTransform');156test('Can use webTransforms with subprocess.stdio[*] as input, objectMode', testGeneratorStdioInputPipe, true, false, 'webTransform');157test('Can use webTransforms with subprocess.stdio[*] as input, noop transform', testGeneratorStdioInputPipe, false, true, 'webTransform');158test('Can use webTransforms with subprocess.stdio[*] as input, objectMode, noop transform', testGeneratorStdioInputPipe, true, true, 'webTransform');
added:test/transform/generator-main.js+185 added
1import {Buffer} from 'node:buffer';2import {scheduler} from 'node:timers/promises';3import test from 'ava';4import {getStreamAsArray} from 'get-stream';5import {execa, execaSync} from '../../index.js';6import {foobarString} from '../helpers/input.js';7import {8 noopGenerator,9 outputObjectGenerator,10 convertTransformToFinal,11 prefix,12 suffix,13} from '../helpers/generator.js';14import {generatorsMap} from '../helpers/map.js';15import {defaultHighWaterMark} from '../helpers/stream.js';16import {setFixtureDir} from '../helpers/fixtures-dir.js';17import {maxBuffer, assertErrorMessage} from '../helpers/max-buffer.js';1819setFixtureDir();2021const repeatCount = defaultHighWaterMark * 3;2223const writerGenerator = function * () {24 for (let index = 0; index < repeatCount; index += 1) {25 yield '\n';26 }27};2829const getLengthGenerator = function * (t, chunk) {30 t.is(chunk.length, 1);31 yield chunk;32};3334// eslint-disable-next-line max-params35const 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};4748test('Synchronous yields are not buffered, no passThrough', testHighWaterMark, false, false, false, execa);49test('Synchronous yields are not buffered, line-wise passThrough', testHighWaterMark, true, false, false, execa);50test('Synchronous yields are not buffered, binary passThrough', testHighWaterMark, true, true, false, execa);51test('Synchronous yields are not buffered, objectMode as input but not output', testHighWaterMark, false, false, true, execa);52test('Synchronous yields are not buffered, no passThrough, sync', testHighWaterMark, false, false, false, execaSync);53test('Synchronous yields are not buffered, line-wise passThrough, sync', testHighWaterMark, true, false, false, execaSync);54test('Synchronous yields are not buffered, binary passThrough, sync', testHighWaterMark, true, true, false, execaSync);55test('Synchronous yields are not buffered, objectMode as input but not output, sync', testHighWaterMark, false, false, true, execaSync);5657// eslint-disable-next-line max-params58const 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};6263test('Generator can filter "transform" by not calling yield', testNoYield, 'generator', false, false, '', execa);64test('Generator can filter "transform" by not calling yield, objectMode', testNoYield, 'generator', true, false, [], execa);65test('Generator can filter "final" by not calling yield', testNoYield, 'generator', false, true, '', execa);66test('Generator can filter "final" by not calling yield, objectMode', testNoYield, 'generator', true, true, [], execa);67test('Generator can filter "transform" by not calling yield, sync', testNoYield, 'generator', false, false, '', execaSync);68test('Generator can filter "transform" by not calling yield, objectMode, sync', testNoYield, 'generator', true, false, [], execaSync);69test('Generator can filter "final" by not calling yield, sync', testNoYield, 'generator', false, true, '', execaSync);70test('Generator can filter "final" by not calling yield, objectMode, sync', testNoYield, 'generator', true, true, [], execaSync);71test('Duplex can filter by not calling push', testNoYield, 'duplex', false, false, '', execa);72test('Duplex can filter by not calling push, objectMode', testNoYield, 'duplex', true, false, [], execa);73test('WebTransform can filter by not calling push', testNoYield, 'webTransform', false, false, '', execa);74test('WebTransform can filter by not calling push, objectMode', testNoYield, 'webTransform', true, false, [], execa);7576const 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};8182test('Generator can yield "transform" multiple times at different moments', testMultipleYields, 'generator', false, false);83test('Generator can yield "final" multiple times at different moments', testMultipleYields, 'generator', true, false);84test('Duplex can push multiple times at different moments', testMultipleYields, 'duplex', false, true);85test('WebTransform can push multiple times at different moments', testMultipleYields, 'webTransform', false, true);8687const partsPerChunk = 4;88const chunksPerCall = 10;89const callCount = 5;90const fullString = '\n'.repeat(defaultHighWaterMark / partsPerChunk);9192const yieldFullStrings = function * () {93 yield * Array.from({length: partsPerChunk * chunksPerCall}).fill(fullString);94};9596const 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};103104const 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};111112test('Generator "transform" yields are sent right away', testManyYields, false);113test('Generator "final" yields are sent right away', testManyYields, true);114115const 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);122123 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};130131test('Generators take "maxBuffer" into account', testMaxBuffer, 'generator');132test('Duplexes take "maxBuffer" into account', testMaxBuffer, 'duplex');133test('WebTransforms take "maxBuffer" into account', testMaxBuffer, 'webTransform');134135test('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});144145const 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);152153 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};160161test('Generators take "maxBuffer" into account, objectMode', testMaxBufferObject, 'generator');162test('Duplexes take "maxBuffer" into account, objectMode', testMaxBufferObject, 'duplex');163test('WebTransforms take "maxBuffer" into account, objectMode', testMaxBufferObject, 'webTransform');164165test('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});174175const 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};181182test('Generators "transform" is awaited on success', testAsyncGenerators, 'generator', false);183test('Generators "final" is awaited on success', testAsyncGenerators, 'generator', true);184test('Duplex is awaited on success', testAsyncGenerators, 'duplex', false);185test('WebTransform is awaited on success', testAsyncGenerators, 'webTransform', false);
added:test/transform/generator-mixed.js+104 added
1import {readFile, writeFile, rm} from 'node:fs/promises';2import {PassThrough} from 'node:stream';3import test from 'ava';4import getStream from 'get-stream';5import tempfile from 'tempfile';6import {execa, execaSync} from '../../index.js';7import {setFixtureDir} from '../helpers/fixtures-dir.js';8import {foobarString, foobarUppercase, foobarUint8Array} from '../helpers/input.js';9import {uppercaseGenerator} from '../helpers/generator.js';10import {uppercaseBufferDuplex} from '../helpers/duplex.js';11import {uppercaseBufferWebTransform} from '../helpers/web-transform.js';12import {generatorsMap} from '../helpers/map.js';1314setFixtureDir();1516const 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};2021test('Can use generators with input option', testInputOption, 'generator', execa);22test('Can use generators with input option, sync', testInputOption, 'generator', execaSync);23test('Can use duplexes with input option', testInputOption, 'duplex', execa);24test('Can use webTransforms with input option', testInputOption, 'webTransform', execa);2526// eslint-disable-next-line max-params27const 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};3839test('Can use generators with a file as input', testInputFile, uppercaseGenerator(), false, false, execa);40test('Can use generators with a file as input, reversed', testInputFile, uppercaseGenerator(), false, true, execa);41test('Can use generators with inputFile option', testInputFile, uppercaseGenerator(), true, false, execa);42test('Can use generators with a file as input, sync', testInputFile, uppercaseGenerator(), false, false, execaSync);43test('Can use generators with a file as input, reversed, sync', testInputFile, uppercaseGenerator(), false, true, execaSync);44test('Can use generators with inputFile option, sync', testInputFile, uppercaseGenerator(), true, false, execaSync);45test('Can use duplexes with a file as input', testInputFile, uppercaseBufferDuplex(), false, false, execa);46test('Can use duplexes with a file as input, reversed', testInputFile, uppercaseBufferDuplex(), false, true, execa);47test('Can use duplexes with inputFile option', testInputFile, uppercaseBufferDuplex(), true, false, execa);48test('Can use webTransforms with a file as input', testInputFile, uppercaseBufferWebTransform(), false, false, execa);49test('Can use webTransforms with a file as input, reversed', testInputFile, uppercaseBufferWebTransform(), false, true, execa);50test('Can use webTransforms with inputFile option', testInputFile, uppercaseBufferWebTransform(), true, false, execa);5152const 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};6162test('Can use generators with a file as output', testOutputFile, false, 'generator', execa);63test('Can use generators with a file as output, reversed', testOutputFile, true, 'generator', execa);64test('Can use generators with a file as output, sync', testOutputFile, false, 'generator', execaSync);65test('Can use generators with a file as output, reversed, sync', testOutputFile, true, 'generator', execaSync);66test('Can use duplexes with a file as output', testOutputFile, false, 'duplex', execa);67test('Can use duplexes with a file as output, reversed', testOutputFile, true, 'duplex', execa);68test('Can use webTransforms with a file as output', testOutputFile, false, 'webTransform', execa);69test('Can use webTransforms with a file as output, reversed', testOutputFile, true, 'webTransform', execa);7071const 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};8081test('Can use generators to a Writable stream', testWritableDestination, 'generator');82test('Can use duplexes to a Writable stream', testWritableDestination, 'duplex');83test('Can use webTransforms to a Writable stream', testWritableDestination, 'webTransform');8485const 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};9293test('Can use generators from a Readable stream', testReadableSource, 'generator');94test('Can use duplexes from a Readable stream', testReadableSource, 'duplex');95test('Can use webTransforms from a Readable stream', testReadableSource, 'webTransform');9697const testInherit = async (t, type) => {98 const {stdout} = await execa('nested-inherit.js', [type]);99 t.is(stdout, foobarUppercase);100};101102test('Can use generators with "inherit"', testInherit, 'generator');103test('Can use duplexes with "inherit"', testInherit, 'duplex');104test('Can use webTransforms with "inherit"', testInherit, 'webTransform');
added:test/transform/generator-output.js+261 added
1import test from 'ava';2import getStream, {getStreamAsArray} from 'get-stream';3import {execa, execaSync} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';5import {getStdio} from '../helpers/stdio.js';6import {foobarString, foobarUppercase, foobarObject} from '../helpers/input.js';7import {generatorsMap} from '../helpers/map.js';89setFixtureDir();1011const 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 };2223// eslint-disable-next-line max-params24const 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};3132test('Can use generators with result.stdio[1]', testGeneratorOutput, 1, true, false, false, false, 'generator', execa);33test('Can use generators with result.stdout', testGeneratorOutput, 1, true, true, false, false, 'generator', execa);34test('Can use generators with result.stdio[2]', testGeneratorOutput, 2, true, false, false, false, 'generator', execa);35test('Can use generators with result.stderr', testGeneratorOutput, 2, true, true, false, false, 'generator', execa);36test('Can use generators with result.stdio[*] as output', testGeneratorOutput, 3, true, false, false, false, 'generator', execa);37test('Can use generators with error.stdio[1]', testGeneratorOutput, 1, false, false, false, false, 'generator', execa);38test('Can use generators with error.stdout', testGeneratorOutput, 1, false, true, false, false, 'generator', execa);39test('Can use generators with error.stdio[2]', testGeneratorOutput, 2, false, false, false, false, 'generator', execa);40test('Can use generators with error.stderr', testGeneratorOutput, 2, false, true, false, false, 'generator', execa);41test('Can use generators with error.stdio[*] as output', testGeneratorOutput, 3, false, false, false, false, 'generator', execa);42test('Can use generators with result.stdio[1], objectMode', testGeneratorOutput, 1, true, false, true, false, 'generator', execa);43test('Can use generators with result.stdout, objectMode', testGeneratorOutput, 1, true, true, true, false, 'generator', execa);44test('Can use generators with result.stdio[2], objectMode', testGeneratorOutput, 2, true, false, true, false, 'generator', execa);45test('Can use generators with result.stderr, objectMode', testGeneratorOutput, 2, true, true, true, false, 'generator', execa);46test('Can use generators with result.stdio[*] as output, objectMode', testGeneratorOutput, 3, true, false, true, false, 'generator', execa);47test('Can use generators with error.stdio[1], objectMode', testGeneratorOutput, 1, false, false, true, false, 'generator', execa);48test('Can use generators with error.stdout, objectMode', testGeneratorOutput, 1, false, true, true, false, 'generator', execa);49test('Can use generators with error.stdio[2], objectMode', testGeneratorOutput, 2, false, false, true, false, 'generator', execa);50test('Can use generators with error.stderr, objectMode', testGeneratorOutput, 2, false, true, true, false, 'generator', execa);51test('Can use generators with error.stdio[*] as output, objectMode', testGeneratorOutput, 3, false, false, true, false, 'generator', execa);52test('Can use generators with result.stdio[1], noop transform', testGeneratorOutput, 1, true, false, false, true, 'generator', execa);53test('Can use generators with result.stdout, noop transform', testGeneratorOutput, 1, true, true, false, true, 'generator', execa);54test('Can use generators with result.stdio[2], noop transform', testGeneratorOutput, 2, true, false, false, true, 'generator', execa);55test('Can use generators with result.stderr, noop transform', testGeneratorOutput, 2, true, true, false, true, 'generator', execa);56test('Can use generators with result.stdio[*] as output, noop transform', testGeneratorOutput, 3, true, false, false, true, 'generator', execa);57test('Can use generators with error.stdio[1], noop transform', testGeneratorOutput, 1, false, false, false, true, 'generator', execa);58test('Can use generators with error.stdout, noop transform', testGeneratorOutput, 1, false, true, false, true, 'generator', execa);59test('Can use generators with error.stdio[2], noop transform', testGeneratorOutput, 2, false, false, false, true, 'generator', execa);60test('Can use generators with error.stderr, noop transform', testGeneratorOutput, 2, false, true, false, true, 'generator', execa);61test('Can use generators with error.stdio[*] as output, noop transform', testGeneratorOutput, 3, false, false, false, true, 'generator', execa);62test('Can use generators with result.stdio[1], objectMode, noop transform', testGeneratorOutput, 1, true, false, true, true, 'generator', execa);63test('Can use generators with result.stdout, objectMode, noop transform', testGeneratorOutput, 1, true, true, true, true, 'generator', execa);64test('Can use generators with result.stdio[2], objectMode, noop transform', testGeneratorOutput, 2, true, false, true, true, 'generator', execa);65test('Can use generators with result.stderr, objectMode, noop transform', testGeneratorOutput, 2, true, true, true, true, 'generator', execa);66test('Can use generators with result.stdio[*] as output, objectMode, noop transform', testGeneratorOutput, 3, true, false, true, true, 'generator', execa);67test('Can use generators with error.stdio[1], objectMode, noop transform', testGeneratorOutput, 1, false, false, true, true, 'generator', execa);68test('Can use generators with error.stdout, objectMode, noop transform', testGeneratorOutput, 1, false, true, true, true, 'generator', execa);69test('Can use generators with error.stdio[2], objectMode, noop transform', testGeneratorOutput, 2, false, false, true, true, 'generator', execa);70test('Can use generators with error.stderr, objectMode, noop transform', testGeneratorOutput, 2, false, true, true, true, 'generator', execa);71test('Can use generators with error.stdio[*] as output, objectMode, noop transform', testGeneratorOutput, 3, false, false, true, true, 'generator', execa);72test('Can use generators with result.stdio[1], sync', testGeneratorOutput, 1, true, false, false, false, 'generator', execaSync);73test('Can use generators with result.stdout, sync', testGeneratorOutput, 1, true, true, false, false, 'generator', execaSync);74test('Can use generators with result.stdio[2], sync', testGeneratorOutput, 2, true, false, false, false, 'generator', execaSync);75test('Can use generators with result.stderr, sync', testGeneratorOutput, 2, true, true, false, false, 'generator', execaSync);76test('Can use generators with result.stdio[*] as output, sync', testGeneratorOutput, 3, true, false, false, false, 'generator', execaSync);77test('Can use generators with error.stdio[1], sync', testGeneratorOutput, 1, false, false, false, false, 'generator', execaSync);78test('Can use generators with error.stdout, sync', testGeneratorOutput, 1, false, true, false, false, 'generator', execaSync);79test('Can use generators with error.stdio[2], sync', testGeneratorOutput, 2, false, false, false, false, 'generator', execaSync);80test('Can use generators with error.stderr, sync', testGeneratorOutput, 2, false, true, false, false, 'generator', execaSync);81test('Can use generators with error.stdio[*] as output, sync', testGeneratorOutput, 3, false, false, false, false, 'generator', execaSync);82test('Can use generators with result.stdio[1], objectMode, sync', testGeneratorOutput, 1, true, false, true, false, 'generator', execaSync);83test('Can use generators with result.stdout, objectMode, sync', testGeneratorOutput, 1, true, true, true, false, 'generator', execaSync);84test('Can use generators with result.stdio[2], objectMode, sync', testGeneratorOutput, 2, true, false, true, false, 'generator', execaSync);85test('Can use generators with result.stderr, objectMode, sync', testGeneratorOutput, 2, true, true, true, false, 'generator', execaSync);86test('Can use generators with result.stdio[*] as output, objectMode, sync', testGeneratorOutput, 3, true, false, true, false, 'generator', execaSync);87test('Can use generators with error.stdio[1], objectMode, sync', testGeneratorOutput, 1, false, false, true, false, 'generator', execaSync);88test('Can use generators with error.stdout, objectMode, sync', testGeneratorOutput, 1, false, true, true, false, 'generator', execaSync);89test('Can use generators with error.stdio[2], objectMode, sync', testGeneratorOutput, 2, false, false, true, false, 'generator', execaSync);90test('Can use generators with error.stderr, objectMode, sync', testGeneratorOutput, 2, false, true, true, false, 'generator', execaSync);91test('Can use generators with error.stdio[*] as output, objectMode, sync', testGeneratorOutput, 3, false, false, true, false, 'generator', execaSync);92test('Can use generators with result.stdio[1], noop transform, sync', testGeneratorOutput, 1, true, false, false, true, 'generator', execaSync);93test('Can use generators with result.stdout, noop transform, sync', testGeneratorOutput, 1, true, true, false, true, 'generator', execaSync);94test('Can use generators with result.stdio[2], noop transform, sync', testGeneratorOutput, 2, true, false, false, true, 'generator', execaSync);95test('Can use generators with result.stderr, noop transform, sync', testGeneratorOutput, 2, true, true, false, true, 'generator', execaSync);96test('Can use generators with result.stdio[*] as output, noop transform, sync', testGeneratorOutput, 3, true, false, false, true, 'generator', execaSync);97test('Can use generators with error.stdio[1], noop transform, sync', testGeneratorOutput, 1, false, false, false, true, 'generator', execaSync);98test('Can use generators with error.stdout, noop transform, sync', testGeneratorOutput, 1, false, true, false, true, 'generator', execaSync);99test('Can use generators with error.stdio[2], noop transform, sync', testGeneratorOutput, 2, false, false, false, true, 'generator', execaSync);100test('Can use generators with error.stderr, noop transform, sync', testGeneratorOutput, 2, false, true, false, true, 'generator', execaSync);101test('Can use generators with error.stdio[*] as output, noop transform, sync', testGeneratorOutput, 3, false, false, false, true, 'generator', execaSync);102test('Can use generators with result.stdio[1], objectMode, noop transform, sync', testGeneratorOutput, 1, true, false, true, true, 'generator', execaSync);103test('Can use generators with result.stdout, objectMode, noop transform, sync', testGeneratorOutput, 1, true, true, true, true, 'generator', execaSync);104test('Can use generators with result.stdio[2], objectMode, noop transform, sync', testGeneratorOutput, 2, true, false, true, true, 'generator', execaSync);105test('Can use generators with result.stderr, objectMode, noop transform, sync', testGeneratorOutput, 2, true, true, true, true, 'generator', execaSync);106test('Can use generators with result.stdio[*] as output, objectMode, noop transform, sync', testGeneratorOutput, 3, true, false, true, true, 'generator', execaSync);107test('Can use generators with error.stdio[1], objectMode, noop transform, sync', testGeneratorOutput, 1, false, false, true, true, 'generator', execaSync);108test('Can use generators with error.stdout, objectMode, noop transform, sync', testGeneratorOutput, 1, false, true, true, true, 'generator', execaSync);109test('Can use generators with error.stdio[2], objectMode, noop transform, sync', testGeneratorOutput, 2, false, false, true, true, 'generator', execaSync);110test('Can use generators with error.stderr, objectMode, noop transform, sync', testGeneratorOutput, 2, false, true, true, true, 'generator', execaSync);111test('Can use generators with error.stdio[*] as output, objectMode, noop transform, sync', testGeneratorOutput, 3, false, false, true, true, 'generator', execaSync);112test('Can use duplexes with result.stdio[1]', testGeneratorOutput, 1, true, false, false, false, 'duplex', execa);113test('Can use duplexes with result.stdout', testGeneratorOutput, 1, true, true, false, false, 'duplex', execa);114test('Can use duplexes with result.stdio[2]', testGeneratorOutput, 2, true, false, false, false, 'duplex', execa);115test('Can use duplexes with result.stderr', testGeneratorOutput, 2, true, true, false, false, 'duplex', execa);116test('Can use duplexes with result.stdio[*] as output', testGeneratorOutput, 3, true, false, false, false, 'duplex', execa);117test('Can use duplexes with error.stdio[1]', testGeneratorOutput, 1, false, false, false, false, 'duplex', execa);118test('Can use duplexes with error.stdout', testGeneratorOutput, 1, false, true, false, false, 'duplex', execa);119test('Can use duplexes with error.stdio[2]', testGeneratorOutput, 2, false, false, false, false, 'duplex', execa);120test('Can use duplexes with error.stderr', testGeneratorOutput, 2, false, true, false, false, 'duplex', execa);121test('Can use duplexes with error.stdio[*] as output', testGeneratorOutput, 3, false, false, false, false, 'duplex', execa);122test('Can use duplexes with result.stdio[1], objectMode', testGeneratorOutput, 1, true, false, true, false, 'duplex', execa);123test('Can use duplexes with result.stdout, objectMode', testGeneratorOutput, 1, true, true, true, false, 'duplex', execa);124test('Can use duplexes with result.stdio[2], objectMode', testGeneratorOutput, 2, true, false, true, false, 'duplex', execa);125test('Can use duplexes with result.stderr, objectMode', testGeneratorOutput, 2, true, true, true, false, 'duplex', execa);126test('Can use duplexes with result.stdio[*] as output, objectMode', testGeneratorOutput, 3, true, false, true, false, 'duplex', execa);127test('Can use duplexes with error.stdio[1], objectMode', testGeneratorOutput, 1, false, false, true, false, 'duplex', execa);128test('Can use duplexes with error.stdout, objectMode', testGeneratorOutput, 1, false, true, true, false, 'duplex', execa);129test('Can use duplexes with error.stdio[2], objectMode', testGeneratorOutput, 2, false, false, true, false, 'duplex', execa);130test('Can use duplexes with error.stderr, objectMode', testGeneratorOutput, 2, false, true, true, false, 'duplex', execa);131test('Can use duplexes with error.stdio[*] as output, objectMode', testGeneratorOutput, 3, false, false, true, false, 'duplex', execa);132test('Can use duplexes with result.stdio[1], noop transform', testGeneratorOutput, 1, true, false, false, true, 'duplex', execa);133test('Can use duplexes with result.stdout, noop transform', testGeneratorOutput, 1, true, true, false, true, 'duplex', execa);134test('Can use duplexes with result.stdio[2], noop transform', testGeneratorOutput, 2, true, false, false, true, 'duplex', execa);135test('Can use duplexes with result.stderr, noop transform', testGeneratorOutput, 2, true, true, false, true, 'duplex', execa);136test('Can use duplexes with result.stdio[*] as output, noop transform', testGeneratorOutput, 3, true, false, false, true, 'duplex', execa);137test('Can use duplexes with error.stdio[1], noop transform', testGeneratorOutput, 1, false, false, false, true, 'duplex', execa);138test('Can use duplexes with error.stdout, noop transform', testGeneratorOutput, 1, false, true, false, true, 'duplex', execa);139test('Can use duplexes with error.stdio[2], noop transform', testGeneratorOutput, 2, false, false, false, true, 'duplex', execa);140test('Can use duplexes with error.stderr, noop transform', testGeneratorOutput, 2, false, true, false, true, 'duplex', execa);141test('Can use duplexes with error.stdio[*] as output, noop transform', testGeneratorOutput, 3, false, false, false, true, 'duplex', execa);142test('Can use duplexes with result.stdio[1], objectMode, noop transform', testGeneratorOutput, 1, true, false, true, true, 'duplex', execa);143test('Can use duplexes with result.stdout, objectMode, noop transform', testGeneratorOutput, 1, true, true, true, true, 'duplex', execa);144test('Can use duplexes with result.stdio[2], objectMode, noop transform', testGeneratorOutput, 2, true, false, true, true, 'duplex', execa);145test('Can use duplexes with result.stderr, objectMode, noop transform', testGeneratorOutput, 2, true, true, true, true, 'duplex', execa);146test('Can use duplexes with result.stdio[*] as output, objectMode, noop transform', testGeneratorOutput, 3, true, false, true, true, 'duplex', execa);147test('Can use duplexes with error.stdio[1], objectMode, noop transform', testGeneratorOutput, 1, false, false, true, true, 'duplex', execa);148test('Can use duplexes with error.stdout, objectMode, noop transform', testGeneratorOutput, 1, false, true, true, true, 'duplex', execa);149test('Can use duplexes with error.stdio[2], objectMode, noop transform', testGeneratorOutput, 2, false, false, true, true, 'duplex', execa);150test('Can use duplexes with error.stderr, objectMode, noop transform', testGeneratorOutput, 2, false, true, true, true, 'duplex', execa);151test('Can use duplexes with error.stdio[*] as output, objectMode, noop transform', testGeneratorOutput, 3, false, false, true, true, 'duplex', execa);152test('Can use webTransforms with result.stdio[1]', testGeneratorOutput, 1, true, false, false, false, 'webTransform', execa);153test('Can use webTransforms with result.stdout', testGeneratorOutput, 1, true, true, false, false, 'webTransform', execa);154test('Can use webTransforms with result.stdio[2]', testGeneratorOutput, 2, true, false, false, false, 'webTransform', execa);155test('Can use webTransforms with result.stderr', testGeneratorOutput, 2, true, true, false, false, 'webTransform', execa);156test('Can use webTransforms with result.stdio[*] as output', testGeneratorOutput, 3, true, false, false, false, 'webTransform', execa);157test('Can use webTransforms with error.stdio[1]', testGeneratorOutput, 1, false, false, false, false, 'webTransform', execa);158test('Can use webTransforms with error.stdout', testGeneratorOutput, 1, false, true, false, false, 'webTransform', execa);159test('Can use webTransforms with error.stdio[2]', testGeneratorOutput, 2, false, false, false, false, 'webTransform', execa);160test('Can use webTransforms with error.stderr', testGeneratorOutput, 2, false, true, false, false, 'webTransform', execa);161test('Can use webTransforms with error.stdio[*] as output', testGeneratorOutput, 3, false, false, false, false, 'webTransform', execa);162test('Can use webTransforms with result.stdio[1], objectMode', testGeneratorOutput, 1, true, false, true, false, 'webTransform', execa);163test('Can use webTransforms with result.stdout, objectMode', testGeneratorOutput, 1, true, true, true, false, 'webTransform', execa);164test('Can use webTransforms with result.stdio[2], objectMode', testGeneratorOutput, 2, true, false, true, false, 'webTransform', execa);165test('Can use webTransforms with result.stderr, objectMode', testGeneratorOutput, 2, true, true, true, false, 'webTransform', execa);166test('Can use webTransforms with result.stdio[*] as output, objectMode', testGeneratorOutput, 3, true, false, true, false, 'webTransform', execa);167test('Can use webTransforms with error.stdio[1], objectMode', testGeneratorOutput, 1, false, false, true, false, 'webTransform', execa);168test('Can use webTransforms with error.stdout, objectMode', testGeneratorOutput, 1, false, true, true, false, 'webTransform', execa);169test('Can use webTransforms with error.stdio[2], objectMode', testGeneratorOutput, 2, false, false, true, false, 'webTransform', execa);170test('Can use webTransforms with error.stderr, objectMode', testGeneratorOutput, 2, false, true, true, false, 'webTransform', execa);171test('Can use webTransforms with error.stdio[*] as output, objectMode', testGeneratorOutput, 3, false, false, true, false, 'webTransform', execa);172test('Can use webTransforms with result.stdio[1], noop transform', testGeneratorOutput, 1, true, false, false, true, 'webTransform', execa);173test('Can use webTransforms with result.stdout, noop transform', testGeneratorOutput, 1, true, true, false, true, 'webTransform', execa);174test('Can use webTransforms with result.stdio[2], noop transform', testGeneratorOutput, 2, true, false, false, true, 'webTransform', execa);175test('Can use webTransforms with result.stderr, noop transform', testGeneratorOutput, 2, true, true, false, true, 'webTransform', execa);176test('Can use webTransforms with result.stdio[*] as output, noop transform', testGeneratorOutput, 3, true, false, false, true, 'webTransform', execa);177test('Can use webTransforms with error.stdio[1], noop transform', testGeneratorOutput, 1, false, false, false, true, 'webTransform', execa);178test('Can use webTransforms with error.stdout, noop transform', testGeneratorOutput, 1, false, true, false, true, 'webTransform', execa);179test('Can use webTransforms with error.stdio[2], noop transform', testGeneratorOutput, 2, false, false, false, true, 'webTransform', execa);180test('Can use webTransforms with error.stderr, noop transform', testGeneratorOutput, 2, false, true, false, true, 'webTransform', execa);181test('Can use webTransforms with error.stdio[*] as output, noop transform', testGeneratorOutput, 3, false, false, false, true, 'webTransform', execa);182test('Can use webTransforms with result.stdio[1], objectMode, noop transform', testGeneratorOutput, 1, true, false, true, true, 'webTransform', execa);183test('Can use webTransforms with result.stdout, objectMode, noop transform', testGeneratorOutput, 1, true, true, true, true, 'webTransform', execa);184test('Can use webTransforms with result.stdio[2], objectMode, noop transform', testGeneratorOutput, 2, true, false, true, true, 'webTransform', execa);185test('Can use webTransforms with result.stderr, objectMode, noop transform', testGeneratorOutput, 2, true, true, true, true, 'webTransform', execa);186test('Can use webTransforms with result.stdio[*] as output, objectMode, noop transform', testGeneratorOutput, 3, true, false, true, true, 'webTransform', execa);187test('Can use webTransforms with error.stdio[1], objectMode, noop transform', testGeneratorOutput, 1, false, false, true, true, 'webTransform', execa);188test('Can use webTransforms with error.stdout, objectMode, noop transform', testGeneratorOutput, 1, false, true, true, true, 'webTransform', execa);189test('Can use webTransforms with error.stdio[2], objectMode, noop transform', testGeneratorOutput, 2, false, false, true, true, 'webTransform', execa);190test('Can use webTransforms with error.stderr, objectMode, noop transform', testGeneratorOutput, 2, false, true, true, true, 'webTransform', execa);191test('Can use webTransforms with error.stdio[*] as output, objectMode, noop transform', testGeneratorOutput, 3, false, false, true, true, 'webTransform', execa);192193// eslint-disable-next-line max-params194const 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};201202test('Can use generators with subprocess.stdio[1]', testGeneratorOutputPipe, 1, false, false, false, 'generator');203test('Can use generators with subprocess.stdout', testGeneratorOutputPipe, 1, true, false, false, 'generator');204test('Can use generators with subprocess.stdio[2]', testGeneratorOutputPipe, 2, false, false, false, 'generator');205test('Can use generators with subprocess.stderr', testGeneratorOutputPipe, 2, true, false, false, 'generator');206test('Can use generators with subprocess.stdio[*] as output', testGeneratorOutputPipe, 3, false, false, false, 'generator');207test('Can use generators with subprocess.stdio[1], objectMode', testGeneratorOutputPipe, 1, false, true, false, 'generator');208test('Can use generators with subprocess.stdout, objectMode', testGeneratorOutputPipe, 1, true, true, false, 'generator');209test('Can use generators with subprocess.stdio[2], objectMode', testGeneratorOutputPipe, 2, false, true, false, 'generator');210test('Can use generators with subprocess.stderr, objectMode', testGeneratorOutputPipe, 2, true, true, false, 'generator');211test('Can use generators with subprocess.stdio[*] as output, objectMode', testGeneratorOutputPipe, 3, false, true, false, 'generator');212test('Can use generators with subprocess.stdio[1], noop transform', testGeneratorOutputPipe, 1, false, false, true, 'generator');213test('Can use generators with subprocess.stdout, noop transform', testGeneratorOutputPipe, 1, true, false, true, 'generator');214test('Can use generators with subprocess.stdio[2], noop transform', testGeneratorOutputPipe, 2, false, false, true, 'generator');215test('Can use generators with subprocess.stderr, noop transform', testGeneratorOutputPipe, 2, true, false, true, 'generator');216test('Can use generators with subprocess.stdio[*] as output, noop transform', testGeneratorOutputPipe, 3, false, false, true, 'generator');217test('Can use generators with subprocess.stdio[1], objectMode, noop transform', testGeneratorOutputPipe, 1, false, true, true, 'generator');218test('Can use generators with subprocess.stdout, objectMode, noop transform', testGeneratorOutputPipe, 1, true, true, true, 'generator');219test('Can use generators with subprocess.stdio[2], objectMode, noop transform', testGeneratorOutputPipe, 2, false, true, true, 'generator');220test('Can use generators with subprocess.stderr, objectMode, noop transform', testGeneratorOutputPipe, 2, true, true, true, 'generator');221test('Can use generators with subprocess.stdio[*] as output, objectMode, noop transform', testGeneratorOutputPipe, 3, false, true, true, 'generator');222test('Can use duplexes with subprocess.stdio[1]', testGeneratorOutputPipe, 1, false, false, false, 'duplex');223test('Can use duplexes with subprocess.stdout', testGeneratorOutputPipe, 1, true, false, false, 'duplex');224test('Can use duplexes with subprocess.stdio[2]', testGeneratorOutputPipe, 2, false, false, false, 'duplex');225test('Can use duplexes with subprocess.stderr', testGeneratorOutputPipe, 2, true, false, false, 'duplex');226test('Can use duplexes with subprocess.stdio[*] as output', testGeneratorOutputPipe, 3, false, false, false, 'duplex');227test('Can use duplexes with subprocess.stdio[1], objectMode', testGeneratorOutputPipe, 1, false, true, false, 'duplex');228test('Can use duplexes with subprocess.stdout, objectMode', testGeneratorOutputPipe, 1, true, true, false, 'duplex');229test('Can use duplexes with subprocess.stdio[2], objectMode', testGeneratorOutputPipe, 2, false, true, false, 'duplex');230test('Can use duplexes with subprocess.stderr, objectMode', testGeneratorOutputPipe, 2, true, true, false, 'duplex');231test('Can use duplexes with subprocess.stdio[*] as output, objectMode', testGeneratorOutputPipe, 3, false, true, false, 'duplex');232test('Can use duplexes with subprocess.stdio[1], noop transform', testGeneratorOutputPipe, 1, false, false, true, 'duplex');233test('Can use duplexes with subprocess.stdout, noop transform', testGeneratorOutputPipe, 1, true, false, true, 'duplex');234test('Can use duplexes with subprocess.stdio[2], noop transform', testGeneratorOutputPipe, 2, false, false, true, 'duplex');235test('Can use duplexes with subprocess.stderr, noop transform', testGeneratorOutputPipe, 2, true, false, true, 'duplex');236test('Can use duplexes with subprocess.stdio[*] as output, noop transform', testGeneratorOutputPipe, 3, false, false, true, 'duplex');237test('Can use duplexes with subprocess.stdio[1], objectMode, noop transform', testGeneratorOutputPipe, 1, false, true, true, 'duplex');238test('Can use duplexes with subprocess.stdout, objectMode, noop transform', testGeneratorOutputPipe, 1, true, true, true, 'duplex');239test('Can use duplexes with subprocess.stdio[2], objectMode, noop transform', testGeneratorOutputPipe, 2, false, true, true, 'duplex');240test('Can use duplexes with subprocess.stderr, objectMode, noop transform', testGeneratorOutputPipe, 2, true, true, true, 'duplex');241test('Can use duplexes with subprocess.stdio[*] as output, objectMode, noop transform', testGeneratorOutputPipe, 3, false, true, true, 'duplex');242test('Can use webTransforms with subprocess.stdio[1]', testGeneratorOutputPipe, 1, false, false, false, 'webTransform');243test('Can use webTransforms with subprocess.stdout', testGeneratorOutputPipe, 1, true, false, false, 'webTransform');244test('Can use webTransforms with subprocess.stdio[2]', testGeneratorOutputPipe, 2, false, false, false, 'webTransform');245test('Can use webTransforms with subprocess.stderr', testGeneratorOutputPipe, 2, true, false, false, 'webTransform');246test('Can use webTransforms with subprocess.stdio[*] as output', testGeneratorOutputPipe, 3, false, false, false, 'webTransform');247test('Can use webTransforms with subprocess.stdio[1], objectMode', testGeneratorOutputPipe, 1, false, true, false, 'webTransform');248test('Can use webTransforms with subprocess.stdout, objectMode', testGeneratorOutputPipe, 1, true, true, false, 'webTransform');249test('Can use webTransforms with subprocess.stdio[2], objectMode', testGeneratorOutputPipe, 2, false, true, false, 'webTransform');250test('Can use webTransforms with subprocess.stderr, objectMode', testGeneratorOutputPipe, 2, true, true, false, 'webTransform');251test('Can use webTransforms with subprocess.stdio[*] as output, objectMode', testGeneratorOutputPipe, 3, false, true, false, 'webTransform');252test('Can use webTransforms with subprocess.stdio[1], noop transform', testGeneratorOutputPipe, 1, false, false, true, 'webTransform');253test('Can use webTransforms with subprocess.stdout, noop transform', testGeneratorOutputPipe, 1, true, false, true, 'webTransform');254test('Can use webTransforms with subprocess.stdio[2], noop transform', testGeneratorOutputPipe, 2, false, false, true, 'webTransform');255test('Can use webTransforms with subprocess.stderr, noop transform', testGeneratorOutputPipe, 2, true, false, true, 'webTransform');256test('Can use webTransforms with subprocess.stdio[*] as output, noop transform', testGeneratorOutputPipe, 3, false, false, true, 'webTransform');257test('Can use webTransforms with subprocess.stdio[1], objectMode, noop transform', testGeneratorOutputPipe, 1, false, true, true, 'webTransform');258test('Can use webTransforms with subprocess.stdout, objectMode, noop transform', testGeneratorOutputPipe, 1, true, true, true, 'webTransform');259test('Can use webTransforms with subprocess.stdio[2], objectMode, noop transform', testGeneratorOutputPipe, 2, false, true, true, 'webTransform');260test('Can use webTransforms with subprocess.stderr, objectMode, noop transform', testGeneratorOutputPipe, 2, true, true, true, 'webTransform');261test('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
1import {Buffer} from 'node:buffer';2import test from 'ava';3import {execa, execaSync} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';5import {foobarString, foobarUint8Array} from '../helpers/input.js';6import {getOutputGenerator, convertTransformToFinal} from '../helpers/generator.js';78setFixtureDir();910// eslint-disable-next-line max-params11const 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};2223test('Generator can return string with default encoding', testGeneratorReturnType, foobarString, 'utf8', true, false, false, execa);24test('Generator can return Uint8Array with default encoding', testGeneratorReturnType, foobarUint8Array, 'utf8', true, false, false, execa);25test('Generator can return string with encoding "utf16le"', testGeneratorReturnType, foobarString, 'utf16le', true, false, false, execa);26test('Generator can return Uint8Array with encoding "utf16le"', testGeneratorReturnType, foobarUint8Array, 'utf16le', true, false, false, execa);27test('Generator can return string with encoding "buffer"', testGeneratorReturnType, foobarString, 'buffer', true, false, false, execa);28test('Generator can return Uint8Array with encoding "buffer"', testGeneratorReturnType, foobarUint8Array, 'buffer', true, false, false, execa);29test('Generator can return string with encoding "hex"', testGeneratorReturnType, foobarString, 'hex', true, false, false, execa);30test('Generator can return Uint8Array with encoding "hex"', testGeneratorReturnType, foobarUint8Array, 'hex', true, false, false, execa);31test('Generator can return string with default encoding, failure', testGeneratorReturnType, foobarString, 'utf8', false, false, false, execa);32test('Generator can return Uint8Array with default encoding, failure', testGeneratorReturnType, foobarUint8Array, 'utf8', false, false, false, execa);33test('Generator can return string with encoding "utf16le", failure', testGeneratorReturnType, foobarString, 'utf16le', false, false, false, execa);34test('Generator can return Uint8Array with encoding "utf16le", failure', testGeneratorReturnType, foobarUint8Array, 'utf16le', false, false, false, execa);35test('Generator can return string with encoding "buffer", failure', testGeneratorReturnType, foobarString, 'buffer', false, false, false, execa);36test('Generator can return Uint8Array with encoding "buffer", failure', testGeneratorReturnType, foobarUint8Array, 'buffer', false, false, false, execa);37test('Generator can return string with encoding "hex", failure', testGeneratorReturnType, foobarString, 'hex', false, false, false, execa);38test('Generator can return Uint8Array with encoding "hex", failure', testGeneratorReturnType, foobarUint8Array, 'hex', false, false, false, execa);39test('Generator can return string with default encoding, objectMode', testGeneratorReturnType, foobarString, 'utf8', true, true, false, execa);40test('Generator can return Uint8Array with default encoding, objectMode', testGeneratorReturnType, foobarUint8Array, 'utf8', true, true, false, execa);41test('Generator can return string with encoding "utf16le", objectMode', testGeneratorReturnType, foobarString, 'utf16le', true, true, false, execa);42test('Generator can return Uint8Array with encoding "utf16le", objectMode', testGeneratorReturnType, foobarUint8Array, 'utf16le', true, true, false, execa);43test('Generator can return string with encoding "buffer", objectMode', testGeneratorReturnType, foobarString, 'buffer', true, true, false, execa);44test('Generator can return Uint8Array with encoding "buffer", objectMode', testGeneratorReturnType, foobarUint8Array, 'buffer', true, true, false, execa);45test('Generator can return string with encoding "hex", objectMode', testGeneratorReturnType, foobarString, 'hex', true, true, false, execa);46test('Generator can return Uint8Array with encoding "hex", objectMode', testGeneratorReturnType, foobarUint8Array, 'hex', true, true, false, execa);47test('Generator can return string with default encoding, objectMode, failure', testGeneratorReturnType, foobarString, 'utf8', false, true, false, execa);48test('Generator can return Uint8Array with default encoding, objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'utf8', false, true, false, execa);49test('Generator can return string with encoding "utf16le", objectMode, failure', testGeneratorReturnType, foobarString, 'utf16le', false, true, false, execa);50test('Generator can return Uint8Array with encoding "utf16le", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'utf16le', false, true, false, execa);51test('Generator can return string with encoding "buffer", objectMode, failure', testGeneratorReturnType, foobarString, 'buffer', false, true, false, execa);52test('Generator can return Uint8Array with encoding "buffer", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'buffer', false, true, false, execa);53test('Generator can return string with encoding "hex", objectMode, failure', testGeneratorReturnType, foobarString, 'hex', false, true, false, execa);54test('Generator can return Uint8Array with encoding "hex", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'hex', false, true, false, execa);55test('Generator can return final string with default encoding', testGeneratorReturnType, foobarString, 'utf8', true, false, true, execa);56test('Generator can return final Uint8Array with default encoding', testGeneratorReturnType, foobarUint8Array, 'utf8', true, false, true, execa);57test('Generator can return final string with encoding "utf16le"', testGeneratorReturnType, foobarString, 'utf16le', true, false, true, execa);58test('Generator can return final Uint8Array with encoding "utf16le"', testGeneratorReturnType, foobarUint8Array, 'utf16le', true, false, true, execa);59test('Generator can return final string with encoding "buffer"', testGeneratorReturnType, foobarString, 'buffer', true, false, true, execa);60test('Generator can return final Uint8Array with encoding "buffer"', testGeneratorReturnType, foobarUint8Array, 'buffer', true, false, true, execa);61test('Generator can return final string with encoding "hex"', testGeneratorReturnType, foobarString, 'hex', true, false, true, execa);62test('Generator can return final Uint8Array with encoding "hex"', testGeneratorReturnType, foobarUint8Array, 'hex', true, false, true, execa);63test('Generator can return final string with default encoding, failure', testGeneratorReturnType, foobarString, 'utf8', false, false, true, execa);64test('Generator can return final Uint8Array with default encoding, failure', testGeneratorReturnType, foobarUint8Array, 'utf8', false, false, true, execa);65test('Generator can return final string with encoding "utf16le", failure', testGeneratorReturnType, foobarString, 'utf16le', false, false, true, execa);66test('Generator can return final Uint8Array with encoding "utf16le", failure', testGeneratorReturnType, foobarUint8Array, 'utf16le', false, false, true, execa);67test('Generator can return final string with encoding "buffer", failure', testGeneratorReturnType, foobarString, 'buffer', false, false, true, execa);68test('Generator can return final Uint8Array with encoding "buffer", failure', testGeneratorReturnType, foobarUint8Array, 'buffer', false, false, true, execa);69test('Generator can return final string with encoding "hex", failure', testGeneratorReturnType, foobarString, 'hex', false, false, true, execa);70test('Generator can return final Uint8Array with encoding "hex", failure', testGeneratorReturnType, foobarUint8Array, 'hex', false, false, true, execa);71test('Generator can return final string with default encoding, objectMode', testGeneratorReturnType, foobarString, 'utf8', true, true, true, execa);72test('Generator can return final Uint8Array with default encoding, objectMode', testGeneratorReturnType, foobarUint8Array, 'utf8', true, true, true, execa);73test('Generator can return final string with encoding "utf16le", objectMode', testGeneratorReturnType, foobarString, 'utf16le', true, true, true, execa);74test('Generator can return final Uint8Array with encoding "utf16le", objectMode', testGeneratorReturnType, foobarUint8Array, 'utf16le', true, true, true, execa);75test('Generator can return final string with encoding "buffer", objectMode', testGeneratorReturnType, foobarString, 'buffer', true, true, true, execa);76test('Generator can return final Uint8Array with encoding "buffer", objectMode', testGeneratorReturnType, foobarUint8Array, 'buffer', true, true, true, execa);77test('Generator can return final string with encoding "hex", objectMode', testGeneratorReturnType, foobarString, 'hex', true, true, true, execa);78test('Generator can return final Uint8Array with encoding "hex", objectMode', testGeneratorReturnType, foobarUint8Array, 'hex', true, true, true, execa);79test('Generator can return final string with default encoding, objectMode, failure', testGeneratorReturnType, foobarString, 'utf8', false, true, true, execa);80test('Generator can return final Uint8Array with default encoding, objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'utf8', false, true, true, execa);81test('Generator can return final string with encoding "utf16le", objectMode, failure', testGeneratorReturnType, foobarString, 'utf16le', false, true, true, execa);82test('Generator can return final Uint8Array with encoding "utf16le", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'utf16le', false, true, true, execa);83test('Generator can return final string with encoding "buffer", objectMode, failure', testGeneratorReturnType, foobarString, 'buffer', false, true, true, execa);84test('Generator can return final Uint8Array with encoding "buffer", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'buffer', false, true, true, execa);85test('Generator can return final string with encoding "hex", objectMode, failure', testGeneratorReturnType, foobarString, 'hex', false, true, true, execa);86test('Generator can return final Uint8Array with encoding "hex", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'hex', false, true, true, execa);87test('Generator can return string with default encoding, sync', testGeneratorReturnType, foobarString, 'utf8', true, false, false, execaSync);88test('Generator can return Uint8Array with default encoding, sync', testGeneratorReturnType, foobarUint8Array, 'utf8', true, false, false, execaSync);89test('Generator can return string with encoding "utf16le", sync', testGeneratorReturnType, foobarString, 'utf16le', true, false, false, execaSync);90test('Generator can return Uint8Array with encoding "utf16le", sync', testGeneratorReturnType, foobarUint8Array, 'utf16le', true, false, false, execaSync);91test('Generator can return string with encoding "buffer", sync', testGeneratorReturnType, foobarString, 'buffer', true, false, false, execaSync);92test('Generator can return Uint8Array with encoding "buffer", sync', testGeneratorReturnType, foobarUint8Array, 'buffer', true, false, false, execaSync);93test('Generator can return string with encoding "hex", sync', testGeneratorReturnType, foobarString, 'hex', true, false, false, execaSync);94test('Generator can return Uint8Array with encoding "hex", sync', testGeneratorReturnType, foobarUint8Array, 'hex', true, false, false, execaSync);95test('Generator can return string with default encoding, failure, sync', testGeneratorReturnType, foobarString, 'utf8', false, false, false, execaSync);96test('Generator can return Uint8Array with default encoding, failure, sync', testGeneratorReturnType, foobarUint8Array, 'utf8', false, false, false, execaSync);97test('Generator can return string with encoding "utf16le", failure, sync', testGeneratorReturnType, foobarString, 'utf16le', false, false, false, execaSync);98test('Generator can return Uint8Array with encoding "utf16le", failure, sync', testGeneratorReturnType, foobarUint8Array, 'utf16le', false, false, false, execaSync);99test('Generator can return string with encoding "buffer", failure, sync', testGeneratorReturnType, foobarString, 'buffer', false, false, false, execaSync);100test('Generator can return Uint8Array with encoding "buffer", failure, sync', testGeneratorReturnType, foobarUint8Array, 'buffer', false, false, false, execaSync);101test('Generator can return string with encoding "hex", failure, sync', testGeneratorReturnType, foobarString, 'hex', false, false, false, execaSync);102test('Generator can return Uint8Array with encoding "hex", failure, sync', testGeneratorReturnType, foobarUint8Array, 'hex', false, false, false, execaSync);103test('Generator can return string with default encoding, objectMode, sync', testGeneratorReturnType, foobarString, 'utf8', true, true, false, execaSync);104test('Generator can return Uint8Array with default encoding, objectMode, sync', testGeneratorReturnType, foobarUint8Array, 'utf8', true, true, false, execaSync);105test('Generator can return string with encoding "utf16le", objectMode, sync', testGeneratorReturnType, foobarString, 'utf16le', true, true, false, execaSync);106test('Generator can return Uint8Array with encoding "utf16le", objectMode, sync', testGeneratorReturnType, foobarUint8Array, 'utf16le', true, true, false, execaSync);107test('Generator can return string with encoding "buffer", objectMode, sync', testGeneratorReturnType, foobarString, 'buffer', true, true, false, execaSync);108test('Generator can return Uint8Array with encoding "buffer", objectMode, sync', testGeneratorReturnType, foobarUint8Array, 'buffer', true, true, false, execaSync);109test('Generator can return string with encoding "hex", objectMode, sync', testGeneratorReturnType, foobarString, 'hex', true, true, false, execaSync);110test('Generator can return Uint8Array with encoding "hex", objectMode, sync', testGeneratorReturnType, foobarUint8Array, 'hex', true, true, false, execaSync);111test('Generator can return string with default encoding, objectMode, failure, sync', testGeneratorReturnType, foobarString, 'utf8', false, true, false, execaSync);112test('Generator can return Uint8Array with default encoding, objectMode, failure, sync', testGeneratorReturnType, foobarUint8Array, 'utf8', false, true, false, execaSync);113test('Generator can return string with encoding "utf16le", objectMode, failure, sync', testGeneratorReturnType, foobarString, 'utf16le', false, true, false, execaSync);114test('Generator can return Uint8Array with encoding "utf16le", objectMode, failure, sync', testGeneratorReturnType, foobarUint8Array, 'utf16le', false, true, false, execaSync);115test('Generator can return string with encoding "buffer", objectMode, failure, sync', testGeneratorReturnType, foobarString, 'buffer', false, true, false, execaSync);116test('Generator can return Uint8Array with encoding "buffer", objectMode, failure, sync', testGeneratorReturnType, foobarUint8Array, 'buffer', false, true, false, execaSync);117test('Generator can return string with encoding "hex", objectMode, failure, sync', testGeneratorReturnType, foobarString, 'hex', false, true, false, execaSync);118test('Generator can return Uint8Array with encoding "hex", objectMode, failure, sync', testGeneratorReturnType, foobarUint8Array, 'hex', false, true, false, execaSync);119test('Generator can return final string with default encoding, sync', testGeneratorReturnType, foobarString, 'utf8', true, false, true, execaSync);120test('Generator can return final Uint8Array with default encoding, sync', testGeneratorReturnType, foobarUint8Array, 'utf8', true, false, true, execaSync);121test('Generator can return final string with encoding "utf16le", sync', testGeneratorReturnType, foobarString, 'utf16le', true, false, true, execaSync);122test('Generator can return final Uint8Array with encoding "utf16le", sync', testGeneratorReturnType, foobarUint8Array, 'utf16le', true, false, true, execaSync);123test('Generator can return final string with encoding "buffer", sync', testGeneratorReturnType, foobarString, 'buffer', true, false, true, execaSync);124test('Generator can return final Uint8Array with encoding "buffer", sync', testGeneratorReturnType, foobarUint8Array, 'buffer', true, false, true, execaSync);125test('Generator can return final string with encoding "hex", sync', testGeneratorReturnType, foobarString, 'hex', true, false, true, execaSync);126test('Generator can return final Uint8Array with encoding "hex", sync', testGeneratorReturnType, foobarUint8Array, 'hex', true, false, true, execaSync);127test('Generator can return final string with default encoding, failure, sync', testGeneratorReturnType, foobarString, 'utf8', false, false, true, execaSync);128test('Generator can return final Uint8Array with default encoding, failure, sync', testGeneratorReturnType, foobarUint8Array, 'utf8', false, false, true, execaSync);129test('Generator can return final string with encoding "utf16le", failure, sync', testGeneratorReturnType, foobarString, 'utf16le', false, false, true, execaSync);130test('Generator can return final Uint8Array with encoding "utf16le", failure, sync', testGeneratorReturnType, foobarUint8Array, 'utf16le', false, false, true, execaSync);131test('Generator can return final string with encoding "buffer", failure, sync', testGeneratorReturnType, foobarString, 'buffer', false, false, true, execaSync);132test('Generator can return final Uint8Array with encoding "buffer", failure, sync', testGeneratorReturnType, foobarUint8Array, 'buffer', false, false, true, execaSync);133test('Generator can return final string with encoding "hex", failure, sync', testGeneratorReturnType, foobarString, 'hex', false, false, true, execaSync);134test('Generator can return final Uint8Array with encoding "hex", failure, sync', testGeneratorReturnType, foobarUint8Array, 'hex', false, false, true, execaSync);135test('Generator can return final string with default encoding, objectMode, sync', testGeneratorReturnType, foobarString, 'utf8', true, true, true, execaSync);136test('Generator can return final Uint8Array with default encoding, objectMode, sync', testGeneratorReturnType, foobarUint8Array, 'utf8', true, true, true, execaSync);137test('Generator can return final string with encoding "utf16le", objectMode, sync', testGeneratorReturnType, foobarString, 'utf16le', true, true, true, execaSync);138test('Generator can return final Uint8Array with encoding "utf16le", objectMode, sync', testGeneratorReturnType, foobarUint8Array, 'utf16le', true, true, true, execaSync);139test('Generator can return final string with encoding "buffer", objectMode, sync', testGeneratorReturnType, foobarString, 'buffer', true, true, true, execaSync);140test('Generator can return final Uint8Array with encoding "buffer", objectMode, sync', testGeneratorReturnType, foobarUint8Array, 'buffer', true, true, true, execaSync);141test('Generator can return final string with encoding "hex", objectMode, sync', testGeneratorReturnType, foobarString, 'hex', true, true, true, execaSync);142test('Generator can return final Uint8Array with encoding "hex", objectMode, sync', testGeneratorReturnType, foobarUint8Array, 'hex', true, true, true, execaSync);143test('Generator can return final string with default encoding, objectMode, failure, sync', testGeneratorReturnType, foobarString, 'utf8', false, true, true, execaSync);144test('Generator can return final Uint8Array with default encoding, objectMode, failure, sync', testGeneratorReturnType, foobarUint8Array, 'utf8', false, true, true, execaSync);145test('Generator can return final string with encoding "utf16le", objectMode, failure, sync', testGeneratorReturnType, foobarString, 'utf16le', false, true, true, execaSync);146test('Generator can return final Uint8Array with encoding "utf16le", objectMode, failure, sync', testGeneratorReturnType, foobarUint8Array, 'utf16le', false, true, true, execaSync);147test('Generator can return final string with encoding "buffer", objectMode, failure, sync', testGeneratorReturnType, foobarString, 'buffer', false, true, true, execaSync);148test('Generator can return final Uint8Array with encoding "buffer", objectMode, failure, sync', testGeneratorReturnType, foobarUint8Array, 'buffer', false, true, true, execaSync);149test('Generator can return final string with encoding "hex", objectMode, failure, sync', testGeneratorReturnType, foobarString, 'hex', false, true, true, execaSync);150test('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
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {foobarString, foobarUppercase, foobarUint8Array} from '../helpers/input.js';5import {casedSuffix} from '../helpers/generator.js';6import {generatorsMap} from '../helpers/map.js';78setFixtureDir();910const 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};1718test('Can use multiple generators as input', testAppendInput, false, 'generator', execa);19test('Can use multiple generators as input, reversed', testAppendInput, true, 'generator', execa);20test('Can use multiple generators as input, sync', testAppendInput, false, 'generator', execaSync);21test('Can use multiple generators as input, reversed, sync', testAppendInput, true, 'generator', execaSync);22test('Can use multiple duplexes as input', testAppendInput, false, 'duplex', execa);23test('Can use multiple duplexes as input, reversed', testAppendInput, true, 'duplex', execa);24test('Can use multiple webTransforms as input', testAppendInput, false, 'webTransform', execa);25test('Can use multiple webTransforms as input, reversed', testAppendInput, true, 'webTransform', execa);2627const 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};3435test('Can use multiple generators as output', testAppendOutput, false, 'generator', execa);36test('Can use multiple generators as output, reversed', testAppendOutput, true, 'generator', execa);37test('Can use multiple generators as output, sync', testAppendOutput, false, 'generator', execaSync);38test('Can use multiple generators as output, reversed, sync', testAppendOutput, true, 'generator', execaSync);39test('Can use multiple duplexes as output', testAppendOutput, false, 'duplex', execa);40test('Can use multiple duplexes as output, reversed', testAppendOutput, true, 'duplex', execa);41test('Can use multiple webTransforms as output', testAppendOutput, false, 'webTransform', execa);42test('Can use multiple webTransforms as output, reversed', testAppendOutput, true, 'webTransform', execa);4344const 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};4950test('Can pass generators with an options plain object', testGeneratorSyntax, 'generator', false, execa);51test('Can pass generators without an options plain object', testGeneratorSyntax, 'generator', true, execa);52test('Can pass generators with an options plain object, sync', testGeneratorSyntax, 'generator', false, execaSync);53test('Can pass generators without an options plain object, sync', testGeneratorSyntax, 'generator', true, execaSync);54test('Can pass webTransforms with an options plain object', testGeneratorSyntax, 'webTransform', true, execa);55test('Can pass webTransforms without an options plain object', testGeneratorSyntax, 'webTransform', false, execa);
added:test/transform/split-binary.js+95 added
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {getOutputsGenerator, resultGenerator} from '../helpers/generator.js';5import {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';1819setFixtureDir();2021// eslint-disable-next-line max-params22const 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};3536test('Does not split lines when "binary" is true', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFull, false, true, 'utf8', execa);37test('Splits lines when "binary" is false', testBinaryOption, false, simpleChunks, simpleLines, simpleFull, false, true, 'utf8', execa);38test('Splits lines when "binary" is undefined', testBinaryOption, undefined, simpleChunks, simpleLines, simpleFull, false, true, 'utf8', execa);39test('Does not split lines when "binary" is true, encoding "utf16le"', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUtf16Inverted, false, true, 'utf16le', execa);40test('Splits lines when "binary" is false, encoding "utf16le"', testBinaryOption, false, [simpleFullUtf16Uint8Array], simpleLines, simpleFullUtf16Inverted, false, true, 'utf16le', execa);41test('Splits lines when "binary" is undefined, encoding "utf16le"', testBinaryOption, undefined, [simpleFullUtf16Uint8Array], simpleLines, simpleFullUtf16Inverted, false, true, 'utf16le', execa);42test('Does not split lines when "binary" is true, encoding "buffer"', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, true, 'buffer', execa);43test('Does not split lines when "binary" is undefined, encoding "buffer"', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, true, 'buffer', execa);44test('Does not split lines when "binary" is false, encoding "buffer"', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, true, 'buffer', execa);45test('Does not split lines when "binary" is true, encoding "hex"', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, true, 'hex', execa);46test('Does not split lines when "binary" is undefined, encoding "hex"', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, true, 'hex', execa);47test('Does not split lines when "binary" is false, encoding "hex"', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, true, 'hex', execa);48test('Does not split lines when "binary" is true, objectMode', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleChunksUint8Array, true, true, 'utf8', execa);49test('Splits lines when "binary" is false, objectMode', testBinaryOption, false, simpleChunks, simpleLines, simpleLines, true, true, 'utf8', execa);50test('Splits lines when "binary" is undefined, objectMode', testBinaryOption, undefined, simpleChunks, simpleLines, simpleLines, true, true, 'utf8', execa);51test('Does not split lines when "binary" is true, preserveNewlines', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFull, false, false, 'utf8', execa);52test('Splits lines when "binary" is false, preserveNewlines', testBinaryOption, false, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, 'utf8', execa);53test('Splits lines when "binary" is undefined, preserveNewlines', testBinaryOption, undefined, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, 'utf8', execa);54test('Does not split lines when "binary" is true, preserveNewlines, encoding "utf16le"', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUtf16Inverted, false, false, 'utf16le', execa);55test('Splits lines when "binary" is false, preserveNewlines, encoding "utf16le"', testBinaryOption, false, [simpleFullUtf16Uint8Array], noNewlinesChunks, simpleFullEndUtf16Inverted, false, false, 'utf16le', execa);56test('Splits lines when "binary" is undefined, preserveNewlines, encoding "utf16le"', testBinaryOption, undefined, [simpleFullUtf16Uint8Array], noNewlinesChunks, simpleFullEndUtf16Inverted, false, false, 'utf16le', execa);57test('Does not split lines when "binary" is true, encoding "buffer", preserveNewlines', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, false, 'buffer', execa);58test('Does not split lines when "binary" is undefined, encoding "buffer", preserveNewlines', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, false, 'buffer', execa);59test('Does not split lines when "binary" is false, encoding "buffer", preserveNewlines', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, false, 'buffer', execa);60test('Does not split lines when "binary" is true, objectMode, preserveNewlines', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleChunksUint8Array, true, false, 'utf8', execa);61test('Does not split lines when "binary" is true, encoding "hex", preserveNewlines', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, false, 'hex', execa);62test('Does not split lines when "binary" is undefined, encoding "hex", preserveNewlines', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, false, 'hex', execa);63test('Does not split lines when "binary" is false, encoding "hex", preserveNewlines', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, false, 'hex', execa);64test('Splits lines when "binary" is false, objectMode, preserveNewlines', testBinaryOption, false, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, 'utf8', execa);65test('Splits lines when "binary" is undefined, objectMode, preserveNewlines', testBinaryOption, undefined, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, 'utf8', execa);66test('Does not split lines when "binary" is true, sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFull, false, true, 'utf8', execaSync);67test('Splits lines when "binary" is false, sync', testBinaryOption, false, simpleChunks, simpleLines, simpleFull, false, true, 'utf8', execaSync);68test('Splits lines when "binary" is undefined, sync', testBinaryOption, undefined, simpleChunks, simpleLines, simpleFull, false, true, 'utf8', execaSync);69test('Does not split lines when "binary" is true, encoding "utf16le", sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUtf16Inverted, false, true, 'utf16le', execaSync);70test('Splits lines when "binary" is false, encoding "utf16le", sync', testBinaryOption, false, [simpleFullUtf16Uint8Array], simpleLines, simpleFullUtf16Inverted, false, true, 'utf16le', execaSync);71test('Splits lines when "binary" is undefined, encoding "utf16le", sync', testBinaryOption, undefined, [simpleFullUtf16Uint8Array], simpleLines, simpleFullUtf16Inverted, false, true, 'utf16le', execaSync);72test('Does not split lines when "binary" is true, encoding "buffer", sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, true, 'buffer', execaSync);73test('Does not split lines when "binary" is undefined, encoding "buffer", sync', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, true, 'buffer', execaSync);74test('Does not split lines when "binary" is false, encoding "buffer", sync', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, true, 'buffer', execaSync);75test('Does not split lines when "binary" is true, encoding "hex", sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, true, 'hex', execaSync);76test('Does not split lines when "binary" is undefined, encoding "hex", sync', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, true, 'hex', execaSync);77test('Does not split lines when "binary" is false, encoding "hex", sync', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, true, 'hex', execaSync);78test('Does not split lines when "binary" is true, objectMode, sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleChunksUint8Array, true, true, 'utf8', execaSync);79test('Splits lines when "binary" is false, objectMode, sync', testBinaryOption, false, simpleChunks, simpleLines, simpleLines, true, true, 'utf8', execaSync);80test('Splits lines when "binary" is undefined, objectMode, sync', testBinaryOption, undefined, simpleChunks, simpleLines, simpleLines, true, true, 'utf8', execaSync);81test('Does not split lines when "binary" is true, preserveNewlines, sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFull, false, false, 'utf8', execaSync);82test('Splits lines when "binary" is false, preserveNewlines, sync', testBinaryOption, false, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, 'utf8', execaSync);83test('Splits lines when "binary" is undefined, preserveNewlines, sync', testBinaryOption, undefined, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, 'utf8', execaSync);84test('Does not split lines when "binary" is true, preserveNewlines, encoding "utf16le", sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUtf16Inverted, false, false, 'utf16le', execaSync);85test('Splits lines when "binary" is false, preserveNewlines, encoding "utf16le", sync', testBinaryOption, false, [simpleFullUtf16Uint8Array], noNewlinesChunks, simpleFullEndUtf16Inverted, false, false, 'utf16le', execaSync);86test('Splits lines when "binary" is undefined, preserveNewlines, encoding "utf16le", sync', testBinaryOption, undefined, [simpleFullUtf16Uint8Array], noNewlinesChunks, simpleFullEndUtf16Inverted, false, false, 'utf16le', execaSync);87test('Does not split lines when "binary" is true, encoding "buffer", preserveNewlines, sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, false, 'buffer', execaSync);88test('Does not split lines when "binary" is undefined, encoding "buffer", preserveNewlines, sync', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, false, 'buffer', execaSync);89test('Does not split lines when "binary" is false, encoding "buffer", preserveNewlines, sync', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullUint8Array, false, false, 'buffer', execaSync);90test('Does not split lines when "binary" is true, objectMode, preserveNewlines, sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleChunksUint8Array, true, false, 'utf8', execaSync);91test('Does not split lines when "binary" is true, encoding "hex", preserveNewlines, sync', testBinaryOption, true, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, false, 'hex', execaSync);92test('Does not split lines when "binary" is undefined, encoding "hex", preserveNewlines, sync', testBinaryOption, undefined, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, false, 'hex', execaSync);93test('Does not split lines when "binary" is false, encoding "hex", preserveNewlines, sync', testBinaryOption, false, simpleChunks, simpleChunksUint8Array, simpleFullHex, false, false, 'hex', execaSync);94test('Splits lines when "binary" is false, objectMode, preserveNewlines, sync', testBinaryOption, false, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, 'utf8', execaSync);95test('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
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {getStdio} from '../helpers/stdio.js';5import {getOutputsGenerator, resultGenerator} from '../helpers/generator.js';6import {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';1819setFixtureDir();2021const windowsFull = 'aaa\r\nbbb\r\nccc';22const windowsFullEnd = `${windowsFull}\r\n`;23const windowsChunks = [windowsFull];24const windowsLines = ['aaa\r\n', 'bbb\r\n', 'ccc'];25const noNewlinesFullEnd = `${noNewlinesFull}\n`;26const noNewlinesLines = ['aaabbbccc'];27const singleChunks = [singleFull];28const noLines = [];29const emptyFull = '';30const emptyChunks = [emptyFull];31const manyEmptyChunks = [emptyFull, emptyFull, emptyFull];32const newlineFull = '\n';33const newlineChunks = [newlineFull];34const newlinesFull = '\n\n\n';35const newlinesChunks = [newlinesFull];36const newlinesLines = ['\n', '\n', '\n'];37const windowsNewlinesFull = '\r\n\r\n\r\n';38const windowsNewlinesChunks = [windowsNewlinesFull];39const windowsNewlinesLines = ['\r\n', '\r\n', '\r\n'];40const runOverChunks = ['aaa\nb', 'b', 'b\nccc'];41const bigFull = '.'.repeat(1e5);42const bigFullEnd = `${bigFull}\n`;43const bigChunks = [bigFull];44const manyChunks = Array.from({length: 1e3}).fill('.');45const manyFull = manyChunks.join('');46const manyFullEnd = `${manyFull}\n`;47const manyLines = [manyFull];4849// eslint-disable-next-line max-params50const 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};6263test('Split stdout - n newlines, 1 chunk', testLines, 1, simpleChunks, simpleLines, simpleFull, false, true, execa);64test('Split stderr - n newlines, 1 chunk', testLines, 2, simpleChunks, simpleLines, simpleFull, false, true, execa);65test('Split stdio[*] - n newlines, 1 chunk', testLines, 3, simpleChunks, simpleLines, simpleFull, false, true, execa);66test('Split stdout - preserveNewlines, n chunks', testLines, 1, noNewlinesChunks, noNewlinesLines, noNewlinesFull, false, true, execa);67test('Split stdout - 0 newlines, 1 chunk', testLines, 1, singleChunks, singleChunks, singleFull, false, true, execa);68test('Split stdout - empty, 1 chunk', testLines, 1, emptyChunks, noLines, emptyFull, false, true, execa);69test('Split stdout - Windows newlines', testLines, 1, windowsChunks, windowsLines, windowsFull, false, true, execa);70test('Split stdout - chunk ends with newline', testLines, 1, simpleFullEndChunks, simpleFullEndLines, simpleFullEnd, false, true, execa);71test('Split stdout - single newline', testLines, 1, newlineChunks, newlineChunks, newlineFull, false, true, execa);72test('Split stdout - only newlines', testLines, 1, newlinesChunks, newlinesLines, newlinesFull, false, true, execa);73test('Split stdout - only Windows newlines', testLines, 1, windowsNewlinesChunks, windowsNewlinesLines, windowsNewlinesFull, false, true, execa);74test('Split stdout - line split over multiple chunks', testLines, 1, runOverChunks, simpleLines, simpleFull, false, true, execa);75test('Split stdout - 0 newlines, big line', testLines, 1, bigChunks, bigChunks, bigFull, false, true, execa);76test('Split stdout - 0 newlines, many chunks', testLines, 1, manyChunks, manyLines, manyFull, false, true, execa);77test('Split stdout - n newlines, 1 chunk, objectMode', testLines, 1, simpleChunks, simpleLines, simpleLines, true, true, execa);78test('Split stderr - n newlines, 1 chunk, objectMode', testLines, 2, simpleChunks, simpleLines, simpleLines, true, true, execa);79test('Split stdio[*] - n newlines, 1 chunk, objectMode', testLines, 3, simpleChunks, simpleLines, simpleLines, true, true, execa);80test('Split stdout - preserveNewlines, n chunks, objectMode', testLines, 1, noNewlinesChunks, noNewlinesLines, noNewlinesLines, true, true, execa);81test('Split stdout - empty, 1 chunk, objectMode', testLines, 1, emptyChunks, noLines, noLines, true, true, execa);82test('Split stdout - 0 newlines, 1 chunk, objectMode', testLines, 1, singleChunks, singleChunks, singleChunks, true, true, execa);83test('Split stdout - Windows newlines, objectMode', testLines, 1, windowsChunks, windowsLines, windowsLines, true, true, execa);84test('Split stdout - chunk ends with newline, objectMode', testLines, 1, simpleFullEndChunks, simpleFullEndLines, simpleFullEndLines, true, true, execa);85test('Split stdout - single newline, objectMode', testLines, 1, newlineChunks, newlineChunks, newlineChunks, true, true, execa);86test('Split stdout - only newlines, objectMode', testLines, 1, newlinesChunks, newlinesLines, newlinesLines, true, true, execa);87test('Split stdout - only Windows newlines, objectMode', testLines, 1, windowsNewlinesChunks, windowsNewlinesLines, windowsNewlinesLines, true, true, execa);88test('Split stdout - line split over multiple chunks, objectMode', testLines, 1, runOverChunks, simpleLines, simpleLines, true, true, execa);89test('Split stdout - 0 newlines, big line, objectMode', testLines, 1, bigChunks, bigChunks, bigChunks, true, true, execa);90test('Split stdout - 0 newlines, many chunks, objectMode', testLines, 1, manyChunks, manyLines, manyLines, true, true, execa);91test('Split stdout - n newlines, 1 chunk, preserveNewlines', testLines, 1, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, execa);92test('Split stderr - n newlines, 1 chunk, preserveNewlines', testLines, 2, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, execa);93test('Split stdio[*] - n newlines, 1 chunk, preserveNewlines', testLines, 3, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, execa);94test('Split stdout - preserveNewlines, n chunks, preserveNewlines', testLines, 1, noNewlinesChunks, noNewlinesLines, noNewlinesFullEnd, false, false, execa);95test('Split stdout - empty, 1 chunk, preserveNewlines', testLines, 1, emptyChunks, noLines, emptyFull, false, false, execa);96test('Split stdout - 0 newlines, 1 chunk, preserveNewlines', testLines, 1, singleChunks, singleChunks, singleFullEnd, false, false, execa);97test('Split stdout - Windows newlines, preserveNewlines', testLines, 1, windowsChunks, noNewlinesChunks, windowsFullEnd, false, false, execa);98test('Split stdout - chunk ends with newline, preserveNewlines', testLines, 1, simpleFullEndChunks, noNewlinesChunks, simpleFullEnd, false, false, execa);99test('Split stdout - single newline, preserveNewlines', testLines, 1, newlineChunks, emptyChunks, newlineFull, false, false, execa);100test('Split stdout - only newlines, preserveNewlines', testLines, 1, newlinesChunks, manyEmptyChunks, newlinesFull, false, false, execa);101test('Split stdout - only Windows newlines, preserveNewlines', testLines, 1, windowsNewlinesChunks, manyEmptyChunks, windowsNewlinesFull, false, false, execa);102test('Split stdout - line split over multiple chunks, preserveNewlines', testLines, 1, runOverChunks, noNewlinesChunks, simpleFullEnd, false, false, execa);103test('Split stdout - 0 newlines, big line, preserveNewlines', testLines, 1, bigChunks, bigChunks, bigFullEnd, false, false, execa);104test('Split stdout - 0 newlines, many chunks, preserveNewlines', testLines, 1, manyChunks, manyLines, manyFullEnd, false, false, execa);105test('Split stdout - n newlines, 1 chunk, objectMode, preserveNewlines', testLines, 1, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, execa);106test('Split stderr - n newlines, 1 chunk, objectMode, preserveNewlines', testLines, 2, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, execa);107test('Split stdio[*] - n newlines, 1 chunk, objectMode, preserveNewlines', testLines, 3, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, execa);108test('Split stdout - preserveNewlines, n chunks, objectMode, preserveNewlines', testLines, 1, noNewlinesChunks, noNewlinesLines, noNewlinesLines, true, false, execa);109test('Split stdout - empty, 1 chunk, objectMode, preserveNewlines', testLines, 1, emptyChunks, noLines, noLines, true, false, execa);110test('Split stdout - 0 newlines, 1 chunk, objectMode, preserveNewlines', testLines, 1, singleChunks, singleChunks, singleChunks, true, false, execa);111test('Split stdout - Windows newlines, objectMode, preserveNewlines', testLines, 1, windowsChunks, noNewlinesChunks, noNewlinesChunks, true, false, execa);112test('Split stdout - chunk ends with newline, objectMode, preserveNewlines', testLines, 1, simpleFullEndChunks, noNewlinesChunks, noNewlinesChunks, true, false, execa);113test('Split stdout - single newline, objectMode, preserveNewlines', testLines, 1, newlineChunks, emptyChunks, emptyChunks, true, false, execa);114test('Split stdout - only newlines, objectMode, preserveNewlines', testLines, 1, newlinesChunks, manyEmptyChunks, manyEmptyChunks, true, false, execa);115test('Split stdout - only Windows newlines, objectMode, preserveNewlines', testLines, 1, windowsNewlinesChunks, manyEmptyChunks, manyEmptyChunks, true, false, execa);116test('Split stdout - line split over multiple chunks, objectMode, preserveNewlines', testLines, 1, runOverChunks, noNewlinesChunks, noNewlinesChunks, true, false, execa);117test('Split stdout - 0 newlines, big line, objectMode, preserveNewlines', testLines, 1, bigChunks, bigChunks, bigChunks, true, false, execa);118test('Split stdout - 0 newlines, many chunks, objectMode, preserveNewlines', testLines, 1, manyChunks, manyLines, manyLines, true, false, execa);119test('Split stdout - n newlines, 1 chunk, sync', testLines, 1, simpleChunks, simpleLines, simpleFull, false, true, execaSync);120test('Split stderr - n newlines, 1 chunk, sync', testLines, 2, simpleChunks, simpleLines, simpleFull, false, true, execaSync);121test('Split stdio[*] - n newlines, 1 chunk, sync', testLines, 3, simpleChunks, simpleLines, simpleFull, false, true, execaSync);122test('Split stdout - preserveNewlines, n chunks, sync', testLines, 1, noNewlinesChunks, noNewlinesLines, noNewlinesFull, false, true, execaSync);123test('Split stdout - 0 newlines, 1 chunk, sync', testLines, 1, singleChunks, singleChunks, singleFull, false, true, execaSync);124test('Split stdout - empty, 1 chunk, sync', testLines, 1, emptyChunks, noLines, emptyFull, false, true, execaSync);125test('Split stdout - Windows newlines, sync', testLines, 1, windowsChunks, windowsLines, windowsFull, false, true, execaSync);126test('Split stdout - chunk ends with newline, sync', testLines, 1, simpleFullEndChunks, simpleFullEndLines, simpleFullEnd, false, true, execaSync);127test('Split stdout - single newline, sync', testLines, 1, newlineChunks, newlineChunks, newlineFull, false, true, execaSync);128test('Split stdout - only newlines, sync', testLines, 1, newlinesChunks, newlinesLines, newlinesFull, false, true, execaSync);129test('Split stdout - only Windows newlines, sync', testLines, 1, windowsNewlinesChunks, windowsNewlinesLines, windowsNewlinesFull, false, true, execaSync);130test('Split stdout - line split over multiple chunks, sync', testLines, 1, runOverChunks, simpleLines, simpleFull, false, true, execaSync);131test('Split stdout - 0 newlines, big line, sync', testLines, 1, bigChunks, bigChunks, bigFull, false, true, execaSync);132test('Split stdout - 0 newlines, many chunks, sync', testLines, 1, manyChunks, manyLines, manyFull, false, true, execaSync);133test('Split stdout - n newlines, 1 chunk, objectMode, sync', testLines, 1, simpleChunks, simpleLines, simpleLines, true, true, execaSync);134test('Split stderr - n newlines, 1 chunk, objectMode, sync', testLines, 2, simpleChunks, simpleLines, simpleLines, true, true, execaSync);135test('Split stdio[*] - n newlines, 1 chunk, objectMode, sync', testLines, 3, simpleChunks, simpleLines, simpleLines, true, true, execaSync);136test('Split stdout - preserveNewlines, n chunks, objectMode, sync', testLines, 1, noNewlinesChunks, noNewlinesLines, noNewlinesLines, true, true, execaSync);137test('Split stdout - empty, 1 chunk, objectMode, sync', testLines, 1, emptyChunks, noLines, noLines, true, true, execaSync);138test('Split stdout - 0 newlines, 1 chunk, objectMode, sync', testLines, 1, singleChunks, singleChunks, singleChunks, true, true, execaSync);139test('Split stdout - Windows newlines, objectMode, sync', testLines, 1, windowsChunks, windowsLines, windowsLines, true, true, execaSync);140test('Split stdout - chunk ends with newline, objectMode, sync', testLines, 1, simpleFullEndChunks, simpleFullEndLines, simpleFullEndLines, true, true, execaSync);141test('Split stdout - single newline, objectMode, sync', testLines, 1, newlineChunks, newlineChunks, newlineChunks, true, true, execaSync);142test('Split stdout - only newlines, objectMode, sync', testLines, 1, newlinesChunks, newlinesLines, newlinesLines, true, true, execaSync);143test('Split stdout - only Windows newlines, objectMode, sync', testLines, 1, windowsNewlinesChunks, windowsNewlinesLines, windowsNewlinesLines, true, true, execaSync);144test('Split stdout - line split over multiple chunks, objectMode, sync', testLines, 1, runOverChunks, simpleLines, simpleLines, true, true, execaSync);145test('Split stdout - 0 newlines, big line, objectMode, sync', testLines, 1, bigChunks, bigChunks, bigChunks, true, true, execaSync);146test('Split stdout - 0 newlines, many chunks, objectMode, sync', testLines, 1, manyChunks, manyLines, manyLines, true, true, execaSync);147test('Split stdout - n newlines, 1 chunk, preserveNewlines, sync', testLines, 1, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, execaSync);148test('Split stderr - n newlines, 1 chunk, preserveNewlines, sync', testLines, 2, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, execaSync);149test('Split stdio[*] - n newlines, 1 chunk, preserveNewlines, sync', testLines, 3, simpleChunks, noNewlinesChunks, simpleFullEnd, false, false, execaSync);150test('Split stdout - preserveNewlines, n chunks, preserveNewlines, sync', testLines, 1, noNewlinesChunks, noNewlinesLines, noNewlinesFullEnd, false, false, execaSync);151test('Split stdout - empty, 1 chunk, preserveNewlines, sync', testLines, 1, emptyChunks, noLines, emptyFull, false, false, execaSync);152test('Split stdout - 0 newlines, 1 chunk, preserveNewlines, sync', testLines, 1, singleChunks, singleChunks, singleFullEnd, false, false, execaSync);153test('Split stdout - Windows newlines, preserveNewlines, sync', testLines, 1, windowsChunks, noNewlinesChunks, windowsFullEnd, false, false, execaSync);154test('Split stdout - chunk ends with newline, preserveNewlines, sync', testLines, 1, simpleFullEndChunks, noNewlinesChunks, simpleFullEnd, false, false, execaSync);155test('Split stdout - single newline, preserveNewlines, sync', testLines, 1, newlineChunks, emptyChunks, newlineFull, false, false, execaSync);156test('Split stdout - only newlines, preserveNewlines, sync', testLines, 1, newlinesChunks, manyEmptyChunks, newlinesFull, false, false, execaSync);157test('Split stdout - only Windows newlines, preserveNewlines, sync', testLines, 1, windowsNewlinesChunks, manyEmptyChunks, windowsNewlinesFull, false, false, execaSync);158test('Split stdout - line split over multiple chunks, preserveNewlines, sync', testLines, 1, runOverChunks, noNewlinesChunks, simpleFullEnd, false, false, execaSync);159test('Split stdout - 0 newlines, big line, preserveNewlines, sync', testLines, 1, bigChunks, bigChunks, bigFullEnd, false, false, execaSync);160test('Split stdout - 0 newlines, many chunks, preserveNewlines, sync', testLines, 1, manyChunks, manyLines, manyFullEnd, false, false, execaSync);161test('Split stdout - n newlines, 1 chunk, objectMode, preserveNewlines, sync', testLines, 1, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, execaSync);162test('Split stderr - n newlines, 1 chunk, objectMode, preserveNewlines, sync', testLines, 2, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, execaSync);163test('Split stdio[*] - n newlines, 1 chunk, objectMode, preserveNewlines, sync', testLines, 3, simpleChunks, noNewlinesChunks, noNewlinesChunks, true, false, execaSync);164test('Split stdout - preserveNewlines, n chunks, objectMode, preserveNewlines, sync', testLines, 1, noNewlinesChunks, noNewlinesLines, noNewlinesLines, true, false, execaSync);165test('Split stdout - empty, 1 chunk, objectMode, preserveNewlines, sync', testLines, 1, emptyChunks, noLines, noLines, true, false, execaSync);166test('Split stdout - 0 newlines, 1 chunk, objectMode, preserveNewlines, sync', testLines, 1, singleChunks, singleChunks, singleChunks, true, false, execaSync);167test('Split stdout - Windows newlines, objectMode, preserveNewlines, sync', testLines, 1, windowsChunks, noNewlinesChunks, noNewlinesChunks, true, false, execaSync);168test('Split stdout - chunk ends with newline, objectMode, preserveNewlines, sync', testLines, 1, simpleFullEndChunks, noNewlinesChunks, noNewlinesChunks, true, false, execaSync);169test('Split stdout - single newline, objectMode, preserveNewlines, sync', testLines, 1, newlineChunks, emptyChunks, emptyChunks, true, false, execaSync);170test('Split stdout - only newlines, objectMode, preserveNewlines, sync', testLines, 1, newlinesChunks, manyEmptyChunks, manyEmptyChunks, true, false, execaSync);171test('Split stdout - only Windows newlines, objectMode, preserveNewlines, sync', testLines, 1, windowsNewlinesChunks, manyEmptyChunks, manyEmptyChunks, true, false, execaSync);172test('Split stdout - line split over multiple chunks, objectMode, preserveNewlines, sync', testLines, 1, runOverChunks, noNewlinesChunks, noNewlinesChunks, true, false, execaSync);173test('Split stdout - 0 newlines, big line, objectMode, preserveNewlines, sync', testLines, 1, bigChunks, bigChunks, bigChunks, true, false, execaSync);174test('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
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {getOutputsGenerator, noopGenerator, noopAsyncGenerator} from '../helpers/generator.js';5import {singleFull, singleFullEnd} from '../helpers/lines.js';67setFixtureDir();89const singleFullEndWindows = `${singleFull}\r\n`;10const mixedNewlines = '.\n.\r\n.\n.\r\n.\n';1112const 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};1920test('Strips newline when user do not mistakenly yield one at the end', testStripNewline, singleFull, singleFullEnd, execa);21test('Strips newline when user mistakenly yielded one at the end', testStripNewline, singleFullEnd, singleFullEnd, execa);22test('Strips newline when user mistakenly yielded one at the end, Windows newline', testStripNewline, singleFullEndWindows, singleFullEndWindows, execa);23test('Strips newline when user do not mistakenly yield one at the end, sync', testStripNewline, singleFull, singleFullEnd, execaSync);24test('Strips newline when user mistakenly yielded one at the end, sync', testStripNewline, singleFullEnd, singleFullEnd, execaSync);25test('Strips newline when user mistakenly yielded one at the end, Windows newline, sync', testStripNewline, singleFullEndWindows, singleFullEndWindows, execaSync);2627const 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};3435test('Can mix Unix and Windows newlines', testMixNewlines, noopGenerator, execa);36test('Can mix Unix and Windows newlines, sync', testMixNewlines, noopGenerator, execaSync);37test('Can mix Unix and Windows newlines, async', testMixNewlines, noopAsyncGenerator, execa);
added:test/transform/split-transform.js+78 added
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {getOutputsGenerator, resultGenerator} from '../helpers/generator.js';5import {foobarString, foobarUint8Array, foobarObject, foobarObjectString} from '../helpers/input.js';67setFixtureDir();89const resultUint8ArrayGenerator = function * (lines, chunk) {10 lines.push(chunk);11 yield new TextEncoder().encode(chunk);12};1314// eslint-disable-next-line max-params15const 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};2829test('Line splitting when converting from string to Uint8Array', testStringToUint8Array, [foobarString], false, true, execa);30test('Line splitting when converting from string to Uint8Array, objectMode', testStringToUint8Array, [foobarUint8Array], true, true, execa);31test('Line splitting when converting from string to Uint8Array, preserveNewlines', testStringToUint8Array, [foobarString], false, false, execa);32test('Line splitting when converting from string to Uint8Array, objectMode, preserveNewlines', testStringToUint8Array, [foobarUint8Array], true, false, execa);33test('Line splitting when converting from string to Uint8Array, sync', testStringToUint8Array, [foobarString], false, true, execaSync);34test('Line splitting when converting from string to Uint8Array, objectMode, sync', testStringToUint8Array, [foobarUint8Array], true, true, execaSync);35test('Line splitting when converting from string to Uint8Array, preserveNewlines, sync', testStringToUint8Array, [foobarString], false, false, execaSync);36test('Line splitting when converting from string to Uint8Array, objectMode, preserveNewlines, sync', testStringToUint8Array, [foobarUint8Array], true, false, execaSync);3738const serializeResultGenerator = function * (lines, chunk) {39 lines.push(chunk);40 yield JSON.stringify(chunk);41};4243const 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};5556test('Can switch from objectMode to non-objectMode', testUnsetObjectMode, `${foobarObjectString}\n`, false, execa);57test('Can switch from objectMode to non-objectMode, preserveNewlines', testUnsetObjectMode, foobarObjectString, true, execa);58test('Can switch from objectMode to non-objectMode, sync', testUnsetObjectMode, `${foobarObjectString}\n`, false, execaSync);59test('Can switch from objectMode to non-objectMode, preserveNewlines, sync', testUnsetObjectMode, foobarObjectString, true, execaSync);6061// eslint-disable-next-line max-params62const 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};7475test('Can use "yield* array" to produce multiple lines', testYieldArray, [foobarString, foobarString], [foobarString, foobarString], `${foobarString}\n${foobarString}\n`, execa);76test('Can use "yield* array" to produce empty lines', testYieldArray, [foobarString, ''], [foobarString, ''], `${foobarString}\n\n`, execa);77test('Can use "yield* array" to produce multiple lines, sync', testYieldArray, [foobarString, foobarString], [foobarString, foobarString], `${foobarString}\n${foobarString}\n`, execaSync);78test('Can use "yield* array" to produce empty lines, sync', testYieldArray, [foobarString, ''], [foobarString, ''], `${foobarString}\n\n`, execaSync);
added:test/transform/validate.js+95 added
1import {Buffer} from 'node:buffer';2import test from 'ava';3import {execa, execaSync} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';5import {getStdio} from '../helpers/stdio.js';6import {foobarUint8Array, foobarBuffer, foobarObject} from '../helpers/input.js';7import {serializeGenerator, getOutputGenerator, convertTransformToFinal} from '../helpers/generator.js';89setFixtureDir();1011const getMessage = input => {12 if (input === null || input === undefined) {13 return 'not be called at all';14 }1516 if (Buffer.isBuffer(input)) {17 return 'not a buffer';18 }1920 return 'a string or an Uint8Array';21};2223const lastInputGenerator = input => objectMode => [foobarUint8Array, getOutputGenerator(input)(objectMode)];24const inputGenerator = input => objectMode => [...lastInputGenerator(input)(objectMode), serializeGenerator(true)];2526// eslint-disable-next-line max-params27const 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};3233test('Generators with result.stdin cannot return an object if not in objectMode', testGeneratorReturn, 0, inputGenerator, foobarObject, false, true);34test('Generators with result.stdio[*] as input cannot return an object if not in objectMode', testGeneratorReturn, 3, inputGenerator, foobarObject, false, true);35test('The last generator with result.stdin cannot return an object even in objectMode', testGeneratorReturn, 0, lastInputGenerator, foobarObject, true, true);36test('The last generator with result.stdio[*] as input cannot return an object even in objectMode', testGeneratorReturn, 3, lastInputGenerator, foobarObject, true, true);37test('Generators with result.stdout cannot return an object if not in objectMode', testGeneratorReturn, 1, getOutputGenerator, foobarObject, false, false);38test('Generators with result.stderr cannot return an object if not in objectMode', testGeneratorReturn, 2, getOutputGenerator, foobarObject, false, false);39test('Generators with result.stdio[*] as output cannot return an object if not in objectMode', testGeneratorReturn, 3, getOutputGenerator, foobarObject, false, false);40test('Generators with result.stdin cannot return a Buffer if not in objectMode', testGeneratorReturn, 0, inputGenerator, foobarBuffer, false, true);41test('Generators with result.stdio[*] as input cannot return a Buffer if not in objectMode', testGeneratorReturn, 3, inputGenerator, foobarBuffer, false, true);42test('The last generator with result.stdin cannot return a Buffer even in objectMode', testGeneratorReturn, 0, lastInputGenerator, foobarBuffer, true, true);43test('The last generator with result.stdio[*] as input cannot return a Buffer even in objectMode', testGeneratorReturn, 3, lastInputGenerator, foobarBuffer, true, true);44test('Generators with result.stdout cannot return a Buffer if not in objectMode', testGeneratorReturn, 1, getOutputGenerator, foobarBuffer, false, false);45test('Generators with result.stderr cannot return a Buffer if not in objectMode', testGeneratorReturn, 2, getOutputGenerator, foobarBuffer, false, false);46test('Generators with result.stdio[*] as output cannot return a Buffer if not in objectMode', testGeneratorReturn, 3, getOutputGenerator, foobarBuffer, false, false);47test('Generators with result.stdin cannot return null if not in objectMode', testGeneratorReturn, 0, inputGenerator, null, false, true);48test('Generators with result.stdin cannot return null if in objectMode', testGeneratorReturn, 0, inputGenerator, null, true, true);49test('Generators with result.stdout cannot return null if not in objectMode', testGeneratorReturn, 1, getOutputGenerator, null, false, false);50test('Generators with result.stdout cannot return null if in objectMode', testGeneratorReturn, 1, getOutputGenerator, null, true, false);51test('Generators with result.stdin cannot return undefined if not in objectMode', testGeneratorReturn, 0, inputGenerator, undefined, false, true);52test('Generators with result.stdin cannot return undefined if in objectMode', testGeneratorReturn, 0, inputGenerator, undefined, true, true);53test('Generators with result.stdout cannot return undefined if not in objectMode', testGeneratorReturn, 1, getOutputGenerator, undefined, false, false);54test('Generators with result.stdout cannot return undefined if in objectMode', testGeneratorReturn, 1, getOutputGenerator, undefined, true, false);5556// eslint-disable-next-line max-params57const 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};6465test('Generators with result.stdin cannot return an object if not in objectMode, sync', testGeneratorReturnSync, 0, inputGenerator, foobarObject, false, true);66test('The last generator with result.stdin cannot return an object even in objectMode, sync', testGeneratorReturnSync, 0, lastInputGenerator, foobarObject, true, true);67test('Generators with result.stdout cannot return an object if not in objectMode, sync', testGeneratorReturnSync, 1, getOutputGenerator, foobarObject, false, false);68test('Generators with result.stderr cannot return an object if not in objectMode, sync', testGeneratorReturnSync, 2, getOutputGenerator, foobarObject, false, false);69test('Generators with result.stdio[*] as output cannot return an object if not in objectMode, sync', testGeneratorReturnSync, 3, getOutputGenerator, foobarObject, false, false);70test('Generators with result.stdin cannot return a Buffer if not in objectMode, sync', testGeneratorReturnSync, 0, inputGenerator, foobarBuffer, false, true);71test('The last generator with result.stdin cannot return a Buffer even in objectMode, sync', testGeneratorReturnSync, 0, lastInputGenerator, foobarBuffer, true, true);72test('Generators with result.stdout cannot return a Buffer if not in objectMode, sync', testGeneratorReturnSync, 1, getOutputGenerator, foobarBuffer, false, false);73test('Generators with result.stderr cannot return a Buffer if not in objectMode, sync', testGeneratorReturnSync, 2, getOutputGenerator, foobarBuffer, false, false);74test('Generators with result.stdio[*] as output cannot return a Buffer if not in objectMode, sync', testGeneratorReturnSync, 3, getOutputGenerator, foobarBuffer, false, false);75test('Generators with result.stdin cannot return null if not in objectMode, sync', testGeneratorReturnSync, 0, inputGenerator, null, false, true);76test('Generators with result.stdin cannot return null if in objectMode, sync', testGeneratorReturnSync, 0, inputGenerator, null, true, true);77test('Generators with result.stdout cannot return null if not in objectMode, sync', testGeneratorReturnSync, 1, getOutputGenerator, null, false, false);78test('Generators with result.stdout cannot return null if in objectMode, sync', testGeneratorReturnSync, 1, getOutputGenerator, null, true, false);79test('Generators with result.stdin cannot return undefined if not in objectMode, sync', testGeneratorReturnSync, 0, inputGenerator, undefined, false, true);80test('Generators with result.stdin cannot return undefined if in objectMode, sync', testGeneratorReturnSync, 0, inputGenerator, undefined, true, true);81test('Generators with result.stdout cannot return undefined if not in objectMode, sync', testGeneratorReturnSync, 1, getOutputGenerator, undefined, false, false);82test('Generators with result.stdout cannot return undefined if in objectMode, sync', testGeneratorReturnSync, 1, getOutputGenerator, undefined, true, false);8384test('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});9091test('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
1import process from 'node:process';2import test from 'ava';3import {execa} from '../index.js';4import {setFixtureDir} from './helpers/fixtures-dir.js';56setFixtureDir();78const isWindows = process.platform === 'win32';910if (isWindows) {11 test('execa() - cmd file', async t => {12 const {stdout} = await execa('hello.cmd');13 t.is(stdout, 'Hello World');14 });1516 test('execa() - run cmd command', async t => {17 const {stdout} = await execa('cmd', ['/c', 'hello.cmd']);18 t.is(stdout, 'Hello World');19 });20}2122test('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
1import {join} from 'node:path';2import test from 'ava';3import {execaCommand, execaCommandSync} from '../index.js';4import {setFixtureDir, FIXTURES_DIR} from './helpers/fixtures-dir.js';5import {QUOTE} from './helpers/verbose.js';67setFixtureDir();8const STDIN_FIXTURE = join(FIXTURES_DIR, 'stdin.js');910test('execaCommand()', async t => {11 const {stdout} = await execaCommand('echo.js foo bar');12 t.is(stdout, 'foo\nbar');13});1415test('execaCommandSync()', t => {16 const {stdout} = execaCommandSync('echo.js foo bar');17 t.is(stdout, 'foo\nbar');18});1920test('execaCommand`...`', async t => {21 const {stdout} = await execaCommand`${'echo.js foo bar'}`;22 t.is(stdout, 'foo\nbar');23});2425test('execaCommandSync`...`', t => {26 const {stdout} = execaCommandSync`${'echo.js foo bar'}`;27 t.is(stdout, 'foo\nbar');28});2930test('execaCommand(options)`...`', async t => {31 const {stdout} = await execaCommand({stripFinalNewline: false})`${'echo.js foo bar'}`;32 t.is(stdout, 'foo\nbar\n');33});3435test('execaCommandSync(options)`...`', t => {36 const {stdout} = execaCommandSync({stripFinalNewline: false})`${'echo.js foo bar'}`;37 t.is(stdout, 'foo\nbar\n');38});3940test('execaCommand(options)()', async t => {41 const {stdout} = await execaCommand({stripFinalNewline: false})('echo.js foo bar');42 t.is(stdout, 'foo\nbar\n');43});4445test('execaCommandSync(options)()', t => {46 const {stdout} = execaCommandSync({stripFinalNewline: false})('echo.js foo bar');47 t.is(stdout, 'foo\nbar\n');48});4950test('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});5455test('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});5960test('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});6465test('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});6970test('execaCommand() ignores consecutive spaces', async t => {71 const {stdout} = await execaCommand('echo.js foo bar');72 t.is(stdout, 'foo\nbar');73});7475test('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});7980test('execaCommand() allows escaping spaces in arguments', async t => {81 const {stdout} = await execaCommand('echo.js foo\\ bar');82 t.is(stdout, 'foo bar');83});8485test('execaCommand() escapes other whitespaces', async t => {86 const {stdout} = await execaCommand('echo.js foo\tbar');87 t.is(stdout, 'foo\tbar');88});8990test('execaCommand() trims', async t => {91 const {stdout} = await execaCommand(' echo.js foo bar ');92 t.is(stdout, 'foo\nbar');93});9495const 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};100101test('execaCommand() must not pass an array of arguments', testInvalidArgsArray, execaCommand);102test('execaCommandSync() must not pass an array of arguments', testInvalidArgsArray, execaCommandSync);103104const 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};110111test('execaCommand() must not pass an array of arguments with a template string', testInvalidArgsTemplate, execaCommand);112test('execaCommandSync() must not pass an array of arguments with a template string', testInvalidArgsTemplate, execaCommandSync);
deleted:test/override-promise.js-14 removed
1import test from 'ava';2// The helper module overrides Promise on import so has to be imported before `execa`.3import {restorePromise} from './helpers/override-promise.js';4// eslint-disable-next-line import/order5import {execa} from '../index.js';6import {setFixtureDir} from './helpers/fixtures-dir.js';78restorePromise();9setFixtureDir();1011test('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
1import test from 'ava';2import {execa} from '../index.js';3import {setFixtureDir} from './helpers/fixtures-dir.js';45setFixtureDir();67test('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});1314test('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});2223test('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});3233test('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});3940test('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});4647const 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};5152test('Throws if promise is not awaited and subprocess fails', testNoAwait, 'fail.js', {}, 'exit code 2');53test('Throws if promise is not awaited and subprocess times out', testNoAwait, 'forever.js', {timeout: 1}, 'timed out');
deleted:test/script.js-59 removed
1import test from 'ava';2import {isStream} from 'is-stream';3import {$} from '../index.js';4import {setFixtureDir} from './helpers/fixtures-dir.js';5import {foobarString} from './helpers/input.js';67setFixtureDir();89const testScriptStdoutSync = (t, getSubprocess, expectedStdout) => {10 const {stdout} = getSubprocess();11 t.is(stdout, expectedStdout);12};1314test('$.sync`...`', testScriptStdoutSync, () => $.sync`echo.js foo bar`, 'foo\nbar');15test('$.s`...`', testScriptStdoutSync, () => $.s`echo.js foo bar`, 'foo\nbar');16test('$(options).sync`...`', testScriptStdoutSync, () => $({stripFinalNewline: false}).sync`echo.js ${foobarString}`, `${foobarString}\n`);17test('$.sync(options)`...`', testScriptStdoutSync, () => $.sync({stripFinalNewline: false})`echo.js ${foobarString}`, `${foobarString}\n`);1819test('Cannot call $.sync.sync', t => {20 t.false('sync' in $.sync);21});2223test('Cannot call $.sync(options).sync', t => {24 t.false('sync' in $.sync({}));25});2627test('$(options)() stdin defaults to "inherit"', async t => {28 const {stdout} = await $({input: foobarString})('stdin-script.js');29 t.is(stdout, foobarString);30});3132test('$.sync(options)() stdin defaults to "inherit"', t => {33 const {stdout} = $.sync({input: foobarString})('stdin-script.js');34 t.is(stdout, foobarString);35});3637test('$(options).sync() stdin defaults to "inherit"', t => {38 const {stdout} = $({input: foobarString}).sync('stdin-script.js');39 t.is(stdout, foobarString);40});4142test('$(options)`...` stdin defaults to "inherit"', async t => {43 const {stdout} = await $({input: foobarString})`stdin-script.js`;44 t.is(stdout, foobarString);45});4647test('$.sync(options)`...` stdin defaults to "inherit"', t => {48 const {stdout} = $.sync({input: foobarString})`stdin-script.js`;49 t.is(stdout, foobarString);50});5152test('$(options).sync`...` stdin defaults to "inherit"', t => {53 const {stdout} = $({input: foobarString}).sync`stdin-script.js`;54 t.is(stdout, foobarString);55});5657test('$ 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
1import {createExeca} from './lib/arguments/create.js';2import {mapCommandAsync, mapCommandSync} from './lib/command.js';3import {mapNode} from './lib/arguments/node.js';4import {mapScriptAsync, setScriptSync, deepScriptOptions} from './lib/script.js';1import {createExeca} from './lib/methods/create.js';2import {mapCommandAsync, mapCommandSync} from './lib/methods/command.js';3import {mapNode} from './lib/methods/node.js';4import {mapScriptAsync, setScriptSync, deepScriptOptions} from './lib/methods/script.js';56export {ExecaError, ExecaSyncError} from './lib/return/cause.js';6export {ExecaError, ExecaSyncError} from './lib/return/final-error.js';78export const execa = createExeca(() => ({}));9export const execaSync = createExeca(() => ({isSync: true}));10export const execaCommand = createExeca(mapCommandAsync);
3 unmodified lines