Skip to content
Myr

Allow any type with transforms (#709)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by ehmicky · committed by GitHub · parent f8dffc1 · Browse files · 29 files+1107 added−418 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

29 files+1107 added−418 removed

  • tests:+589 added−243 removed
  • other:+518 added−175 removed

29 files+1107 added−418 removed

modified:docs/transform.md+30 added
modified:lib/stdio/async.js+2 added-7 removed
modified:lib/stdio/duplex.js+10 added-4 removed
9 unmodified lines
10 Those convert the chunk type from `Buffer` to `string | Uint8Array` depending on the encoding option.11- This new iterable is transformed again to another one, this time by applying the user-supplied generator.12- Finally, `Readable.from()` is used to convert this final iterable to a `Readable` stream.13*/14export const generatorsToDuplex = (generators, {objectMode}) => {15 const highWaterMark = getDefaultHighWaterMark(objectMode);16 const passThrough = new PassThrough({objectMode, highWaterMark, destroy: destroyPassThrough});14export const generatorsToDuplex = (generators, {writableObjectMode, readableObjectMode}) => {15 const passThrough = new PassThrough({16 objectMode: writableObjectMode,17 highWaterMark: getDefaultHighWaterMark(writableObjectMode),18 destroy: destroyPassThrough,19 });20 let iterable = passThrough.iterator();2122 for (const generator of generators) {23 iterable = generator(iterable);24 }2523 const readableStream = Readable.from(iterable, {objectMode, highWaterMark});26 const readableStream = Readable.from(iterable, {27 objectMode: readableObjectMode,28 highWaterMark: getDefaultHighWaterMark(readableObjectMode),29 });30 const duplexStream = Duplex.from({writable: passThrough, readable: readableStream});31 return duplexStream;32};33
16 unmodified lines
modified:lib/stdio/encoding.js+16 added-3 removed
1import {StringDecoder} from 'node:string_decoder';2import {Buffer} from 'node:buffer';3import {isUint8Array} from './utils.js';45// Apply the `encoding` option using an implicit generator.6// This encodes the final output of `stdout`/`stderr`.7export const handleStreamsEncoding = (stdioStreams, {encoding}, isSync) => {
1 unmodified line
9 return stdioStreams.map(stdioStream => ({...stdioStream, encoding}));10 }1112 const transform = encodingEndGenerator.bind(undefined, encoding);13 const objectMode = stdioStreams.findLast(({type}) => type === 'generator')?.value.readableObjectMode === true;14 return [15 ...stdioStreams,16 {17 ...stdioStreams[0],18 type: 'generator',16 value: {transform, binary: true},19 value: {transform, binary: true, readableObjectMode: objectMode, writableObjectMode: objectMode},20 encoding: 'buffer',21 },22 ];23};
30 unmodified lines
54 ? encodingStartBufferGenerator55 : encodingStartStringGenerator;5657const encodingStartBufferGenerator = async function * (chunks) {58 const textEncoder = new TextEncoder();5960 for await (const chunk of chunks) {61 if (Buffer.isBuffer(chunk)) {56 yield new Uint8Array(chunk);62 yield new Uint8Array(chunk);63 } else if (typeof chunk === 'string') {64 yield textEncoder.encode(chunk);65 } else {66 yield chunk;67 }68 }69};7071const encodingStartStringGenerator = async function * (chunks) {72 const textDecoder = new TextDecoder();7374 for await (const chunk of chunks) {64 yield textDecoder.decode(chunk, {stream: true});75 yield Buffer.isBuffer(chunk) || isUint8Array(chunk)76 ? textDecoder.decode(chunk, {stream: true})77 : chunk;78 }7980 const lastChunk = textDecoder.decode();81 if (lastChunk !== '') {
3 unmodified lines
modified:lib/stdio/generator.js+68 added-5 removed
1import {generatorsToDuplex} from './duplex.js';2import {getEncodingStartGenerator} from './encoding.js';3import {getLinesGenerator} from './lines.js';4import {isGeneratorOptions} from './type.js';5import {isBinary} from './utils.js';67export const normalizeGenerators = stdioStreams => {8 const nonGenerators = stdioStreams.filter(({type}) => type !== 'generator');9 const generators = stdioStreams.filter(({type}) => type === 'generator');1011 const newGenerators = Array.from({length: generators.length});1213 for (const [index, stdioStream] of Object.entries(generators)) {14 newGenerators[index] = normalizeGenerator(stdioStream, Number(index), newGenerators);15 }1617 return [...nonGenerators, ...sortGenerators(newGenerators)];18};1920const normalizeGenerator = ({value, ...stdioStream}, index, newGenerators) => {21 const {transform, binary = false, objectMode = false} = isGeneratorOptions(value) ? value : {transform: value};22 const objectModes = stdioStream.direction === 'output'23 ? getOutputObjectModes(objectMode, index, newGenerators)24 : getInputObjectModes(objectMode, index, newGenerators);25 return {...stdioStream, value: {transform, binary, ...objectModes}};26};2728/*29`objectMode` determines the return value's type, i.e. the `readableObjectMode`.30The chunk argument's type is based on the previous generator's return value, i.e. the `writableObjectMode` is based on the previous `readableObjectMode`.31The last input's generator is read by `childProcess.stdin` which:32- should not be in `objectMode` for performance reasons.33- can only be strings, Buffers and Uint8Arrays.34Therefore its `readableObjectMode` must be `false`.35The same applies to the first output's generator's `writableObjectMode`.36*/37const getOutputObjectModes = (objectMode, index, newGenerators) => {38 const writableObjectMode = index !== 0 && newGenerators[index - 1].value.readableObjectMode;39 const readableObjectMode = objectMode;40 return {writableObjectMode, readableObjectMode};41};4243const getInputObjectModes = (objectMode, index, newGenerators) => {44 const writableObjectMode = index === 045 ? objectMode46 : newGenerators[index - 1].value.readableObjectMode;47 const readableObjectMode = index !== newGenerators.length - 1 && objectMode;48 return {writableObjectMode, readableObjectMode};49};5051const sortGenerators = newGenerators => newGenerators[0]?.direction === 'input' ? newGenerators.reverse() : newGenerators;5253/*54Generators can be used to transform/filter standard streams.5556Generators have a simple syntax, yet allows all of the following:57- Sharing state between chunks, by using logic before the `for` loop
5 unmodified lines
63Therefore, there is no need to allow Node.js or web transform streams.6465The `highWaterMark` is kept as the default value, since this is what `childProcess.std*` uses.6620We ensure `objectMode` is `false` for better buffering.2167Chunks are currently processed serially. We could add a `concurrency` option to parallelize in the future.68*/24export const generatorToDuplexStream = ({value, encoding}) => {25 const {transform, binary} = isGeneratorOptions(value) ? value : {transform: value};69export const generatorToDuplexStream = ({70 value: {transform, binary, writableObjectMode, readableObjectMode},71 encoding,72 optionName,73}) => {74 const generators = [75 getEncodingStartGenerator(encoding),76 getLinesGenerator(encoding, binary),77 transform,78 getValidateTransformReturn(readableObjectMode, optionName),79 ].filter(Boolean);31 const duplexStream = generatorsToDuplex(generators, {objectMode: false});80 const duplexStream = generatorsToDuplex(generators, {writableObjectMode, readableObjectMode});81 return {value: duplexStream};82};8384const getValidateTransformReturn = (readableObjectMode, optionName) => readableObjectMode85 ? undefined86 : validateTransformReturn.bind(undefined, optionName);8788const validateTransformReturn = async function * (optionName, chunks) {89 for await (const chunk of chunks) {90 if (typeof chunk !== 'string' && !isBinary(chunk)) {91 throw new Error(`The \`${optionName}\` option's function must return a string or an Uint8Array, not ${typeof chunk}.`);92 }9394 yield chunk;95 }96};9798// `childProcess.stdin|stdout|stderr|stdio` is directly mutated.99export const pipeGenerator = (spawned, {value, direction, index}) => {100 if (direction === 'output') {101 spawned.stdio[index].pipe(value);
13 unmodified lines
modified:lib/stdio/handle.js+2 added
2 unmodified lines
3import {normalizeStdio} from './normalize.js';4import {handleNativeStream} from './native.js';5import {handleInputOptions} from './input.js';6import {handleStreamsEncoding} from './encoding.js';7import {normalizeGenerators} from './generator.js';89// Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in async/sync mode10export const handleInput = (addProperties, options, isSync) => {11 const stdio = normalizeStdio(options);12 const [stdinStreams, ...otherStreamsGroups] = stdio.map((stdioOption, index) => getStdioStreams(stdioOption, index));13 const stdioStreamsGroups = [[...stdinStreams, ...handleInputOptions(options)], ...otherStreamsGroups]14 .map(stdioStreams => validateStreams(stdioStreams))15 .map(stdioStreams => addStreamDirection(stdioStreams))16 .map(stdioStreams => normalizeGenerators(stdioStreams))17 .map(stdioStreams => handleStreamsEncoding(stdioStreams, options, isSync))18 .map(stdioStreams => addStreamsProperties(stdioStreams, addProperties));19 options.stdio = transformStdio(stdioStreamsGroups);20 return stdioStreamsGroups;
87 unmodified lines
modified:lib/stdio/lines.js+23 added-3 removed
1import {isUint8Array} from './utils.js';23// Split chunks line-wise4export const getLinesGenerator = (encoding, binary) => {5 if (binary) {6 return;
2 unmodified lines
9 return encoding === 'buffer' ? linesUint8ArrayGenerator : linesStringGenerator;10};1112const linesUint8ArrayGenerator = async function * (chunks) {11 yield * linesGenerator(chunks, new Uint8Array(0), 0x0A, concatUint8Array);13 yield * linesGenerator({14 chunks,15 emptyValue: new Uint8Array(0),16 newline: 0x0A,17 concat: concatUint8Array,18 isValidType: isUint8Array,19 });20};2122const concatUint8Array = (firstChunk, secondChunk) => {23 const chunk = new Uint8Array(firstChunk.length + secondChunk.length);
2 unmodified lines
26 return chunk;27};2829const linesStringGenerator = async function * (chunks) {22 yield * linesGenerator(chunks, '', '\n', concatString);30 yield * linesGenerator({31 chunks,32 emptyValue: '',33 newline: '\n',34 concat: concatString,35 isValidType: isString,36 });37};3839const concatString = (firstChunk, secondChunk) => `${firstChunk}${secondChunk}`;40const isString = chunk => typeof chunk === 'string';4142// This imperative logic is much faster than using `String.split()` and uses very low memory.43// Also, it allows sharing it with `Uint8Array`.29const linesGenerator = async function * (chunks, emptyValue, newline, concat) {44const linesGenerator = async function * ({chunks, emptyValue, newline, concat, isValidType}) {45 let previousChunks = emptyValue;4647 for await (const chunk of chunks) {48 if (!isValidType(chunk)) {49 yield chunk;50 continue;51 }5253 let start = -1;5455 for (let end = 0; end < chunk.length; end += 1) {56 if (chunk[end] === newline) {
21 unmodified lines
modified:lib/stdio/sync.js+2 added-2 removed
1import {readFileSync, writeFileSync} from 'node:fs';2import {handleInput} from './handle.js';3import {TYPE_TO_MESSAGE} from './type.js';4import {bufferToUint8Array} from './utils.js';4import {bufferToUint8Array, binaryToString} from './utils.js';56// Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in sync mode7export const handleInputSync = options => {8 const stdioStreamsGroups = handleInput(addPropertiesSync, options, true);
34 unmodified lines
43 ? inputs[0].value44 : inputs.map(stdioStream => serializeInput(stdioStream)).join('');45};4647const serializeInput = ({type, value}) => type === 'string' ? value : new TextDecoder().decode(value);47const serializeInput = ({type, value}) => type === 'string' ? value : binaryToString(value);4849// Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, after spawning, in sync mode50export const pipeOutputSync = (stdioStreamsGroups, result) => {51 if (result.output === null) {
19 unmodified lines
modified:lib/stdio/type.js+9 added-5 removed
40 unmodified lines
4142 return 'native';43};4445const getGeneratorObjectType = ({transform, binary}, optionName) => {45const getGeneratorObjectType = ({transform, binary, objectMode}, optionName) => {46 if (!isAsyncGenerator(transform)) {47 throw new TypeError(`The \`${optionName}.transform\` option must use an asynchronous generator.`);48 }4950 if (binary !== undefined && typeof binary !== 'boolean') {51 throw new TypeError(`The \`${optionName}.binary\` option must use a boolean.`);52 }50 checkBooleanOption(binary, `${optionName}.binary`);51 checkBooleanOption(objectMode, `${optionName}.objectMode`);5253 return 'generator';54};5556const checkBooleanOption = (value, optionName) => {57 if (value !== undefined && typeof value !== 'boolean') {58 throw new TypeError(`The \`${optionName}\` option must use a boolean.`);59 }60};6162const isAsyncGenerator = stdioOption => Object.prototype.toString.call(stdioOption) === '[object AsyncGeneratorFunction]';63const isSyncGenerator = stdioOption => Object.prototype.toString.call(stdioOption) === '[object GeneratorFunction]';64export const isGeneratorOptions = stdioOption => typeof stdioOption === 'object'65 && stdioOption !== null
16 unmodified lines
82const isWebStream = stdioOption => isReadableStream(stdioOption) || isWritableStream(stdioOption);8384const isIterableObject = stdioOption => typeof stdioOption === 'object'85 && stdioOption !== null81 && !Array.isArray(stdioOption)86 && (typeof stdioOption[Symbol.asyncIterator] === 'function' || typeof stdioOption[Symbol.iterator] === 'function');8788// Convert types to human-friendly strings for error messages89export const TYPE_TO_MESSAGE = {
10 unmodified lines
modified:lib/stdio/utils.js+4 added
1 unmodified line
23export const bufferToUint8Array = buffer => new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);45export const isUint8Array = value => Object.prototype.toString.call(value) === '[object Uint8Array]' && !Buffer.isBuffer(value);6export const isBinary = value => isUint8Array(value) || Buffer.isBuffer(value);78const textDecoder = new TextDecoder();9export const binaryToString = uint8ArrayOrBuffer => textDecoder.decode(uint8ArrayOrBuffer);
modified:lib/command.js+3 added-2 removed
1import {ChildProcess} from 'node:child_process';2import {isBinary, binaryToString} from './stdio/utils.js';34const normalizeArgs = (file, args = []) => {5 if (!Array.isArray(args)) {6 return [file];
57 unmodified lines
64 if (typeOfStdout === 'string') {65 return expression.stdout;66 }6767 if (ArrayBuffer.isView(expression.stdout)) {68 return new TextDecoder().decode(expression.stdout);68 if (isBinary(expression.stdout)) {69 return binaryToString(expression.stdout);70 }7172 throw new TypeError(`Unexpected "${typeOfStdout}" stdout in template expression`);73 }
46 unmodified lines
modified:lib/error.js+10 added-6 removed
1import process from 'node:process';2import {signalsByName} from 'human-signals';3import stripFinalNewline from 'strip-final-newline';4import {isUint8Array} from './stdio/utils.js';4import {isBinary, binaryToString} from './stdio/utils.js';56const getErrorPrefix = ({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}) => {7 if (timedOut) {8 return `timed out after ${timeout} milliseconds`;
17 unmodified lines
2627 return 'failed';28};2930const serializeMessagePart = messagePart => Array.isArray(messagePart)31 ? messagePart.map(messageItem => serializeMessageItem(messageItem)).join('')32 : serializeMessageItem(messagePart);3330const serializeMessagePart = messagePart => {31 if (typeof messagePart === 'string') {32 return messagePart;34const serializeMessageItem = messageItem => {35 if (typeof messageItem === 'string') {36 return messageItem;37 }3835 if (isUint8Array(messagePart)) {36 return new TextDecoder().decode(messagePart);39 if (isBinary(messageItem)) {40 return binaryToString(messageItem);41 }4243 return '';44};
64 unmodified lines
modified:lib/stream.js+37 added-7 removed
1import {once} from 'node:events';2import {finished} from 'node:stream/promises';3import getStream, {getStreamAsArrayBuffer} from 'get-stream';3import getStream, {getStreamAsArrayBuffer, getStreamAsArray} from 'get-stream';4import mergeStreams from '@sindresorhus/merge-streams';5import {throwOnTimeout, cleanupOnExit} from './kill.js';6import {STANDARD_STREAMS} from './stdio/native.js';7import {generatorToDuplexStream} from './stdio/generator.js';89// `all` interleaves `stdout` and `stderr`10export const makeAllStream = ({stdout, stderr}, {all}) => all && (stdout || stderr)11 ? mergeStreams([stdout, stderr].filter(Boolean))
6 unmodified lines
18const getBufferedData = async (streamPromise, encoding) => {19 try {20 return await streamPromise;21 } catch (error) {21 return error.bufferedData === undefined ? undefined : applyEncoding(error.bufferedData, encoding);22 return error.bufferedData === undefined || Array.isArray(error.bufferedData)23 ? error.bufferedData24 : applyEncoding(error.bufferedData, encoding);25 }26};2725const getStdioPromise = ({stream, index, stdioStreamsGroups, encoding, buffer, maxBuffer}) => stdioStreamsGroups[index]?.[0]?.direction === 'output'26 ? getStreamPromise(stream, {encoding, buffer, maxBuffer})28const getStdioPromise = ({stream, stdioStreams, encoding, buffer, maxBuffer}) => stdioStreams[0].direction === 'output'29 ? getStreamPromise({stream, encoding, buffer, maxBuffer, objectMode: stream?.readableObjectMode})30 : undefined;3129const getStreamPromise = async (stream, {encoding, buffer, maxBuffer}) => {32const getAllPromise = ({spawned, encoding, buffer, maxBuffer}) => {33 const stream = getAllStream(spawned, encoding);34 const objectMode = spawned.stdout?.readableObjectMode || spawned.stderr?.readableObjectMode;35 return getStreamPromise({stream, encoding, buffer, maxBuffer, objectMode});36};3738// When `childProcess.stdout` is in objectMode but not `childProcess.stderr` (or the opposite), we need to use both:39// - `getStreamAsArray()` for the chunks in objectMode, to return as an array without changing each chunk40// - `getStreamAsArrayBuffer()` or `getStream()` for the chunks not in objectMode, to convert them from Buffers to string or Uint8Array41// We do this by emulating the Buffer -> string|Uint8Array conversion performed by `get-stream` with our own, which is identical.42const getAllStream = ({all, stdout, stderr}, encoding) => all && stdout && stderr && stdout.readableObjectMode !== stderr.readableObjectMode43 ? all.pipe(generatorToDuplexStream({value: allStreamGenerator, encoding}).value)44 : all;4546const allStreamGenerator = {47 async * transform(chunks) {48 yield * chunks;49 },50 binary: true,51 writableObjectMode: true,52 readableObjectMode: true,53};5455const getStreamPromise = async ({stream, encoding, buffer, maxBuffer, objectMode}) => {56 if (!stream || !buffer) {57 return;58 }5960 if (objectMode) {61 return getStreamAsArray(stream, {maxBuffer});62 }6364 const contents = encoding === 'buffer'65 ? await getStreamAsArrayBuffer(stream, {maxBuffer})66 : await getStream(stream, {maxBuffer});67 return applyEncoding(contents, encoding);
51 unmodified lines
119 const finalizers = [];120 cleanupOnExit(spawned, cleanup, detached, finalizers);121 const customStreams = getCustomStreams(stdioStreamsGroups);12293 const stdioPromises = spawned.stdio.map((stream, index) => getStdioPromise({stream, index, stdioStreamsGroups, encoding, buffer, maxBuffer}));94 const allPromise = getStreamPromise(spawned.all, {encoding, buffer, maxBuffer: maxBuffer * 2});123 const stdioPromises = spawned.stdio.map((stream, index) => getStdioPromise({stream, stdioStreams: stdioStreamsGroups[index], encoding, buffer, maxBuffer}));124 const allPromise = getAllPromise({spawned, encoding, buffer, maxBuffer: maxBuffer * 2});125126 try {127 return await Promise.race([128 Promise.all([
24 unmodified lines
modified:test/helpers/generator.js+33 added-28 removed
1import {setTimeout} from 'node:timers/promises';1import {foobarObject} from './input.js';23export const stringGenerator = function * () {4 yield * ['foo', 'bar'];5};3export const noopGenerator = objectMode => ({4 async * transform(lines) {5 yield * lines;6 },7 objectMode,8});97const textEncoder = new TextEncoder();8const binaryFoo = textEncoder.encode('foo');9const binaryBar = textEncoder.encode('bar');1011export const binaryGenerator = function * () {12 yield * [binaryFoo, binaryBar];10export const serializeGenerator = {11 async * transform(objects) {12 for await (const object of objects) {13 yield JSON.stringify(object);14 }15 },16 objectMode: true,17};1815export const asyncGenerator = async function * () {16 await setTimeout(0);17 yield * ['foo', 'bar'];18};19export const getOutputsGenerator = (inputs, objectMode) => ({20 async * transform(lines) {21 // eslint-disable-next-line no-unused-vars22 for await (const line of lines) {23 yield * inputs;24 }25 },26 objectMode,27});2820// eslint-disable-next-line require-yield21export const throwingGenerator = function * () {22 throw new Error('generator error');23};29export const getOutputGenerator = (input, objectMode) => ({30 async * transform(lines) {31 // eslint-disable-next-line no-unused-vars32 for await (const line of lines) {33 yield input;34 }35 },36 objectMode,37});3825export const infiniteGenerator = () => {26 const controller = new AbortController();2728 const generator = async function * () {29 yield 'foo';30 await setTimeout(1e7, undefined, {signal: controller.signal});31 };3233 return {iterable: generator(), abort: controller.abort.bind(controller)};34};39export const outputObjectGenerator = getOutputGenerator(foobarObject, true);
added:test/helpers/input.js+12 added
1import {Buffer} from 'node:buffer';23const textEncoder = new TextEncoder();45export const foobarString = 'foobar';6export const foobarUint8Array = textEncoder.encode('foobar');7export const foobarArrayBuffer = foobarUint8Array.buffer;8export const foobarUint16Array = new Uint16Array(foobarArrayBuffer);9export const foobarBuffer = Buffer.from(foobarString);10export const foobarDataView = new DataView(foobarArrayBuffer);11export const foobarObject = {foo: 'bar'};12export const foobarObjectString = JSON.stringify(foobarObject);
modified:test/stdio/array.js+1 added-2 removed
2 unmodified lines
3import test from 'ava';4import tempfile from 'tempfile';5import {execa, execaSync} from '../../index.js';6import {fullStdio, getStdio, STANDARD_STREAMS} from '../helpers/stdio.js';7import {stringGenerator} from '../helpers/generator.js';7import {setFixtureDir} from '../helpers/fixtures-dir.js';89setFixtureDir();10
110 unmodified lines
121122const testAmbiguousMultiple = async (t, index) => {123 const filePath = tempfile();124 await writeFile(filePath, 'foobar');126 const {stdout} = await execa('stdin-fd.js', [`${index}`], getStdio(index, [{file: filePath}, stringGenerator()]));125 const {stdout} = await execa('stdin-fd.js', [`${index}`], getStdio(index, [{file: filePath}, ['foo', 'bar']]));126 t.is(stdout, 'foobarfoobar');127 await rm(filePath);128};129
125 unmodified lines
modified:test/stdio/encoding.js+7 added-4 removed
143 unmodified lines
144 yield foobarArray[3];145 }146};147148test('Handle multibyte characters', async t => {149 const {stdout} = await execa('noop.js', {stdout: delayedGenerator, encoding: 'base64'});150 t.is(stdout, btoa(foobarArray.join('')));151});148const testMultiByteCharacter = async (t, objectMode) => {149 const {stdout} = await execa('noop.js', {stdout: {transform: delayedGenerator, objectMode}, encoding: 'base64'});150 t.is(objectMode ? stdout.join('') : stdout, btoa(foobarArray.join('')));151};152153test('Handle multibyte characters', testMultiByteCharacter, false);154test('Handle multibyte characters, with objectMode', testMultiByteCharacter, true);
modified:test/stdio/file-path.js+2 added-3 removed
6 unmodified lines
7import {execa, execaSync} from '../../index.js';8import {setFixtureDir} from '../helpers/fixtures-dir.js';9import {identity, getStdio} from '../helpers/stdio.js';10import {runExeca, runExecaSync, runScript, runScriptSync} from '../helpers/run.js';11import {foobarUint8Array} from '../helpers/input.js';1213setFixtureDir();1414const textEncoder = new TextEncoder();15const binaryFoobar = textEncoder.encode('foobar');15const nonFileUrl = new URL('https://example.com');1617const getAbsolutePath = file => ({file});18const getRelativePath = filePath => ({file: relative('.', filePath)});
5 unmodified lines
24 return {input: 'foobar'};25 }2627 if (index === 'binary') {29 return {input: binaryFoobar};28 return {input: foobarUint8Array};29 }3031 return getStdioFile(index, file);32};
171 unmodified lines
modified:test/stdio/generator.js+349 added-130 removed
1 unmodified line
2import {readFile, writeFile, rm} from 'node:fs/promises';3import {getDefaultHighWaterMark, PassThrough} from 'node:stream';4import {setTimeout} from 'node:timers/promises';5import test from 'ava';6import getStream from 'get-stream';6import getStream, {getStreamAsArray} from 'get-stream';7import tempfile from 'tempfile';8import {execa, execaSync} from '../../index.js';9import {setFixtureDir} from '../helpers/fixtures-dir.js';10import {getStdio} from '../helpers/stdio.js';11import {foobarString, foobarUint8Array, foobarBuffer, foobarObject, foobarObjectString} from '../helpers/input.js';12import {serializeGenerator, noopGenerator, getOutputsGenerator, getOutputGenerator, outputObjectGenerator} from '../helpers/generator.js';1314setFixtureDir();1514const foobarString = 'foobar';16const textEncoder = new TextEncoder();17const textDecoder = new TextDecoder();1819const foobarUppercase = foobarString.toUpperCase();16const foobarBuffer = Buffer.from(foobarString);17const foobarUint8Array = new TextEncoder().encode(foobarString);20const foobarHex = foobarBuffer.toString('hex');2122const uppercaseGenerator = async function * (lines) {23 for await (const line of lines) {24 yield line.toUpperCase();25 }26};2725const testGeneratorInput = async (t, index) => {26 const {stdout} = await execa('stdin-fd.js', [`${index}`], getStdio(index, [foobarUint8Array, uppercaseGenerator]));27 t.is(stdout, foobarUppercase);28const uppercaseBufferGenerator = async function * (lines) {29 for await (const line of lines) {30 yield textDecoder.decode(line).toUpperCase();31 }32};3330test('Can use generators with result.stdin', testGeneratorInput, 0);31test('Can use generators with result.stdio[*] as input', testGeneratorInput, 3);34const getInputObjectMode = objectMode => objectMode35 ? {input: [foobarObject], generator: serializeGenerator, output: foobarObjectString}36 : {input: foobarUint8Array, generator: uppercaseGenerator, output: foobarUppercase};3733const testGeneratorInputPipe = async (t, index, useShortcutProperty, encoding) => {34 const childProcess = execa('stdin-fd.js', [`${index}`], getStdio(index, uppercaseGenerator));35 const stream = useShortcutProperty ? childProcess.stdin : childProcess.stdio[index];36 stream.end(encoding === 'buffer' ? foobarBuffer : foobarBuffer.toString(encoding), encoding);38const getOutputObjectMode = objectMode => objectMode39 ? {generator: outputObjectGenerator, output: [foobarObject], getStreamMethod: getStreamAsArray}40 : {generator: uppercaseGenerator, output: foobarUppercase, getStreamMethod: getStream};4142const testGeneratorInput = async (t, index, objectMode) => {43 const {input, generator, output} = getInputObjectMode(objectMode);44 const {stdout} = await execa('stdin-fd.js', [`${index}`], getStdio(index, [input, generator]));45 t.is(stdout, output);46};4748test('Can use generators with result.stdin', testGeneratorInput, 0, false);49test('Can use generators with result.stdio[*] as input', testGeneratorInput, 3, false);50test('Can use generators with result.stdin, objectMode', testGeneratorInput, 0, true);51test('Can use generators with result.stdio[*] as input, objectMode', testGeneratorInput, 3, true);5253const testGeneratorInputPipe = async (t, useShortcutProperty, objectMode, input) => {54 const {generator, output} = getInputObjectMode(objectMode);55 const childProcess = execa('stdin-fd.js', ['0'], getStdio(0, generator));56 const stream = useShortcutProperty ? childProcess.stdin : childProcess.stdio[0];57 stream.end(...input);58 const {stdout} = await childProcess;38 t.is(stdout, foobarUppercase);59 t.is(stdout, output);60};6141test('Can use generators with childProcess.stdio[0] and default encoding', testGeneratorInputPipe, 0, false, 'utf8');42test('Can use generators with childProcess.stdin and default encoding', testGeneratorInputPipe, 0, true, 'utf8');43test('Can use generators with childProcess.stdio[0] and encoding "buffer"', testGeneratorInputPipe, 0, false, 'buffer');44test('Can use generators with childProcess.stdin and encoding "buffer"', testGeneratorInputPipe, 0, true, 'buffer');45test('Can use generators with childProcess.stdio[0] and encoding "hex"', testGeneratorInputPipe, 0, false, 'hex');46test('Can use generators with childProcess.stdin and encoding "hex"', testGeneratorInputPipe, 0, true, 'hex');62test('Can use generators with childProcess.stdio[0] and default encoding', testGeneratorInputPipe, false, false, [foobarString, 'utf8']);63test('Can use generators with childProcess.stdin and default encoding', testGeneratorInputPipe, true, false, [foobarString, 'utf8']);64test('Can use generators with childProcess.stdio[0] and encoding "buffer"', testGeneratorInputPipe, false, false, [foobarBuffer, 'buffer']);65test('Can use generators with childProcess.stdin and encoding "buffer"', testGeneratorInputPipe, true, false, [foobarBuffer, 'buffer']);66test('Can use generators with childProcess.stdio[0] and encoding "hex"', testGeneratorInputPipe, false, false, [foobarHex, 'hex']);67test('Can use generators with childProcess.stdin and encoding "hex"', testGeneratorInputPipe, true, false, [foobarHex, 'hex']);68test('Can use generators with childProcess.stdio[0], objectMode', testGeneratorInputPipe, false, true, [foobarObject]);69test('Can use generators with childProcess.stdin, objectMode', testGeneratorInputPipe, true, true, [foobarObject]);7048test('Can use generators with childProcess.stdio[*] as input', async t => {49 const childProcess = execa('stdin-fd.js', ['3'], getStdio(3, [new Uint8Array(), uppercaseGenerator]));50 childProcess.stdio[3].write(foobarUint8Array);71const testGeneratorStdioInputPipe = async (t, objectMode) => {72 const {input, generator, output} = getInputObjectMode(objectMode);73 const childProcess = execa('stdin-fd.js', ['3'], getStdio(3, [new Uint8Array(), generator]));74 childProcess.stdio[3].write(Array.isArray(input) ? input[0] : input);75 const {stdout} = await childProcess;52 t.is(stdout, foobarUppercase);53});76 t.is(stdout, output);77};7879test('Can use generators with childProcess.stdio[*] as input', testGeneratorStdioInputPipe, false);80test('Can use generators with childProcess.stdio[*] as input, objectMode', testGeneratorStdioInputPipe, true);8182const testGeneratorReturn = async (t, index, generators, fixtureName) => {83 await t.throwsAsync(84 execa(fixtureName, [`${index}`], getStdio(index, generators)),85 {message: /a string or an Uint8Array/},86 );87};8889const inputObjectGenerators = [foobarUint8Array, getOutputGenerator(foobarObject, false), serializeGenerator];90const lastInputObjectGenerators = [foobarUint8Array, getOutputGenerator(foobarObject, true)];91const invalidOutputObjectGenerator = getOutputGenerator(foobarObject, false);9293test('Generators with result.stdin cannot return an object if not in objectMode', testGeneratorReturn, 0, inputObjectGenerators, 'stdin-fd.js');94test('Generators with result.stdio[*] as input cannot return an object if not in objectMode', testGeneratorReturn, 3, inputObjectGenerators, 'stdin-fd.js');95test('The last generator with result.stdin cannot return an object even in objectMode', testGeneratorReturn, 0, lastInputObjectGenerators, 'stdin-fd.js');96test('The last generator with result.stdio[*] as input cannot return an object even in objectMode', testGeneratorReturn, 3, lastInputObjectGenerators, 'stdin-fd.js');97test('Generators with result.stdout cannot return an object if not in objectMode', testGeneratorReturn, 1, invalidOutputObjectGenerator, 'noop-fd.js');98test('Generators with result.stderr cannot return an object if not in objectMode', testGeneratorReturn, 2, invalidOutputObjectGenerator, 'noop-fd.js');99test('Generators with result.stdio[*] as output cannot return an object if not in objectMode', testGeneratorReturn, 3, invalidOutputObjectGenerator, 'noop-fd.js');100101// eslint-disable-next-line max-params55const testGeneratorOutput = async (t, index, reject, useShortcutProperty) => {102const testGeneratorOutput = async (t, index, reject, useShortcutProperty, objectMode) => {103 const {generator, output} = getOutputObjectMode(objectMode);104 const fixtureName = reject ? 'noop-fd.js' : 'noop-fail.js';57 const {stdout, stderr, stdio} = await execa(fixtureName, [`${index}`, foobarString], {...getStdio(index, uppercaseGenerator), reject});105 const {stdout, stderr, stdio} = await execa(fixtureName, [`${index}`, foobarString], {...getStdio(index, generator), reject});106 const result = useShortcutProperty ? [stdout, stderr][index - 1] : stdio[index];59 t.is(result, foobarUppercase);107 t.deepEqual(result, output);108};10962test('Can use generators with result.stdio[1]', testGeneratorOutput, 1, true, false);63test('Can use generators with result.stdout', testGeneratorOutput, 1, true, true);64test('Can use generators with result.stdio[2]', testGeneratorOutput, 2, true, false);65test('Can use generators with result.stderr', testGeneratorOutput, 2, true, true);66test('Can use generators with result.stdio[*] as output', testGeneratorOutput, 3, true, false);67test('Can use generators with error.stdio[1]', testGeneratorOutput, 1, false, false);68test('Can use generators with error.stdout', testGeneratorOutput, 1, false, true);69test('Can use generators with error.stdio[2]', testGeneratorOutput, 2, false, false);70test('Can use generators with error.stderr', testGeneratorOutput, 2, false, true);71test('Can use generators with error.stdio[*] as output', testGeneratorOutput, 3, false, false);110test('Can use generators with result.stdio[1]', testGeneratorOutput, 1, true, false, false);111test('Can use generators with result.stdout', testGeneratorOutput, 1, true, true, false);112test('Can use generators with result.stdio[2]', testGeneratorOutput, 2, true, false, false);113test('Can use generators with result.stderr', testGeneratorOutput, 2, true, true, false);114test('Can use generators with result.stdio[*] as output', testGeneratorOutput, 3, true, false, false);115test('Can use generators with error.stdio[1]', testGeneratorOutput, 1, false, false, false);116test('Can use generators with error.stdout', testGeneratorOutput, 1, false, true, false);117test('Can use generators with error.stdio[2]', testGeneratorOutput, 2, false, false, false);118test('Can use generators with error.stderr', testGeneratorOutput, 2, false, true, false);119test('Can use generators with error.stdio[*] as output', testGeneratorOutput, 3, false, false, false);120test('Can use generators with result.stdio[1], objectMode', testGeneratorOutput, 1, true, false, true);121test('Can use generators with result.stdout, objectMode', testGeneratorOutput, 1, true, true, true);122test('Can use generators with result.stdio[2], objectMode', testGeneratorOutput, 2, true, false, true);123test('Can use generators with result.stderr, objectMode', testGeneratorOutput, 2, true, true, true);124test('Can use generators with result.stdio[*] as output, objectMode', testGeneratorOutput, 3, true, false, true);125test('Can use generators with error.stdio[1], objectMode', testGeneratorOutput, 1, false, false, true);126test('Can use generators with error.stdout, objectMode', testGeneratorOutput, 1, false, true, true);127test('Can use generators with error.stdio[2], objectMode', testGeneratorOutput, 2, false, false, true);128test('Can use generators with error.stderr, objectMode', testGeneratorOutput, 2, false, true, true);129test('Can use generators with error.stdio[*] as output, objectMode', testGeneratorOutput, 3, false, false, true);13073const testGeneratorOutputPipe = async (t, index, useShortcutProperty) => {74 const childProcess = execa('noop-fd.js', [`${index}`, foobarString], {...getStdio(index, uppercaseGenerator), buffer: false});131const testGeneratorOutputPipe = async (t, index, useShortcutProperty, objectMode) => {132 const {generator, output, getStreamMethod} = getOutputObjectMode(objectMode);133 const childProcess = execa('noop-fd.js', [`${index}`, foobarString], {...getStdio(index, generator), buffer: false});134 const stream = useShortcutProperty ? [childProcess.stdout, childProcess.stderr][index - 1] : childProcess.stdio[index];76 const [result] = await Promise.all([getStream(stream), childProcess]);77 t.is(result, foobarUppercase);135 const [result] = await Promise.all([getStreamMethod(stream), childProcess]);136 t.deepEqual(result, output);137};13880test('Can use generators with childProcess.stdio[1]', testGeneratorOutputPipe, 1, false);81test('Can use generators with childProcess.stdout', testGeneratorOutputPipe, 1, true);82test('Can use generators with childProcess.stdio[2]', testGeneratorOutputPipe, 2, false);83test('Can use generators with childProcess.stderr', testGeneratorOutputPipe, 2, true);84test('Can use generators with childProcess.stdio[*] as output', testGeneratorOutputPipe, 3, false);139test('Can use generators with childProcess.stdio[1]', testGeneratorOutputPipe, 1, false, false);140test('Can use generators with childProcess.stdout', testGeneratorOutputPipe, 1, true, false);141test('Can use generators with childProcess.stdio[2]', testGeneratorOutputPipe, 2, false, false);142test('Can use generators with childProcess.stderr', testGeneratorOutputPipe, 2, true, false);143test('Can use generators with childProcess.stdio[*] as output', testGeneratorOutputPipe, 3, false, false);144test('Can use generators with childProcess.stdio[1], objectMode', testGeneratorOutputPipe, 1, false, true);145test('Can use generators with childProcess.stdout, objectMode', testGeneratorOutputPipe, 1, true, true);146test('Can use generators with childProcess.stdio[2], objectMode', testGeneratorOutputPipe, 2, false, true);147test('Can use generators with childProcess.stderr, objectMode', testGeneratorOutputPipe, 2, true, true);148test('Can use generators with childProcess.stdio[*] as output, objectMode', testGeneratorOutputPipe, 3, false, true);14986const testGeneratorAll = async (t, reject) => {150const getAllStdioOption = (stdioOption, encoding, objectMode) => {151 if (stdioOption) {152 return 'pipe';153 }154155 if (objectMode) {156 return outputObjectGenerator;157 }158159 return encoding === 'buffer' ? uppercaseBufferGenerator : uppercaseGenerator;160};161162const getStdoutStderrOutput = (output, stdioOption, encoding, objectMode) => {163 if (objectMode && !stdioOption) {164 return [foobarObject];165 }166167 const stdioOutput = stdioOption ? output : output.toUpperCase();168 return encoding === 'buffer' ? textEncoder.encode(stdioOutput) : stdioOutput;169};170171const getAllOutput = (stdoutOutput, stderrOutput, encoding, objectMode) => {172 if (objectMode) {173 return [stdoutOutput, stderrOutput].flat();174 }175176 return encoding === 'buffer'177 ? new Uint8Array([...stdoutOutput, ...stderrOutput])178 : `${stdoutOutput}${stderrOutput}`;179};180181// eslint-disable-next-line max-params182const testGeneratorAll = async (t, reject, encoding, objectMode, stdoutOption, stderrOption) => {183 const fixtureName = reject ? 'all.js' : 'all-fail.js';88 const {all} = await execa(fixtureName, {all: true, reject, stdout: uppercaseGenerator, stderr: uppercaseGenerator});89 t.is(all, 'STDOUT\nSTDERR');184 const {stdout, stderr, all} = await execa(fixtureName, {185 all: true,186 reject,187 stdout: getAllStdioOption(stdoutOption, encoding, objectMode),188 stderr: getAllStdioOption(stderrOption, encoding, objectMode),189 encoding,190 stripFinalNewline: false,191 });192193 const stdoutOutput = getStdoutStderrOutput('stdout\n', stdoutOption, encoding, objectMode);194 t.deepEqual(stdout, stdoutOutput);195 const stderrOutput = getStdoutStderrOutput('stderr\n', stderrOption, encoding, objectMode);196 t.deepEqual(stderr, stderrOutput);197 const allOutput = getAllOutput(stdoutOutput, stderrOutput, encoding, objectMode);198 t.deepEqual(all, allOutput);199};20092test('Can use generators with result.all', testGeneratorAll, true);93test('Can use generators with error.all', testGeneratorAll, false);201test('Can use generators with result.all = transform + transform', testGeneratorAll, true, 'utf8', false, false, false);202test('Can use generators with error.all = transform + transform', testGeneratorAll, false, 'utf8', false, false, false);203test('Can use generators with result.all = transform + transform, encoding "buffer"', testGeneratorAll, true, 'buffer', false, false, false);204test('Can use generators with error.all = transform + transform, encoding "buffer"', testGeneratorAll, false, 'buffer', false, false, false);205test('Can use generators with result.all = transform + pipe', testGeneratorAll, true, 'utf8', false, false, true);206test('Can use generators with error.all = transform + pipe', testGeneratorAll, false, 'utf8', false, false, true);207test('Can use generators with result.all = transform + pipe, encoding "buffer"', testGeneratorAll, true, 'buffer', false, false, true);208test('Can use generators with error.all = transform + pipe, encoding "buffer"', testGeneratorAll, false, 'buffer', false, false, true);209test('Can use generators with result.all = pipe + transform', testGeneratorAll, true, 'utf8', false, true, false);210test('Can use generators with error.all = pipe + transform', testGeneratorAll, false, 'utf8', false, true, false);211test('Can use generators with result.all = pipe + transform, encoding "buffer"', testGeneratorAll, true, 'buffer', false, true, false);212test('Can use generators with error.all = pipe + transform, encoding "buffer"', testGeneratorAll, false, 'buffer', false, true, false);213test('Can use generators with result.all = transform + transform, objectMode', testGeneratorAll, true, 'utf8', true, false, false);214test('Can use generators with error.all = transform + transform, objectMode', testGeneratorAll, false, 'utf8', true, false, false);215test('Can use generators with result.all = transform + transform, objectMode, encoding "buffer"', testGeneratorAll, true, 'buffer', true, false, false);216test('Can use generators with error.all = transform + transform, objectMode, encoding "buffer"', testGeneratorAll, false, 'buffer', true, false, false);217test('Can use generators with result.all = transform + pipe, objectMode', testGeneratorAll, true, 'utf8', true, false, true);218test('Can use generators with error.all = transform + pipe, objectMode', testGeneratorAll, false, 'utf8', true, false, true);219test('Can use generators with result.all = transform + pipe, objectMode, encoding "buffer"', testGeneratorAll, true, 'buffer', true, false, true);220test('Can use generators with error.all = transform + pipe, objectMode, encoding "buffer"', testGeneratorAll, false, 'buffer', true, false, true);221test('Can use generators with result.all = pipe + transform, objectMode', testGeneratorAll, true, 'utf8', true, true, false);222test('Can use generators with error.all = pipe + transform, objectMode', testGeneratorAll, false, 'utf8', true, true, false);223test('Can use generators with result.all = pipe + transform, objectMode, encoding "buffer"', testGeneratorAll, true, 'buffer', true, true, false);224test('Can use generators with error.all = pipe + transform, objectMode, encoding "buffer"', testGeneratorAll, false, 'buffer', true, true, false);225226test('Can use generators with input option', async t => {227 const {stdout} = await execa('stdin-fd.js', ['0'], {stdin: uppercaseGenerator, input: foobarUint8Array});228 t.is(stdout, foobarUppercase);
19 unmodified lines
248test('Cannot use invalid "transform" with stdout', testInvalidGenerator, 1, {transform: true});249test('Cannot use invalid "transform" with stderr', testInvalidGenerator, 2, {transform: true});250test('Cannot use invalid "transform" with stdio[*]', testInvalidGenerator, 3, {transform: true});251121const testInvalidBinary = (t, index) => {252const testInvalidBinary = (t, index, optionName) => {253 t.throws(() => {123 execa('empty.js', getStdio(index, {transform: uppercaseGenerator, binary: 'true'}));254 execa('empty.js', getStdio(index, {transform: uppercaseGenerator, [optionName]: 'true'}));255 }, {message: /a boolean/});256};257127test('Cannot use invalid "binary" with stdin', testInvalidBinary, 0);128test('Cannot use invalid "binary" with stdout', testInvalidBinary, 1);129test('Cannot use invalid "binary" with stderr', testInvalidBinary, 2);130test('Cannot use invalid "binary" with stdio[*]', testInvalidBinary, 3);258test('Cannot use invalid "binary" with stdin', testInvalidBinary, 0, 'binary');259test('Cannot use invalid "binary" with stdout', testInvalidBinary, 1, 'binary');260test('Cannot use invalid "binary" with stderr', testInvalidBinary, 2, 'binary');261test('Cannot use invalid "binary" with stdio[*]', testInvalidBinary, 3, 'binary');262test('Cannot use invalid "objectMode" with stdin', testInvalidBinary, 0, 'objectMode');263test('Cannot use invalid "objectMode" with stdout', testInvalidBinary, 1, 'objectMode');264test('Cannot use invalid "objectMode" with stderr', testInvalidBinary, 2, 'objectMode');265test('Cannot use invalid "objectMode" with stdio[*]', testInvalidBinary, 3, 'objectMode');266267const testSyncMethods = (t, index) => {268 t.throws(() => {269 execaSync('empty.js', getStdio(index, uppercaseGenerator));
25 unmodified lines
295 yield `${chunk.length}`;296 }297};298164const testHighWaterMark = async (t, passThrough) => {165 const index = 1;166 const {stdout} = await execa('noop-fd.js', [`${index}`], getStdio(index, [167 writerGenerator,168 ...passThrough,169 {transform: getLengthGenerator, binary: true},170 ]));299const testHighWaterMark = async (t, passThrough, binary, objectMode) => {300 const {stdout} = await execa('noop.js', {301 stdout: [302 ...(objectMode ? [outputObjectGenerator] : []),303 writerGenerator,304 ...(passThrough ? [{transform: passThroughGenerator, binary}] : []),305 {transform: getLengthGenerator, binary: true},306 ],307 });308 t.is(stdout, `${getDefaultHighWaterMark()}`.repeat(repeatHighWaterMark));309};310174test('Stream respects highWaterMark, no passThrough', testHighWaterMark, []);175test('Stream respects highWaterMark, line-wise passThrough', testHighWaterMark, [passThroughGenerator]);176test('Stream respects highWaterMark, binary passThrough', testHighWaterMark, [{transform: passThroughGenerator, binary: true}]);311test('Stream respects highWaterMark, no passThrough', testHighWaterMark, false, false, false);312test('Stream respects highWaterMark, line-wise passThrough', testHighWaterMark, true, false, false);313test('Stream respects highWaterMark, binary passThrough', testHighWaterMark, true, true, false);314test('Stream respects highWaterMark, objectMode as input but not output', testHighWaterMark, false, false, true);315316const getTypeofGenerator = objectMode => ({178const typeofGenerator = async function * (lines) {179 for await (const line of lines) {180 yield Object.prototype.toString.call(line);181 }182};317 async * transform(lines) {318 for await (const line of lines) {319 yield Object.prototype.toString.call(line);320 }321 },322 objectMode,323});324325// eslint-disable-next-line max-params184const testGeneratorFirstEncoding = async (t, input, encoding) => {185 const childProcess = execa('stdin.js', {stdin: typeofGenerator, encoding});326const testGeneratorFirstEncoding = async (t, input, encoding, output, objectMode) => {327 const childProcess = execa('stdin.js', {stdin: getTypeofGenerator(objectMode), encoding});328 childProcess.stdin.end(input);329 const {stdout} = await childProcess;188 const output = Buffer.from(stdout, encoding).toString();189 t.is(output, encoding === 'buffer' ? '[object Uint8Array]' : '[object String]');330 const result = Buffer.from(stdout, encoding).toString();331 t.is(result, output);332};333192test('First generator argument is string with default encoding, with string writes', testGeneratorFirstEncoding, foobarString, 'utf8');193test('First generator argument is string with default encoding, with Buffer writes', testGeneratorFirstEncoding, foobarBuffer, 'utf8');194test('First generator argument is string with default encoding, with Uint8Array writes', testGeneratorFirstEncoding, foobarUint8Array, 'utf8');195test('First generator argument is Uint8Array with encoding "buffer", with string writes', testGeneratorFirstEncoding, foobarString, 'buffer');196test('First generator argument is Uint8Array with encoding "buffer", with Buffer writes', testGeneratorFirstEncoding, foobarBuffer, 'buffer');197test('First generator argument is Uint8Array with encoding "buffer", with Uint8Array writes', testGeneratorFirstEncoding, foobarUint8Array, 'buffer');198test('First generator argument is Uint8Array with encoding "hex", with string writes', testGeneratorFirstEncoding, foobarString, 'hex');199test('First generator argument is Uint8Array with encoding "hex", with Buffer writes', testGeneratorFirstEncoding, foobarBuffer, 'hex');200test('First generator argument is Uint8Array with encoding "hex", with Uint8Array writes', testGeneratorFirstEncoding, foobarUint8Array, 'hex');334test('First generator argument is string with default encoding, with string writes', testGeneratorFirstEncoding, foobarString, 'utf8', '[object String]', false);335test('First generator argument is string with default encoding, with Buffer writes', testGeneratorFirstEncoding, foobarBuffer, 'utf8', '[object String]', false);336test('First generator argument is string with default encoding, with Uint8Array writes', testGeneratorFirstEncoding, foobarUint8Array, 'utf8', '[object String]', false);337test('First generator argument is Uint8Array with encoding "buffer", with string writes', testGeneratorFirstEncoding, foobarString, 'buffer', '[object Uint8Array]', false);338test('First generator argument is Uint8Array with encoding "buffer", with Buffer writes', testGeneratorFirstEncoding, foobarBuffer, 'buffer', '[object Uint8Array]', false);339test('First generator argument is Uint8Array with encoding "buffer", with Uint8Array writes', testGeneratorFirstEncoding, foobarUint8Array, 'buffer', '[object Uint8Array]', false);340test('First generator argument is Uint8Array with encoding "hex", with string writes', testGeneratorFirstEncoding, foobarString, 'hex', '[object String]', false);341test('First generator argument is Uint8Array with encoding "hex", with Buffer writes', testGeneratorFirstEncoding, foobarBuffer, 'hex', '[object String]', false);342test('First generator argument is Uint8Array with encoding "hex", with Uint8Array writes', testGeneratorFirstEncoding, foobarUint8Array, 'hex', '[object String]', false);343test('First generator argument can be string with objectMode', testGeneratorFirstEncoding, foobarString, 'utf8', '[object String]', true);344test('First generator argument can be objects with objectMode', testGeneratorFirstEncoding, foobarObject, 'utf8', '[object Object]', true);345202const outputGenerator = async function * (input, lines) {203 // eslint-disable-next-line no-unused-vars204 for await (const line of lines) {205 yield input;206 }346const testEncodingIgnored = async (t, encoding) => {347 const input = Buffer.from(foobarString).toString(encoding);348 const childProcess = execa('stdin.js', {stdin: noopGenerator(true)});349 childProcess.stdin.end(input, encoding);350 const {stdout} = await childProcess;351 t.is(stdout, input);352};353209const testGeneratorNextEncoding = async (t, input, encoding) => {210 const {stdout} = await execa('noop.js', ['other'], {stdout: [outputGenerator.bind(undefined, input), typeofGenerator], encoding});211 const output = Buffer.from(stdout, encoding).toString();212 t.is(output, encoding === 'buffer' ? '[object Uint8Array]' : '[object String]');354test('Write call encoding "utf8" is ignored with objectMode', testEncodingIgnored, 'utf8');355test('Write call encoding "utf16le" is ignored with objectMode', testEncodingIgnored, 'utf16le');356test('Write call encoding "hex" is ignored with objectMode', testEncodingIgnored, 'hex');357test('Write call encoding "base64" is ignored with objectMode', testEncodingIgnored, 'base64');358359// eslint-disable-next-line max-params360const testGeneratorNextEncoding = async (t, input, encoding, firstObjectMode, secondObjectMode, expectedType) => {361 const {stdout} = await execa('noop.js', ['other'], {362 stdout: [363 getOutputGenerator(input, firstObjectMode),364 getTypeofGenerator(secondObjectMode),365 ],366 encoding,367 });368 const typeofChunk = Array.isArray(stdout) ? stdout[0] : stdout;369 const output = Buffer.from(typeofChunk, encoding === 'buffer' ? undefined : encoding).toString();370 t.is(output, `[object ${expectedType}]`);371};372215test('Next generator argument is string with default encoding, with string writes', testGeneratorNextEncoding, foobarString, 'utf8');216test('Next generator argument is string with default encoding, with Buffer writes', testGeneratorNextEncoding, foobarBuffer, 'utf8');217test('Next generator argument is string with default encoding, with Uint8Array writes', testGeneratorNextEncoding, foobarUint8Array, 'utf8');218test('Next generator argument is Uint8Array with encoding "buffer", with string writes', testGeneratorNextEncoding, foobarString, 'buffer');219test('Next generator argument is Uint8Array with encoding "buffer", with Buffer writes', testGeneratorNextEncoding, foobarBuffer, 'buffer');220test('Next generator argument is Uint8Array with encoding "buffer", with Uint8Array writes', testGeneratorNextEncoding, foobarUint8Array, 'buffer');221test('Next generator argument is Uint8Array with encoding "hex", with string writes', testGeneratorNextEncoding, foobarString, 'hex');222test('Next generator argument is Uint8Array with encoding "hex", with Buffer writes', testGeneratorNextEncoding, foobarBuffer, 'hex');223test('Next generator argument is Uint8Array with encoding "hex", with Uint8Array writes', testGeneratorNextEncoding, foobarUint8Array, 'hex');373test('Next generator argument is string with default encoding, with string writes', testGeneratorNextEncoding, foobarString, 'utf8', false, false, 'String');374test('Next generator argument is string with default encoding, with string writes, objectMode first', testGeneratorNextEncoding, foobarString, 'utf8', true, false, 'String');375test('Next generator argument is string with default encoding, with string writes, objectMode both', testGeneratorNextEncoding, foobarString, 'utf8', true, true, 'String');376test('Next generator argument is string with default encoding, with Buffer writes', testGeneratorNextEncoding, foobarBuffer, 'utf8', false, false, 'String');377test('Next generator argument is string with default encoding, with Buffer writes, objectMode first', testGeneratorNextEncoding, foobarBuffer, 'utf8', true, false, 'String');378test('Next generator argument is string with default encoding, with Buffer writes, objectMode both', testGeneratorNextEncoding, foobarBuffer, 'utf8', true, true, 'String');379test('Next generator argument is string with default encoding, with Uint8Array writes', testGeneratorNextEncoding, foobarUint8Array, 'utf8', false, false, 'String');380test('Next generator argument is string with default encoding, with Uint8Array writes, objectMode first', testGeneratorNextEncoding, foobarUint8Array, 'utf8', true, false, 'String');381test('Next generator argument is string with default encoding, with Uint8Array writes, objectMode both', testGeneratorNextEncoding, foobarUint8Array, 'utf8', true, true, 'String');382test('Next generator argument is Uint8Array with encoding "buffer", with string writes', testGeneratorNextEncoding, foobarString, 'buffer', false, false, 'Uint8Array');383test('Next generator argument is Uint8Array with encoding "buffer", with string writes, objectMode first', testGeneratorNextEncoding, foobarString, 'buffer', true, false, 'Uint8Array');384test('Next generator argument is Uint8Array with encoding "buffer", with string writes, objectMode both', testGeneratorNextEncoding, foobarString, 'buffer', true, true, 'Uint8Array');385test('Next generator argument is Uint8Array with encoding "buffer", with Buffer writes', testGeneratorNextEncoding, foobarBuffer, 'buffer', false, false, 'Uint8Array');386test('Next generator argument is Uint8Array with encoding "buffer", with Buffer writes, objectMode first', testGeneratorNextEncoding, foobarBuffer, 'buffer', true, false, 'Uint8Array');387test('Next generator argument is Uint8Array with encoding "buffer", with Buffer writes, objectMode both', testGeneratorNextEncoding, foobarBuffer, 'buffer', true, true, 'Uint8Array');388test('Next generator argument is Uint8Array with encoding "buffer", with Uint8Array writes', testGeneratorNextEncoding, foobarUint8Array, 'buffer', false, false, 'Uint8Array');389test('Next generator argument is Uint8Array with encoding "buffer", with Uint8Array writes, objectMode first', testGeneratorNextEncoding, foobarUint8Array, 'buffer', true, false, 'Uint8Array');390test('Next generator argument is Uint8Array with encoding "buffer", with Uint8Array writes, objectMode both', testGeneratorNextEncoding, foobarUint8Array, 'buffer', true, true, 'Uint8Array');391test('Next generator argument is Uint8Array with encoding "hex", with string writes', testGeneratorNextEncoding, foobarString, 'hex', false, false, 'String');392test('Next generator argument is Uint8Array with encoding "hex", with Buffer writes', testGeneratorNextEncoding, foobarBuffer, 'hex', false, false, 'String');393test('Next generator argument is Uint8Array with encoding "hex", with Uint8Array writes', testGeneratorNextEncoding, foobarUint8Array, 'hex', false, false, 'String');394test('Next generator argument is object with default encoding, with object writes, objectMode first', testGeneratorNextEncoding, foobarObject, 'utf8', true, false, 'Object');395test('Next generator argument is object with default encoding, with object writes, objectMode both', testGeneratorNextEncoding, foobarObject, 'utf8', true, true, 'Object');396225const testGeneratorReturnType = async (t, input, encoding) => {226 const {stdout} = await execa('noop.js', ['other'], {stdout: outputGenerator.bind(undefined, input), encoding});227 const output = Buffer.from(stdout, encoding).toString();397const testFirstOutputGeneratorArgument = async (t, index) => {398 const {stdio} = await execa('noop-fd.js', [`${index}`], getStdio(index, getTypeofGenerator(true)));399 t.deepEqual(stdio[index], ['[object String]']);400};401402test('The first generator with result.stdout does not receive an object argument even in objectMode', testFirstOutputGeneratorArgument, 1);403test('The first generator with result.stderr does not receive an object argument even in objectMode', testFirstOutputGeneratorArgument, 2);404test('The first generator with result.stdio[*] does not receive an object argument even in objectMode', testFirstOutputGeneratorArgument, 3);405406// eslint-disable-next-line max-params407const testGeneratorReturnType = async (t, input, encoding, reject, objectMode) => {408 const fixtureName = reject ? 'noop-fd.js' : 'noop-fail.js';409 const {stdout} = await execa(fixtureName, ['1', 'other'], {410 stdout: getOutputGenerator(input, objectMode),411 encoding,412 reject,413 });414 const typeofChunk = Array.isArray(stdout) ? stdout[0] : stdout;415 const output = Buffer.from(typeofChunk, encoding === 'buffer' ? undefined : encoding).toString();416 t.is(output, foobarString);417};418231test('Generator can return string with default encoding', testGeneratorReturnType, foobarString, 'utf8');232test('Generator can return Uint8Array with default encoding', testGeneratorReturnType, foobarUint8Array, 'utf8');233test('Generator can return string with encoding "buffer"', testGeneratorReturnType, foobarString, 'buffer');234test('Generator can return Uint8Array with encoding "buffer"', testGeneratorReturnType, foobarUint8Array, 'buffer');235test('Generator can return string with encoding "hex"', testGeneratorReturnType, foobarString, 'hex');236test('Generator can return Uint8Array with encoding "hex"', testGeneratorReturnType, foobarUint8Array, 'hex');419test('Generator can return string with default encoding', testGeneratorReturnType, foobarString, 'utf8', true, false);420test('Generator can return Uint8Array with default encoding', testGeneratorReturnType, foobarUint8Array, 'utf8', true, false);421test('Generator can return string with encoding "buffer"', testGeneratorReturnType, foobarString, 'buffer', true, false);422test('Generator can return Uint8Array with encoding "buffer"', testGeneratorReturnType, foobarUint8Array, 'buffer', true, false);423test('Generator can return string with encoding "hex"', testGeneratorReturnType, foobarString, 'hex', true, false);424test('Generator can return Uint8Array with encoding "hex"', testGeneratorReturnType, foobarUint8Array, 'hex', true, false);425test('Generator can return string with default encoding, failure', testGeneratorReturnType, foobarString, 'utf8', false, false);426test('Generator can return Uint8Array with default encoding, failure', testGeneratorReturnType, foobarUint8Array, 'utf8', false, false);427test('Generator can return string with encoding "buffer", failure', testGeneratorReturnType, foobarString, 'buffer', false, false);428test('Generator can return Uint8Array with encoding "buffer", failure', testGeneratorReturnType, foobarUint8Array, 'buffer', false, false);429test('Generator can return string with encoding "hex", failure', testGeneratorReturnType, foobarString, 'hex', false, false);430test('Generator can return Uint8Array with encoding "hex", failure', testGeneratorReturnType, foobarUint8Array, 'hex', false, false);431test('Generator can return string with default encoding, objectMode', testGeneratorReturnType, foobarString, 'utf8', true, true);432test('Generator can return Uint8Array with default encoding, objectMode', testGeneratorReturnType, foobarUint8Array, 'utf8', true, true);433test('Generator can return string with encoding "buffer", objectMode', testGeneratorReturnType, foobarString, 'buffer', true, true);434test('Generator can return Uint8Array with encoding "buffer", objectMode', testGeneratorReturnType, foobarUint8Array, 'buffer', true, true);435test('Generator can return string with encoding "hex", objectMode', testGeneratorReturnType, foobarString, 'hex', true, true);436test('Generator can return Uint8Array with encoding "hex", objectMode', testGeneratorReturnType, foobarUint8Array, 'hex', true, true);437test('Generator can return string with default encoding, objectMode, failure', testGeneratorReturnType, foobarString, 'utf8', false, true);438test('Generator can return Uint8Array with default encoding, objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'utf8', false, true);439test('Generator can return string with encoding "buffer", objectMode, failure', testGeneratorReturnType, foobarString, 'buffer', false, true);440test('Generator can return Uint8Array with encoding "buffer", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'buffer', false, true);441test('Generator can return string with encoding "hex", objectMode, failure', testGeneratorReturnType, foobarString, 'hex', false, true);442test('Generator can return Uint8Array with encoding "hex", objectMode, failure', testGeneratorReturnType, foobarUint8Array, 'hex', false, true);443444const multibyteChar = '\u{1F984}';445const multibyteString = `${multibyteChar}${multibyteChar}`;240const multibyteUint8Array = new TextEncoder().encode(multibyteString);446const multibyteUint8Array = textEncoder.encode(multibyteString);447const breakingLength = multibyteUint8Array.length * 0.75;448const brokenSymbol = '\uFFFD';449244const noopGenerator = async function * (lines) {245 yield * lines;246};247248test('Generator handles multibyte characters with Uint8Array', async t => {249 const childProcess = execa('stdin.js', {stdin: noopGenerator});450const testMultibyte = async (t, objectMode) => {451 const childProcess = execa('stdin.js', {stdin: noopGenerator(objectMode)});452 childProcess.stdin.write(multibyteUint8Array.slice(0, breakingLength));453 await setTimeout(0);454 childProcess.stdin.end(multibyteUint8Array.slice(breakingLength));455 const {stdout} = await childProcess;456 t.is(stdout, multibyteString);255});457};458257test('Generator handles partial multibyte characters with Uint8Array', async t => {258 const {stdout} = await execa('stdin.js', {stdin: [multibyteUint8Array.slice(0, breakingLength), noopGenerator]});459test('Generator handles multibyte characters with Uint8Array', testMultibyte, false);460test('Generator handles multibyte characters with Uint8Array, objectMode', testMultibyte, true);461462const testMultibytePartial = async (t, objectMode) => {463 const {stdout} = await execa('stdin.js', {stdin: [multibyteUint8Array.slice(0, breakingLength), noopGenerator(objectMode)]});464 t.is(stdout, `${multibyteChar}${brokenSymbol}`);260});465};466467test('Generator handles partial multibyte characters with Uint8Array', testMultibytePartial, false);468test('Generator handles partial multibyte characters with Uint8Array, objectMode', testMultibytePartial, true);469470// eslint-disable-next-line require-yield471const noYieldGenerator = async function * (lines) {472 // eslint-disable-next-line no-empty, no-unused-vars473 for await (const line of lines) {}474};475268test('Generator can filter by not calling yield', async t => {269 const {stdout} = await execa('noop.js', {stdout: noYieldGenerator});270 t.is(stdout, '');271});476const testNoYield = async (t, objectMode, output) => {477 const {stdout} = await execa('noop.js', {stdout: {transform: noYieldGenerator, objectMode}});478 t.deepEqual(stdout, output);479};480481test('Generator can filter by not calling yield', testNoYield, false, '');482test('Generator can filter by not calling yield, objectMode', testNoYield, true, []);483484const prefix = '> ';485const suffix = ' <';486487const multipleYieldGenerator = async function * (lines) {
99 unmodified lines
587const maxBuffer = 10;588589test('Generators take "maxBuffer" into account', async t => {590 const bigString = '.'.repeat(maxBuffer);380 const {stdout} = await execa('noop.js', {maxBuffer, stdout: outputGenerator.bind(undefined, bigString)});591 const {stdout} = await execa('noop.js', {maxBuffer, stdout: getOutputGenerator(bigString, false)});592 t.is(stdout, bigString);593383 await t.throwsAsync(execa('noop.js', {maxBuffer, stdout: outputGenerator.bind(undefined, `${bigString}.`)}));594 await t.throwsAsync(execa('noop.js', {maxBuffer, stdout: getOutputGenerator(`${bigString}.`, false)}));595});596597test('Generators take "maxBuffer" into account, objectMode', async t => {598 const bigArray = Array.from({length: maxBuffer});599 const {stdout} = await execa('noop.js', {maxBuffer, stdout: getOutputsGenerator(bigArray, true)});600 t.is(stdout.length, maxBuffer);601602 await t.throwsAsync(execa('noop.js', {maxBuffer, stdout: getOutputsGenerator([...bigArray, ''], true)}));603});604605const timeoutGenerator = async function * (timeout, lines) {606 for await (const line of lines) {607 await setTimeout(timeout);608 yield line;
45 unmodified lines
modified:test/stdio/input.js+11 added-18 removed
1import {Buffer} from 'node:buffer';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 textEncoder = new TextEncoder();11const binaryFoobar = textEncoder.encode('foobar');12const bufferFoobar = Buffer.from(binaryFoobar);13const arrayBufferFoobar = binaryFoobar.buffer;14const dataViewFoobar = new DataView(arrayBufferFoobar);15const uint16ArrayFoobar = new Uint16Array(arrayBufferFoobar);1610const 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);23test('input option can be a Uint8Array', testInput, binaryFoobar, runExeca);16test('input option can be a Uint8Array', testInput, foobarUint8Array, runExeca);17test('input option can be a String - sync', testInput, 'foobar', runExecaSync);25test('input option can be a Uint8Array - sync', testInput, binaryFoobar, 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) => {
1 unmodified line
24 execaMethod('empty.js', {input});25 }, {message: /a string, a Uint8Array/});26};2735test('input option cannot be a Buffer', testInvalidInput, bufferFoobar, execa);36test('input option cannot be an ArrayBuffer', testInvalidInput, arrayBufferFoobar, execa);37test('input option cannot be a DataView', testInvalidInput, dataViewFoobar, execa);38test('input option cannot be a Uint16Array', testInvalidInput, uint16ArrayFoobar, execa);28test('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);43test('input option cannot be a Buffer - sync', testInvalidInput, bufferFoobar, execaSync);44test('input option cannot be an ArrayBuffer - sync', testInvalidInput, arrayBufferFoobar, execaSync);45test('input option cannot be a DataView - sync', testInvalidInput, dataViewFoobar, execaSync);46test('input option cannot be a Uint16Array - sync', testInvalidInput, uint16ArrayFoobar, execaSync);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);
modified:test/stdio/iterable.js+75 added-7 removed
1import {once} from 'node:events';2import {setTimeout} from 'node:timers/promises';3import test from 'ava';4import {execa, execaSync} from '../../index.js';5import {setFixtureDir} from '../helpers/fixtures-dir.js';6import {getStdio} from '../helpers/stdio.js';6import {stringGenerator, binaryGenerator, asyncGenerator, throwingGenerator, infiniteGenerator} from '../helpers/generator.js';7import {foobarObject, foobarObjectString} from '../helpers/input.js';8import {serializeGenerator} from '../helpers/generator.js';910const stringArray = ['foo', 'bar'];1112const stringGenerator = function * () {13 yield * stringArray;14};1516const textEncoder = new TextEncoder();17const binaryFoo = textEncoder.encode('foo');18const binaryBar = textEncoder.encode('bar');19const binaryArray = [binaryFoo, binaryBar];2021const binaryGenerator = function * () {22 yield * binaryArray;23};2425const asyncGenerator = async function * () {26 await setTimeout(0);27 yield * stringArray;28};2930setFixtureDir();3132const testIterable = async (t, stdioOption, index) => {33 const {stdout} = await execa('stdin-fd.js', [`${index}`], getStdio(index, stdioOption));34 t.is(stdout, 'foobar');35};3637test('stdin option can be an array of strings', testIterable, [stringArray], 0);38test('stdio[*] option can be an array of strings', testIterable, [stringArray], 3);39test('stdin option can be an array of Uint8Arrays', testIterable, [binaryArray], 0);40test('stdio[*] option can be an array of Uint8Arrays', testIterable, [binaryArray], 3);41test('stdin option can be an iterable of strings', testIterable, stringGenerator(), 0);42test('stdio[*] option can be an iterable of strings', testIterable, stringGenerator(), 3);43test('stdin option can be an iterable of Uint8Arrays', testIterable, binaryGenerator(), 0);44test('stdio[*] option can be an iterable of Uint8Arrays', testIterable, binaryGenerator(), 3);45test('stdin option can be an async iterable', testIterable, asyncGenerator(), 0);46test('stdio[*] option can be an async iterable', testIterable, asyncGenerator(), 3);4748const foobarObjectGenerator = function * () {49 yield foobarObject;50};5152const foobarAsyncObjectGenerator = function * () {53 yield foobarObject;54};5556const testObjectIterable = async (t, stdioOption, index) => {57 const {stdout} = await execa('stdin-fd.js', [`${index}`], getStdio(index, [stdioOption, serializeGenerator]));58 t.is(stdout, foobarObjectString);59};6061test('stdin option can be an array of objects', testObjectIterable, [foobarObject], 0);62test('stdio[*] option can be an array of objects', testObjectIterable, [foobarObject], 3);63test('stdin option can be an iterable of objects', testObjectIterable, foobarObjectGenerator(), 0);64test('stdio[*] option can be an iterable of objects', testObjectIterable, foobarObjectGenerator(), 3);65test('stdin option can be an async iterable of objects', testObjectIterable, foobarAsyncObjectGenerator(), 0);66test('stdio[*] option can be an async iterable of objects', testObjectIterable, foobarAsyncObjectGenerator(), 3);6768const testIterableSync = (t, stdioOption, index) => {69 t.throws(() => {70 execaSync('empty.js', getStdio(index, stdioOption));71 }, {message: /an iterable in sync mode/});72};7374test('stdin option cannot be an array of strings - sync', testIterableSync, [stringArray], 0);75test('stdio[*] option cannot be an array of strings - sync', testIterableSync, [stringArray], 3);76test('stdin option cannot be a sync iterable - sync', testIterableSync, stringGenerator(), 0);77test('stdio[*] option cannot be a sync iterable - sync', testIterableSync, stringGenerator(), 3);78test('stdin option cannot be an async iterable - sync', testIterableSync, asyncGenerator(), 0);79test('stdio[*] option cannot be an async iterable - sync', testIterableSync, asyncGenerator(), 3);8081// eslint-disable-next-line require-yield82const throwingGenerator = function * () {83 throw new Error('generator error');84};8586const testIterableError = async (t, index) => {87 const {originalMessage} = await t.throwsAsync(execa('stdin-fd.js', [`${index}`], getStdio(index, throwingGenerator())));88 t.is(originalMessage, 'generator error');89};9091test('stdin option handles errors in iterables', testIterableError, 0);92test('stdio[*] option handles errors in iterables', testIterableError, 3);9341const testNoIterableOutput = (t, index, execaMethod) => {94const testNoIterableOutput = (t, stdioOption, index, execaMethod) => {95 t.throws(() => {43 execaMethod('empty.js', getStdio(index, stringGenerator()));96 execaMethod('empty.js', getStdio(index, stdioOption));97 }, {message: /cannot be an iterable/});98};9947test('stdout option cannot be an iterable', testNoIterableOutput, 1, execa);48test('stderr option cannot be an iterable', testNoIterableOutput, 2, execa);49test('stdout option cannot be an iterable - sync', testNoIterableOutput, 1, execaSync);50test('stderr option cannot be an iterable - sync', testNoIterableOutput, 2, execaSync);100test('stdout option cannot be an array of strings', testNoIterableOutput, [stringArray], 1, execa);101test('stderr option cannot be an array of strings', testNoIterableOutput, [stringArray], 2, execa);102test('stdout option cannot be an array of strings - sync', testNoIterableOutput, [stringArray], 1, execaSync);103test('stderr option cannot be an array of strings - sync', testNoIterableOutput, [stringArray], 2, execaSync);104test('stdout option cannot be an iterable', testNoIterableOutput, stringGenerator(), 1, execa);105test('stderr option cannot be an iterable', testNoIterableOutput, stringGenerator(), 2, execa);106test('stdout option cannot be an iterable - sync', testNoIterableOutput, stringGenerator(), 1, execaSync);107test('stderr option cannot be an iterable - sync', testNoIterableOutput, stringGenerator(), 2, execaSync);108109const infiniteGenerator = () => {110 const controller = new AbortController();111112 const generator = async function * () {113 yield 'foo';114 await setTimeout(1e7, undefined, {signal: controller.signal});115 };116117 return {iterable: generator(), abort: controller.abort.bind(controller)};118};119120test('stdin option can be an infinite iterable', async t => {121 const {iterable, abort} = infiniteGenerator();122 try {123 const childProcess = execa('stdin.js', getStdio(0, iterable));
16 unmodified lines
modified:test/stdio/lines.js+75 added-38 removed
31 unmodified lines
3233const stringsToUint8Arrays = (strings, isUint8Array) => isUint8Array34 ? strings.map(string => textEncoder.encode(string))35 : strings;36const uint8ArrayToString = (result, isUint8Array) => isUint8Array ? textDecoder.decode(result) : result;3637const serializeResult = (result, isUint8Array, objectMode) => objectMode38 ? result.map(resultItem => serializeResultItem(resultItem, isUint8Array)).join('')39 : serializeResultItem(result, isUint8Array);4041const serializeResultItem = (resultItem, isUint8Array) => isUint8Array42 ? textDecoder.decode(resultItem)43 : resultItem;4445// eslint-disable-next-line max-params39const testLines = async (t, index, input, expectedLines, isUint8Array) => {46const testLines = async (t, index, input, expectedLines, isUint8Array, objectMode) => {47 const lines = [];48 const {stdio} = await execa('noop-fd.js', [`${index}`], {49 ...getStdio(index, [43 inputGenerator.bind(undefined, stringsToUint8Arrays(input, isUint8Array)),44 resultGenerator.bind(undefined, lines),50 {transform: inputGenerator.bind(undefined, stringsToUint8Arrays(input, isUint8Array)), objectMode},51 {transform: resultGenerator.bind(undefined, lines), objectMode},52 ]),53 encoding: isUint8Array ? 'buffer' : 'utf8',54 stripFinalNewline: false,55 });49 t.is(uint8ArrayToString(stdio[index], isUint8Array), input.join(''));56 t.is(input.join(''), serializeResult(stdio[index], isUint8Array, objectMode));57 t.deepEqual(lines, stringsToUint8Arrays(expectedLines, isUint8Array));58};5953test('Split string stdout - n newlines, 1 chunk', testLines, 1, ['aaa\nbbb\nccc'], ['aaa\n', 'bbb\n', 'ccc'], false);54test('Split string stderr - n newlines, 1 chunk', testLines, 2, ['aaa\nbbb\nccc'], ['aaa\n', 'bbb\n', 'ccc'], false);55test('Split string stdio[*] - n newlines, 1 chunk', testLines, 3, ['aaa\nbbb\nccc'], ['aaa\n', 'bbb\n', 'ccc'], false);56test('Split string stdout - no newline, n chunks', testLines, 1, ['aaa', 'bbb', 'ccc'], ['aaabbbccc'], false);57test('Split string stdout - 0 newlines, 1 chunk', testLines, 1, ['aaa'], ['aaa'], false);58test('Split string stdout - Windows newlines', testLines, 1, ['aaa\r\nbbb\r\nccc'], ['aaa\r\n', 'bbb\r\n', 'ccc'], false);59test('Split string stdout - chunk ends with newline', testLines, 1, ['aaa\nbbb\nccc\n'], ['aaa\n', 'bbb\n', 'ccc\n'], false);60test('Split string stdout - single newline', testLines, 1, ['\n'], ['\n'], false);61test('Split string stdout - only newlines', testLines, 1, ['\n\n\n'], ['\n', '\n', '\n'], false);62test('Split string stdout - only Windows newlines', testLines, 1, ['\r\n\r\n\r\n'], ['\r\n', '\r\n', '\r\n'], false);63test('Split string stdout - line split over multiple chunks', testLines, 1, ['aaa\nb', 'b', 'b\nccc'], ['aaa\n', 'bbb\n', 'ccc'], false);64test('Split string stdout - 0 newlines, big line', testLines, 1, [bigLine], [bigLine], false);65test('Split string stdout - 0 newlines, many chunks', testLines, 1, manyChunks, [manyChunks.join('')], false);66test('Split Uint8Array stdout - n newlines, 1 chunk', testLines, 1, ['aaa\nbbb\nccc'], ['aaa\n', 'bbb\n', 'ccc'], true);67test('Split Uint8Array stderr - n newlines, 1 chunk', testLines, 2, ['aaa\nbbb\nccc'], ['aaa\n', 'bbb\n', 'ccc'], true);68test('Split Uint8Array stdio[*] - n newlines, 1 chunk', testLines, 3, ['aaa\nbbb\nccc'], ['aaa\n', 'bbb\n', 'ccc'], true);69test('Split Uint8Array stdout - no newline, n chunks', testLines, 1, ['aaa', 'bbb', 'ccc'], ['aaabbbccc'], true);70test('Split Uint8Array stdout - 0 newlines, 1 chunk', testLines, 1, ['aaa'], ['aaa'], true);71test('Split Uint8Array stdout - Windows newlines', testLines, 1, ['aaa\r\nbbb\r\nccc'], ['aaa\r\n', 'bbb\r\n', 'ccc'], true);72test('Split Uint8Array stdout - chunk ends with newline', testLines, 1, ['aaa\nbbb\nccc\n'], ['aaa\n', 'bbb\n', 'ccc\n'], true);73test('Split Uint8Array stdout - single newline', testLines, 1, ['\n'], ['\n'], true);74test('Split Uint8Array stdout - only newlines', testLines, 1, ['\n\n\n'], ['\n', '\n', '\n'], true);75test('Split Uint8Array stdout - only Windows newlines', testLines, 1, ['\r\n\r\n\r\n'], ['\r\n', '\r\n', '\r\n'], true);76test('Split Uint8Array stdout - line split over multiple chunks', testLines, 1, ['aaa\nb', 'b', 'b\nccc'], ['aaa\n', 'bbb\n', 'ccc'], true);77test('Split Uint8Array stdout - 0 newlines, big line', testLines, 1, [bigLine], [bigLine], true);78test('Split Uint8Array stdout - 0 newlines, many chunks', testLines, 1, manyChunks, [manyChunks.join('')], true);60test('Split string stdout - n newlines, 1 chunk', testLines, 1, ['aaa\nbbb\nccc'], ['aaa\n', 'bbb\n', 'ccc'], false, false);61test('Split string stderr - n newlines, 1 chunk', testLines, 2, ['aaa\nbbb\nccc'], ['aaa\n', 'bbb\n', 'ccc'], false, false);62test('Split string stdio[*] - n newlines, 1 chunk', testLines, 3, ['aaa\nbbb\nccc'], ['aaa\n', 'bbb\n', 'ccc'], false, false);63test('Split string stdout - no newline, n chunks', testLines, 1, ['aaa', 'bbb', 'ccc'], ['aaabbbccc'], false, false);64test('Split string stdout - 0 newlines, 1 chunk', testLines, 1, ['aaa'], ['aaa'], false, false);65test('Split string stdout - Windows newlines', testLines, 1, ['aaa\r\nbbb\r\nccc'], ['aaa\r\n', 'bbb\r\n', 'ccc'], false, false);66test('Split string stdout - chunk ends with newline', testLines, 1, ['aaa\nbbb\nccc\n'], ['aaa\n', 'bbb\n', 'ccc\n'], false, false);67test('Split string stdout - single newline', testLines, 1, ['\n'], ['\n'], false, false);68test('Split string stdout - only newlines', testLines, 1, ['\n\n\n'], ['\n', '\n', '\n'], false, false);69test('Split string stdout - only Windows newlines', testLines, 1, ['\r\n\r\n\r\n'], ['\r\n', '\r\n', '\r\n'], false, false);70test('Split string stdout - line split over multiple chunks', testLines, 1, ['aaa\nb', 'b', 'b\nccc'], ['aaa\n', 'bbb\n', 'ccc'], false, false);71test('Split string stdout - 0 newlines, big line', testLines, 1, [bigLine], [bigLine], false, false);72test('Split string stdout - 0 newlines, many chunks', testLines, 1, manyChunks, [manyChunks.join('')], false, false);73test('Split Uint8Array stdout - n newlines, 1 chunk', testLines, 1, ['aaa\nbbb\nccc'], ['aaa\n', 'bbb\n', 'ccc'], true, false);74test('Split Uint8Array stderr - n newlines, 1 chunk', testLines, 2, ['aaa\nbbb\nccc'], ['aaa\n', 'bbb\n', 'ccc'], true, false);75test('Split Uint8Array stdio[*] - n newlines, 1 chunk', testLines, 3, ['aaa\nbbb\nccc'], ['aaa\n', 'bbb\n', 'ccc'], true, false);76test('Split Uint8Array stdout - no newline, n chunks', testLines, 1, ['aaa', 'bbb', 'ccc'], ['aaabbbccc'], true, false);77test('Split Uint8Array stdout - 0 newlines, 1 chunk', testLines, 1, ['aaa'], ['aaa'], true, false);78test('Split Uint8Array stdout - Windows newlines', testLines, 1, ['aaa\r\nbbb\r\nccc'], ['aaa\r\n', 'bbb\r\n', 'ccc'], true, false);79test('Split Uint8Array stdout - chunk ends with newline', testLines, 1, ['aaa\nbbb\nccc\n'], ['aaa\n', 'bbb\n', 'ccc\n'], true, false);80test('Split Uint8Array stdout - single newline', testLines, 1, ['\n'], ['\n'], true, false);81test('Split Uint8Array stdout - only newlines', testLines, 1, ['\n\n\n'], ['\n', '\n', '\n'], true, false);82test('Split Uint8Array stdout - only Windows newlines', testLines, 1, ['\r\n\r\n\r\n'], ['\r\n', '\r\n', '\r\n'], true, false);83test('Split Uint8Array stdout - line split over multiple chunks', testLines, 1, ['aaa\nb', 'b', 'b\nccc'], ['aaa\n', 'bbb\n', 'ccc'], true, false);84test('Split Uint8Array stdout - 0 newlines, big line', testLines, 1, [bigLine], [bigLine], true, false);85test('Split Uint8Array stdout - 0 newlines, many chunks', testLines, 1, manyChunks, [manyChunks.join('')], true, false);86test('Split string stdout - n newlines, 1 chunk, objectMode', testLines, 1, ['aaa\nbbb\nccc'], ['aaa\n', 'bbb\n', 'ccc'], false, true);87test('Split string stderr - n newlines, 1 chunk, objectMode', testLines, 2, ['aaa\nbbb\nccc'], ['aaa\n', 'bbb\n', 'ccc'], false, true);88test('Split string stdio[*] - n newlines, 1 chunk, objectMode', testLines, 3, ['aaa\nbbb\nccc'], ['aaa\n', 'bbb\n', 'ccc'], false, true);89test('Split string stdout - no newline, n chunks, objectMode', testLines, 1, ['aaa', 'bbb', 'ccc'], ['aaabbbccc'], false, true);90test('Split string stdout - 0 newlines, 1 chunk, objectMode', testLines, 1, ['aaa'], ['aaa'], false, true);91test('Split string stdout - Windows newlines, objectMode', testLines, 1, ['aaa\r\nbbb\r\nccc'], ['aaa\r\n', 'bbb\r\n', 'ccc'], false, true);92test('Split string stdout - chunk ends with newline, objectMode', testLines, 1, ['aaa\nbbb\nccc\n'], ['aaa\n', 'bbb\n', 'ccc\n'], false, true);93test('Split string stdout - single newline, objectMode', testLines, 1, ['\n'], ['\n'], false, true);94test('Split string stdout - only newlines, objectMode', testLines, 1, ['\n\n\n'], ['\n', '\n', '\n'], false, true);95test('Split string stdout - only Windows newlines, objectMode', testLines, 1, ['\r\n\r\n\r\n'], ['\r\n', '\r\n', '\r\n'], false, true);96test('Split string stdout - line split over multiple chunks, objectMode', testLines, 1, ['aaa\nb', 'b', 'b\nccc'], ['aaa\n', 'bbb\n', 'ccc'], false, true);97test('Split string stdout - 0 newlines, big line, objectMode', testLines, 1, [bigLine], [bigLine], false, true);98test('Split string stdout - 0 newlines, many chunks, objectMode', testLines, 1, manyChunks, [manyChunks.join('')], false, true);99test('Split Uint8Array stdout - n newlines, 1 chunk, objectMode', testLines, 1, ['aaa\nbbb\nccc'], ['aaa\n', 'bbb\n', 'ccc'], true, true);100test('Split Uint8Array stderr - n newlines, 1 chunk, objectMode', testLines, 2, ['aaa\nbbb\nccc'], ['aaa\n', 'bbb\n', 'ccc'], true, true);101test('Split Uint8Array stdio[*] - n newlines, 1 chunk, objectMode', testLines, 3, ['aaa\nbbb\nccc'], ['aaa\n', 'bbb\n', 'ccc'], true, true);102test('Split Uint8Array stdout - no newline, n chunks, objectMode', testLines, 1, ['aaa', 'bbb', 'ccc'], ['aaabbbccc'], true, true);103test('Split Uint8Array stdout - 0 newlines, 1 chunk, objectMode', testLines, 1, ['aaa'], ['aaa'], true, true);104test('Split Uint8Array stdout - Windows newlines, objectMode', testLines, 1, ['aaa\r\nbbb\r\nccc'], ['aaa\r\n', 'bbb\r\n', 'ccc'], true, true);105test('Split Uint8Array stdout - chunk ends with newline, objectMode', testLines, 1, ['aaa\nbbb\nccc\n'], ['aaa\n', 'bbb\n', 'ccc\n'], true, true);106test('Split Uint8Array stdout - single newline, objectMode', testLines, 1, ['\n'], ['\n'], true, true);107test('Split Uint8Array stdout - only newlines, objectMode', testLines, 1, ['\n\n\n'], ['\n', '\n', '\n'], true, true);108test('Split Uint8Array stdout - only Windows newlines, objectMode', testLines, 1, ['\r\n\r\n\r\n'], ['\r\n', '\r\n', '\r\n'], true, true);109test('Split Uint8Array stdout - line split over multiple chunks, objectMode', testLines, 1, ['aaa\nb', 'b', 'b\nccc'], ['aaa\n', 'bbb\n', 'ccc'], true, true);110test('Split Uint8Array stdout - 0 newlines, big line, objectMode', testLines, 1, [bigLine], [bigLine], true, true);111test('Split Uint8Array stdout - 0 newlines, many chunks, objectMode', testLines, 1, manyChunks, [manyChunks.join('')], true, true);112113// eslint-disable-next-line max-params80const testBinaryOption = async (t, binary, input, expectedLines) => {114const testBinaryOption = async (t, binary, input, expectedLines, objectMode) => {115 const lines = [];116 const {stdout} = await execa('noop-fd.js', ['1'], {117 stdout: [84 inputGenerator.bind(undefined, input),85 {transform: resultGenerator.bind(undefined, lines), binary},118 {transform: inputGenerator.bind(undefined, input), objectMode},119 {transform: resultGenerator.bind(undefined, lines), objectMode, binary},120 ],121 });88 t.is(stdout, input.join(''));122 t.is(input.join(''), objectMode ? stdout.join('') : stdout);123 t.deepEqual(lines, expectedLines);124};12592test('Does not split lines when "binary" is true', testBinaryOption, true, ['aaa\nbbb\nccc'], ['aaa\nbbb\nccc']);93test('Splits lines when "binary" is false', testBinaryOption, false, ['aaa\nbbb\nccc'], ['aaa\n', 'bbb\n', 'ccc']);94test('Splits lines when "binary" is undefined', testBinaryOption, undefined, ['aaa\nbbb\nccc'], ['aaa\n', 'bbb\n', 'ccc']);126test('Does not split lines when "binary" is true', testBinaryOption, true, ['aaa\nbbb\nccc'], ['aaa\nbbb\nccc'], false);127test('Splits lines when "binary" is false', testBinaryOption, false, ['aaa\nbbb\nccc'], ['aaa\n', 'bbb\n', 'ccc'], false);128test('Splits lines when "binary" is undefined', testBinaryOption, undefined, ['aaa\nbbb\nccc'], ['aaa\n', 'bbb\n', 'ccc'], false);129test('Does not split lines when "binary" is true, objectMode', testBinaryOption, true, ['aaa\nbbb\nccc'], ['aaa\nbbb\nccc'], true);130test('Splits lines when "binary" is false, objectMode', testBinaryOption, false, ['aaa\nbbb\nccc'], ['aaa\n', 'bbb\n', 'ccc'], true);131test('Splits lines when "binary" is undefined, objectMode', testBinaryOption, undefined, ['aaa\nbbb\nccc'], ['aaa\n', 'bbb\n', 'ccc'], true);
modified:test/stdio/typed-array.js+3 added-4 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 {foobarUint8Array} from '../helpers/input.js';67setFixtureDir();88const uint8ArrayFoobar = new TextEncoder().encode('foobar');99const testUint8Array = async (t, index) => {11 const {stdout} = await execa('stdin-fd.js', [`${index}`], getStdio(index, uint8ArrayFoobar));10 const {stdout} = await execa('stdin-fd.js', [`${index}`], getStdio(index, foobarUint8Array));11 t.is(stdout, 'foobar');12};1314test('stdin option can be a Uint8Array', testUint8Array, 0);
2 unmodified lines
17test('stdio[*] option can be a Uint8Array - sync', testUint8Array, 3);1819const testNoUint8ArrayOutput = (t, index, execaMethod) => {20 t.throws(() => {22 execaMethod('empty.js', getStdio(index, uint8ArrayFoobar));21 execaMethod('empty.js', getStdio(index, foobarUint8Array));22 }, {message: /cannot be a Uint8Array/});23};2425test('stdout option cannot be a Uint8Array', testNoUint8ArrayOutput, 1, execa);
3 unmodified lines
modified:test/error.js+13 added-6 removed
1 unmodified line
2import test from 'ava';3import {execa, execaSync} from '../index.js';4import {FIXTURES_DIR, setFixtureDir} from './helpers/fixtures-dir.js';5import {fullStdio, getStdio} from './helpers/stdio.js';6import {noopGenerator, outputObjectGenerator} from './helpers/generator.js';78const isWindows = process.platform === 'win32';910setFixtureDir();
87 unmodified lines
98test('error.message contains the command', async t => {99 await t.throwsAsync(execa('exit.js', ['2', 'foo', 'bar']), {message: /exit.js 2 foo bar/});100});101101const testStdioMessage = async (t, encoding, all) => {102 const {message} = await t.throwsAsync(execa('echo-fail.js', {...fullStdio, encoding, all}));102const testStdioMessage = async (t, encoding, all, objectMode) => {103 const {message} = await t.throwsAsync(execa('echo-fail.js', {...getStdio(1, noopGenerator(objectMode), 4), encoding, all}));104 const output = all ? 'stdout\nstderr' : 'stderr\n\nstdout';105 t.true(message.endsWith(`echo-fail.js\n\n${output}\n\nfd3`));106};107107test('error.message contains stdout/stderr/stdio if available', testStdioMessage, 'utf8', false);108test('error.message contains stdout/stderr/stdio even with encoding "buffer"', testStdioMessage, 'buffer', false);109test('error.message contains all if available', testStdioMessage, 'utf8', true);110test('error.message contains all even with encoding "buffer"', testStdioMessage, 'buffer', true);108test('error.message contains stdout/stderr/stdio if available', testStdioMessage, 'utf8', false, false);109test('error.message contains stdout/stderr/stdio even with encoding "buffer"', testStdioMessage, 'buffer', false, false);110test('error.message contains all if available', testStdioMessage, 'utf8', true, false);111test('error.message contains all even with encoding "buffer"', testStdioMessage, 'buffer', true, false);112test('error.message contains stdout/stderr/stdio if available, objectMode', testStdioMessage, 'utf8', false, true);113test('error.message contains stdout/stderr/stdio even with encoding "buffer", objectMode', testStdioMessage, 'buffer', false, true);114test('error.message contains all if available, objectMode', testStdioMessage, 'utf8', true, true);115test('error.message contains all even with encoding "buffer", objectMode', testStdioMessage, 'buffer', true, true);116117const testPartialIgnoreMessage = async (t, index, stdioOption, output) => {118 const {message} = await t.throwsAsync(execa('echo-fail.js', getStdio(index, stdioOption, 4)));119 t.true(message.endsWith(`echo-fail.js\n\n${output}\n\nfd3`));120};121122test('error.message does not contain stdout if not available', testPartialIgnoreMessage, 1, 'ignore', 'stderr');123test('error.message does not contain stderr if not available', testPartialIgnoreMessage, 2, 'ignore', 'stdout');124test('error.message does not contain stdout if it is an object', testPartialIgnoreMessage, 1, outputObjectGenerator, 'stderr');125test('error.message does not contain stderr if it is an object', testPartialIgnoreMessage, 2, outputObjectGenerator, 'stdout');126127const testFullIgnoreMessage = async (t, options, resultProperty) => {128 const {[resultProperty]: message} = await t.throwsAsync(execa('echo-fail.js', options));129 t.false(message.includes('stderr'));
158 unmodified lines
modified:test/test.js+8 added-3 removed
5 unmodified lines
6import getNode from 'get-node';7import which from 'which';8import {execa, execaSync, execaNode, $} from '../index.js';9import {setFixtureDir, PATH_KEY, FIXTURES_DIR_URL} from './helpers/fixtures-dir.js';10import {identity, fullStdio} from './helpers/stdio.js';11import {stringGenerator} from './helpers/generator.js';10import {identity, fullStdio, getStdio} from './helpers/stdio.js';11import {noopGenerator} from './helpers/generator.js';1213setFixtureDir();14process.env.FOO = 'foo';15
25 unmodified lines
41test('cannot return stdin', testNoStdin, execa);42test('cannot return stdin - sync', testNoStdin, execaSync);4344test('cannot return input stdio[*]', async t => {45 const {stdio} = await execa('stdin-fd.js', ['3'], {stdio: ['pipe', 'pipe', 'pipe', stringGenerator()]});45 const {stdio} = await execa('stdin-fd.js', ['3'], getStdio(3, [['foobar']]));46 t.is(stdio[3], undefined);47});4849if (process.platform === 'win32') {
41 unmodified lines
91test('stripFinalNewline: false with stderr - sync', testStripFinalNewline, 2, false, execaSync);92test('stripFinalNewline: true with stdio[*] - sync', testStripFinalNewline, 3, undefined, execaSync);93test('stripFinalNewline: false with stdio[*] - sync', testStripFinalNewline, 3, false, execaSync);9495test('stripFinalNewline is not used in objectMode', async t => {96 const {stdout} = await execa('noop-fd.js', ['1', 'foobar\n'], {stripFinalNewline: true, stdout: noopGenerator(true)});97 t.deepEqual(stdout, ['foobar\n']);98});99100const getPathWithoutLocalDir = () => {101 const newPath = process.env[PATH_KEY].split(path.delimiter).filter(pathDir => !BIN_DIR_REGEXP.test(pathDir)).join(path.delimiter);102 return {[PATH_KEY]: newPath};103};
207 unmodified lines
modified:index.d.ts+84 added-27 removed
16 unmodified lines
17 | 'overlapped'18 | 'ignore'19 | 'inherit';2021// @todo Use either `Iterable<string>` or `Iterable<Uint8Array>` based on whether `encoding: 'buffer'` is used.21// @todo Use `string`, `Uint8Array` or `unknown` for both the argument and the return type, based on whether `encoding: 'buffer'` and `objectMode: true` are used.22// See https://github.com/sindresorhus/execa/issues/69423type StdioTransform = ((chunks: Iterable<string | Uint8Array>) => AsyncGenerator<string | Uint8Array, void, void>);23type StdioTransform = ((chunks: Iterable<unknown>) => AsyncGenerator<unknown, void, void>);2425type StdioTransformFull = {26 transform: StdioTransform;27 binary?: boolean;28 objectMode?: boolean;29};3031type CommonStdioOption<IsSync extends boolean = boolean> =32 | BaseStdioOption33 | 'ipc'34 | number
1 unmodified line
36 | URL37 | {file: string}38 | IfAsync<IsSync,39 | StdioTransform34 | {35 transform: StdioTransform;36 binary?: boolean;37 }>;40 | StdioTransformFull>;4142type InputStdioOption<IsSync extends boolean = boolean> =43 | Uint8Array44 | Readable45 | IfAsync<IsSync,43 | Iterable<string | Uint8Array>44 | AsyncIterable<string | Uint8Array>46 | Iterable<unknown>47 | AsyncIterable<unknown>48 | ReadableStream>;4950type OutputStdioOption<IsSync extends boolean = boolean> =51 | Writable
46 unmodified lines
98 | undefined;99type DefaultEncodingOption = 'utf8';100type BufferEncodingOption = 'buffer';101102// Whether `result.stdout|stderr|all` is an array of values due to `objectMode: true`103type IsObjectStream<104 StreamIndex extends string,105 OptionsType extends CommonOptions = CommonOptions,106> = IsObjectNormalStream<StreamIndex, OptionsType> extends true107 ? true108 : IsObjectStdioStream<StreamIndex, OptionsType['stdio']>;109110type IsObjectNormalStream<111 StreamIndex extends string,112 OptionsType extends CommonOptions = CommonOptions,113> = IsObjectOutputOptions<StreamOption<StreamIndex, OptionsType>>;114115type IsObjectStdioStream<116 StreamIndex extends string,117 StdioOptionType extends StdioOptions | undefined,118> = StdioOptionType extends StdioOptionsArray119 ? StreamIndex extends keyof StdioOptionType120 ? StdioOptionType[StreamIndex] extends StdioOption121 ? IsObjectOutputOptions<StdioOptionType[StreamIndex]>122 : false123 : false124 : false;125126type IsObjectOutputOptions<OutputOptions extends StdioOption> = IsObjectOutputOption<OutputOptions extends StdioSingleOption[]127 ? OutputOptions[number]128 : OutputOptions129>;130131type IsObjectOutputOption<OutputOption extends StdioSingleOption> = OutputOption extends StdioTransformFull132 ? BooleanObjectMode<OutputOption['objectMode']>133 : false;134135type BooleanObjectMode<ObjectModeOption extends StdioTransformFull['objectMode']> = ObjectModeOption extends true ? true : false;136137// Whether `result.stdout|stderr|all` is `undefined`, excluding the `buffer` option138type IgnoresStreamResult<139 StreamIndex extends string,140 OptionsType extends CommonOptions = CommonOptions,141> = IgnoresNormalPropertyResult<StreamIndex, OptionsType> extends true142 ? true143 : IgnoresStdioPropertyResult<StreamIndex, OptionsType['stdio']>;144145// `result.stdin` is always `undefined`146// When using `stdout: 'inherit'`, or `'ignore'`, etc. , `result.stdout` is `undefined`147// Same with `stderr`148type IgnoresNormalPropertyResult<149 StreamIndex extends string,150 OptionsType extends CommonOptions = CommonOptions,110 // `result.stdin` is always `undefined`111> = StreamIndex extends '0' ? true112 // When using `stdout: 'inherit'`, or `'ignore'`, etc. , `result.stdout` is `undefined`113 : StreamIndex extends '1' ? OptionsType['stdout'] extends NoOutputStdioOption ? true : false114 // Same with `stderr`115 : StreamIndex extends '2' ? OptionsType['stderr'] extends NoOutputStdioOption ? true : false116 // Otherwise117 : false;151> = StreamIndex extends '0'152 ? true153 : IgnoresNormalProperty<StreamOption<StreamIndex, OptionsType>>;154155type StreamOption<156 StreamIndex extends string,157 OptionsType extends CommonOptions = CommonOptions,158> = StreamIndex extends '0' ? OptionsType['stdin']159 : StreamIndex extends '1' ? OptionsType['stdout']160 : StreamIndex extends '2' ? OptionsType['stderr']161 : undefined;162163type IgnoresNormalProperty<OutputOptions extends StdioOption> = OutputOptions extends NoOutputStdioOption ? true : false;164165type IgnoresStdioPropertyResult<166 StreamIndex extends string,167 StdioOptionType extends StdioOptions | undefined,168 // Same but with `stdio: 'ignore'`
30 unmodified lines
199// Type of `result.stdout|stderr`200type StdioOutput<201 StreamIndex extends string,202 OptionsType extends CommonOptions = CommonOptions,157> = StdioOutputResult<IgnoresStreamOutput<StreamIndex, OptionsType>, OptionsType>;203> = StdioOutputResult<StreamIndex, IgnoresStreamOutput<StreamIndex, OptionsType>, OptionsType>;204205type StdioOutputResult<206 StreamIndex extends string,207 StreamOutputIgnored extends boolean,208 OptionsType extends CommonOptions = CommonOptions,209> = StreamOutputIgnored extends true210 ? undefined164 : StreamResult<OptionsType>;211 : StreamEncoding<IsObjectStream<StreamIndex, OptionsType>, OptionsType['encoding']>;212166type StreamResult<OptionsType extends CommonOptions = CommonOptions> = StreamEncoding<OptionsType['encoding']>;213type StreamEncoding<214 IsObjectResult extends boolean,215 Encoding extends CommonOptions['encoding'],216> = IsObjectResult extends true ? unknown[]217 : Encoding extends 'buffer' ? Uint8Array : string;218168type StreamEncoding<Encoding extends CommonOptions['encoding']> = Encoding extends 'buffer' ? Uint8Array : string;169219// Type of `result.all`220type AllOutput<OptionsType extends Options = Options> = AllOutputProperty<OptionsType['all'], OptionsType>;221222type AllOutputProperty<223 AllOption extends Options['all'] = Options['all'],224 OptionsType extends Options = Options,225> = AllOption extends true177 ? IgnoresStreamOutput<'1', OptionsType> extends true178 ? StdioOutput<'2', OptionsType>179 : StdioOutput<'1', OptionsType>226 ? StdioOutput<AllUsesStdout<OptionsType> extends true ? '1' : '2', OptionsType>227 : undefined;228229type AllUsesStdout<OptionsType extends Options = Options> = IgnoresStreamOutput<'1', OptionsType> extends true230 ? false231 : IgnoresStreamOutput<'2', OptionsType> extends true232 ? true233 : IsObjectStream<'2', OptionsType> extends true234 ? false235 : IsObjectStream<'1', OptionsType>;236237// Type of `result.stdio`238type StdioArrayOutput<OptionsType extends CommonOptions = CommonOptions> = MapStdioOptions<239OptionsType['stdio'] extends StdioOptionsArray ? OptionsType['stdio'] : ['pipe', 'pipe', 'pipe'],240OptionsType
371 unmodified lines
612613 /**614 The output of the process on `stdout`.615561 This is `undefined` if the `stdout` option is set to [`'inherit'`, `'ipc'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio).616 This is `undefined` if the `stdout` option is set to [`'inherit'`, `'ipc'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio). This is an array if the `stdout` option is a transform in object mode.617 */618 stdout: StdioOutput<'1', OptionsType>;619620 /**621 The output of the process on `stderr`.622568 This is `undefined` if the `stderr` option is set to [`'inherit'`, `'ipc'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio).623 This is `undefined` if the `stderr` option is set to [`'inherit'`, `'ipc'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio). This is an array if the `stderr` option is a transform in object mode.624 */625 stderr: StdioOutput<'2', OptionsType>;626627 /**628 The output of the process on `stdin`, `stdout`, `stderr` and other file descriptors.629575 Items are `undefined` when their corresponding `stdio` option is set to [`'inherit'`, `'ipc'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio).630 Items are `undefined` when their corresponding `stdio` option is set to [`'inherit'`, `'ipc'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio). Items are arrays when their corresponding `stdio` option is a transform in object mode.631 */632 stdio: StdioArrayOutput<OptionsType>;633634 /**
46 unmodified lines
681682 This is `undefined` if either:683 - the `all` option is `false` (default value)684 - both `stdout` and `stderr` options are set to [`'inherit'`, `'ipc'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio)685686 This is an array if either the `stdout` or `stderr` option is a transform in object mode.687 */688 all: IfAsync<IsSync, AllOutput<OptionsType>>;689 // Workaround for a TypeScript bug: https://github.com/microsoft/TypeScript/issues/57062690} & {};
606 unmodified lines
modified:index.js+4 added
83 unmodified lines
84 if (value === undefined || value === null) {85 return;86 }8788 if (Array.isArray(value)) {89 return value;90 }9192 if (Buffer.isBuffer(value)) {93 value = bufferToUint8Array(value);94 }95
225 unmodified lines
modified:index.test-d.ts+204 added-96 removed
19 unmodified lines
20 type ExecaSyncReturnValue,21 type ExecaSyncError,22} from './index.js';2324type AnySyncChunk = string | Uint8Array | undefined;25type AnyChunk = AnySyncChunk | unknown[];26expectType<Readable | null>({} as ExecaChildProcess['stdout']);27expectType<Readable | null>({} as ExecaChildProcess['stderr']);28expectType<Readable | undefined>({} as ExecaChildProcess['all']);27expectType<string | Uint8Array | undefined>({} as ExecaReturnValue['stdout']);28expectType<string | Uint8Array | undefined>({} as ExecaReturnValue['stderr']);29expectType<string | Uint8Array | undefined>({} as ExecaReturnValue['all']);30expectType<[undefined, string | Uint8Array | undefined, string | Uint8Array | undefined]>({} as ExecaReturnValue['stdio']);31expectType<string | Uint8Array | undefined>({} as ExecaSyncReturnValue['stdout']);32expectType<string | Uint8Array | undefined>({} as ExecaSyncReturnValue['stderr']);33expectType<[undefined, string | Uint8Array | undefined, string | Uint8Array | undefined]>({} as ExecaSyncReturnValue['stdio']);29expectType<AnyChunk>({} as ExecaReturnValue['stdout']);30expectType<AnyChunk>({} as ExecaReturnValue['stderr']);31expectType<AnyChunk>({} as ExecaReturnValue['all']);32expectType<[undefined, AnyChunk, AnyChunk]>({} as ExecaReturnValue['stdio']);33expectType<AnySyncChunk>({} as ExecaSyncReturnValue['stdout']);34expectType<AnySyncChunk>({} as ExecaSyncReturnValue['stderr']);35expectType<[undefined, AnySyncChunk, AnySyncChunk]>({} as ExecaSyncReturnValue['stdio']);3637const objectGenerator = async function * (lines: Iterable<unknown>) {38 for await (const line of lines) {39 yield JSON.parse(line as string) as object;40 }41};4243const unknownArrayGenerator = async function * (lines: Iterable<unknown>) {44 for await (const line of lines) {45 yield line;46 }47};4849const booleanGenerator = async function * (lines: Iterable<boolean>) {50 for await (const line of lines) {51 yield line;52 }53};5455const arrayGenerator = async function * (lines: string[]) {56 for await (const line of lines) {57 yield line;58 }59};6061const invalidReturnGenerator = async function * (lines: Iterable<string>) {62 for await (const line of lines) {63 yield line;64 }6566 return false;67};6869const syncGenerator = function * (lines: Iterable<string>) {70 for (const line of lines) {71 yield line;72 }7374 return false;75};7677try {78 const execaPromise = execa('unicorns', {all: true});79 execaPromise.cancel();80
245 unmodified lines
326 expectType<undefined>(noBufferFd3Result.stdio[3]);327328 const ignoreFd3Result = await execa('unicorns', {stdio: ['pipe', 'pipe', 'pipe', 'ignore']});329 expectType<undefined>(ignoreFd3Result.stdio[3]);330331 const objectTransformStdoutResult = await execa('unicorns', {stdout: {transform: objectGenerator, objectMode: true}});332 expectType<unknown[]>(objectTransformStdoutResult.stdout);333 expectType<[undefined, unknown[], string]>(objectTransformStdoutResult.stdio);334335 const objectTransformStderrResult = await execa('unicorns', {stderr: {transform: objectGenerator, objectMode: true}});336 expectType<unknown[]>(objectTransformStderrResult.stderr);337 expectType<[undefined, string, unknown[]]>(objectTransformStderrResult.stdio);338339 const objectTransformStdioResult = await execa('unicorns', {stdio: ['pipe', 'pipe', {transform: objectGenerator, objectMode: true}]});340 expectType<unknown[]>(objectTransformStdioResult.stderr);341 expectType<[undefined, string, unknown[]]>(objectTransformStdioResult.stdio);342343 const singleObjectTransformStdoutResult = await execa('unicorns', {stdout: [{transform: objectGenerator, objectMode: true}]});344 expectType<unknown[]>(singleObjectTransformStdoutResult.stdout);345 expectType<[undefined, unknown[], string]>(singleObjectTransformStdoutResult.stdio);346347 const manyObjectTransformStdoutResult = await execa('unicorns', {stdout: [{transform: objectGenerator, objectMode: true}, {transform: objectGenerator, objectMode: true}]});348 expectType<unknown[]>(manyObjectTransformStdoutResult.stdout);349 expectType<[undefined, unknown[], string]>(manyObjectTransformStdoutResult.stdio);350351 const falseObjectTransformStdoutResult = await execa('unicorns', {stdout: {transform: objectGenerator, objectMode: false}});352 expectType<string>(falseObjectTransformStdoutResult.stdout);353 expectType<[undefined, string, string]>(falseObjectTransformStdoutResult.stdio);354355 const falseObjectTransformStderrResult = await execa('unicorns', {stderr: {transform: objectGenerator, objectMode: false}});356 expectType<string>(falseObjectTransformStderrResult.stderr);357 expectType<[undefined, string, string]>(falseObjectTransformStderrResult.stdio);358359 const falseObjectTransformStdioResult = await execa('unicorns', {stdio: ['pipe', 'pipe', {transform: objectGenerator, objectMode: false}]});360 expectType<string>(falseObjectTransformStdioResult.stderr);361 expectType<[undefined, string, string]>(falseObjectTransformStdioResult.stdio);362363 const undefinedObjectTransformStdoutResult = await execa('unicorns', {stdout: {transform: objectGenerator}});364 expectType<string>(undefinedObjectTransformStdoutResult.stdout);365 expectType<[undefined, string, string]>(undefinedObjectTransformStdoutResult.stdio);366367 const noObjectTransformStdoutResult = await execa('unicorns', {stdout: objectGenerator});368 expectType<string>(noObjectTransformStdoutResult.stdout);369 expectType<[undefined, string, string]>(noObjectTransformStdoutResult.stdio);370371 const trueTrueObjectTransformResult = await execa('unicorns', {stdout: {transform: objectGenerator, objectMode: true}, stderr: {transform: objectGenerator, objectMode: true}, all: true});372 expectType<unknown[]>(trueTrueObjectTransformResult.stdout);373 expectType<unknown[]>(trueTrueObjectTransformResult.stderr);374 expectType<unknown[]>(trueTrueObjectTransformResult.all);375 expectType<[undefined, unknown[], unknown[]]>(trueTrueObjectTransformResult.stdio);376377 const trueFalseObjectTransformResult = await execa('unicorns', {stdout: {transform: objectGenerator, objectMode: true}, stderr: {transform: objectGenerator, objectMode: false}, all: true});378 expectType<unknown[]>(trueFalseObjectTransformResult.stdout);379 expectType<string>(trueFalseObjectTransformResult.stderr);380 expectType<unknown[]>(trueFalseObjectTransformResult.all);381 expectType<[undefined, unknown[], string]>(trueFalseObjectTransformResult.stdio);382383 const falseTrueObjectTransformResult = await execa('unicorns', {stdout: {transform: objectGenerator, objectMode: false}, stderr: {transform: objectGenerator, objectMode: true}, all: true});384 expectType<string>(falseTrueObjectTransformResult.stdout);385 expectType<unknown[]>(falseTrueObjectTransformResult.stderr);386 expectType<unknown[]>(falseTrueObjectTransformResult.all);387 expectType<[undefined, string, unknown[]]>(falseTrueObjectTransformResult.stdio);388389 const falseFalseObjectTransformResult = await execa('unicorns', {stdout: {transform: objectGenerator, objectMode: false}, stderr: {transform: objectGenerator, objectMode: false}, all: true});390 expectType<string>(falseFalseObjectTransformResult.stdout);391 expectType<string>(falseFalseObjectTransformResult.stderr);392 expectType<string>(falseFalseObjectTransformResult.all);393 expectType<[undefined, string, string]>(falseFalseObjectTransformResult.stdio);394} catch (error: unknown) {395 const execaError = error as ExecaError;396397 expectType<string>(execaError.message);
84 unmodified lines
482 const streamStderrError = error as ExecaError<{stderr: typeof process.stdout; all: true}>;483 expectType<string>(streamStderrError.stdout);484 expectType<undefined>(streamStderrError.stderr);485 expectType<string>(streamStderrError.all);486487 const objectTransformStdoutError = error as ExecaError<{stdout: {transform: typeof objectGenerator; objectMode: true}}>;488 expectType<unknown[]>(objectTransformStdoutError.stdout);489 expectType<[undefined, unknown[], string]>(objectTransformStdoutError.stdio);490491 const objectTransformStderrError = error as ExecaError<{stderr: {transform: typeof objectGenerator; objectMode: true}}>;492 expectType<unknown[]>(objectTransformStderrError.stderr);493 expectType<[undefined, string, unknown[]]>(objectTransformStderrError.stdio);494495 const objectTransformStdioError = error as ExecaError<{stdio: ['pipe', 'pipe', {transform: typeof objectGenerator; objectMode: true}]}>;496 expectType<unknown[]>(objectTransformStdioError.stderr);497 expectType<[undefined, string, unknown[]]>(objectTransformStdioError.stdio);498499 const falseObjectTransformStdoutError = error as ExecaError<{stdout: {transform: typeof objectGenerator; objectMode: false}}>;500 expectType<string>(falseObjectTransformStdoutError.stdout);501 expectType<[undefined, string, string]>(falseObjectTransformStdoutError.stdio);502503 const falseObjectTransformStderrError = error as ExecaError<{stderr: {transform: typeof objectGenerator; objectMode: false}}>;504 expectType<string>(falseObjectTransformStderrError.stderr);505 expectType<[undefined, string, string]>(falseObjectTransformStderrError.stdio);506507 const falseObjectTransformStdioError = error as ExecaError<{stdio: ['pipe', 'pipe', {transform: typeof objectGenerator; objectMode: false}]}>;508 expectType<string>(falseObjectTransformStdioError.stderr);509 expectType<[undefined, string, string]>(falseObjectTransformStdioError.stdio);510}511512const rejectsResult = await execa('unicorns');513expectError(rejectsResult.stack);
174 unmodified lines
688const binaryGenerator = function * () {689 yield new Uint8Array(0);690};691562const numberGenerator = function * () {563 yield 0;564};565692const asyncStringGenerator = async function * () {693 yield '';694};695696const fileUrl = new URL('file:///test');697572const stringOrUint8ArrayGenerator = async function * (lines: Iterable<string | Uint8Array>) {573 for await (const line of lines) {574 yield line;575 }576};577578const booleanGenerator = async function * (lines: Iterable<boolean>) {579 for await (const line of lines) {580 yield line;581 }582};583584const arrayGenerator = async function * (lines: string[]) {585 for await (const line of lines) {586 yield line;587 }588};589590const invalidReturnGenerator = async function * (lines: Iterable<string>) {591 for await (const line of lines) {592 yield line;593 }594595 return false;596};597598const syncGenerator = function * (lines: Iterable<string>) {599 for (const line of lines) {600 yield line;601 }602603 return false;604};605698expectAssignable<Options>({cleanup: false});699expectNotAssignable<SyncOptions>({cleanup: false});700expectAssignable<SyncOptions>({preferLocal: false});701
53 unmodified lines
755execa('unicorns', {stdin: [new Readable()]});756execaSync('unicorns', {stdin: [new Readable()]});757expectError(execa('unicorns', {stdin: new Writable()}));758expectError(execaSync('unicorns', {stdin: new Writable()}));667expectError(execa('unicorns', {stdin: [new Writable()]}));759expectError(execaSync('unicorns', {stdin: [new Writable()]}));760execa('unicorns', {stdin: new ReadableStream()});761expectError(execaSync('unicorns', {stdin: new ReadableStream()}));762execa('unicorns', {stdin: [new ReadableStream()]});763expectError(execaSync('unicorns', {stdin: [new ReadableStream()]}));764expectError(execa('unicorns', {stdin: new WritableStream()}));765expectError(execaSync('unicorns', {stdin: new WritableStream()}));675expectError(execa('unicorns', {stdin: [new WritableStream()]}));766expectError(execaSync('unicorns', {stdin: [new WritableStream()]}));767execa('unicorns', {stdin: new Uint8Array()});768execaSync('unicorns', {stdin: new Uint8Array()});769execa('unicorns', {stdin: [['foo', 'bar']]});770expectError(execaSync('unicorns', {stdin: [['foo', 'bar']]}));771execa('unicorns', {stdin: [[new Uint8Array(), new Uint8Array()]]});772expectError(execaSync('unicorns', {stdin: [[new Uint8Array(), new Uint8Array()]]}));773execa('unicorns', {stdin: [[{}, {}]]});774expectError(execaSync('unicorns', {stdin: [[{}, {}]]}));775execa('unicorns', {stdin: emptyStringGenerator()});776expectError(execaSync('unicorns', {stdin: emptyStringGenerator()}));777execa('unicorns', {stdin: [emptyStringGenerator()]});778expectError(execaSync('unicorns', {stdin: [emptyStringGenerator()]}));
4 unmodified lines
783execa('unicorns', {stdin: asyncStringGenerator()});784expectError(execaSync('unicorns', {stdin: asyncStringGenerator()}));785execa('unicorns', {stdin: [asyncStringGenerator()]});786expectError(execaSync('unicorns', {stdin: [asyncStringGenerator()]}));691expectError(execa('unicorns', {stdin: numberGenerator()}));692expectError(execaSync('unicorns', {stdin: numberGenerator()}));693expectError(execa('unicorns', {stdin: [numberGenerator()]}));694expectError(execaSync('unicorns', {stdin: [numberGenerator()]}));787execa('unicorns', {stdin: fileUrl});788execaSync('unicorns', {stdin: fileUrl});789execa('unicorns', {stdin: [fileUrl]});790execaSync('unicorns', {stdin: [fileUrl]});
4 unmodified lines
795execa('unicorns', {stdin: 1});796execaSync('unicorns', {stdin: 1});797execa('unicorns', {stdin: [1]});798execaSync('unicorns', {stdin: [1]});707execa('unicorns', {stdin: stringOrUint8ArrayGenerator});708expectError(execaSync('unicorns', {stdin: stringOrUint8ArrayGenerator}));709execa('unicorns', {stdin: [stringOrUint8ArrayGenerator]});710expectError(execaSync('unicorns', {stdin: [stringOrUint8ArrayGenerator]}));799execa('unicorns', {stdin: unknownArrayGenerator});800expectError(execaSync('unicorns', {stdin: unknownArrayGenerator}));801execa('unicorns', {stdin: [unknownArrayGenerator]});802expectError(execaSync('unicorns', {stdin: [unknownArrayGenerator]}));803expectError(execa('unicorns', {stdin: booleanGenerator}));804expectError(execa('unicorns', {stdin: arrayGenerator}));805expectError(execa('unicorns', {stdin: invalidReturnGenerator}));806expectError(execa('unicorns', {stdin: syncGenerator}));715execa('unicorns', {stdin: {transform: stringOrUint8ArrayGenerator}});716expectError(execaSync('unicorns', {stdin: {transform: stringOrUint8ArrayGenerator}}));717execa('unicorns', {stdin: [{transform: stringOrUint8ArrayGenerator}]});718expectError(execaSync('unicorns', {stdin: [{transform: stringOrUint8ArrayGenerator}]}));807execa('unicorns', {stdin: {transform: unknownArrayGenerator}});808expectError(execaSync('unicorns', {stdin: {transform: unknownArrayGenerator}}));809execa('unicorns', {stdin: [{transform: unknownArrayGenerator}]});810expectError(execaSync('unicorns', {stdin: [{transform: unknownArrayGenerator}]}));811expectError(execa('unicorns', {stdin: {transform: booleanGenerator}}));812expectError(execa('unicorns', {stdin: {transform: arrayGenerator}}));813expectError(execa('unicorns', {stdin: {transform: invalidReturnGenerator}}));814expectError(execa('unicorns', {stdin: {transform: syncGenerator}}));815expectError(execa('unicorns', {stdin: {}}));816expectError(execa('unicorns', {stdin: {binary: true}}));817expectError(execa('unicorns', {stdin: {objectMode: true}}));725execa('unicorns', {stdin: {transform: stringOrUint8ArrayGenerator, binary: true}});726expectError(execa('unicorns', {stdin: {transform: stringOrUint8ArrayGenerator, binary: 'true'}}));818execa('unicorns', {stdin: {transform: unknownArrayGenerator, binary: true}});819expectError(execa('unicorns', {stdin: {transform: unknownArrayGenerator, binary: 'true'}}));820execa('unicorns', {stdin: {transform: unknownArrayGenerator, objectMode: true}});821expectError(execa('unicorns', {stdin: {transform: unknownArrayGenerator, objectMode: 'true'}}));822execa('unicorns', {stdin: undefined});823execaSync('unicorns', {stdin: undefined});824execa('unicorns', {stdin: [undefined]});825execaSync('unicorns', {stdin: [undefined]});
50 unmodified lines
876execa('unicorns', {stdout: 1});877execaSync('unicorns', {stdout: 1});878execa('unicorns', {stdout: [1]});879execaSync('unicorns', {stdout: [1]});785execa('unicorns', {stdout: stringOrUint8ArrayGenerator});786expectError(execaSync('unicorns', {stdout: stringOrUint8ArrayGenerator}));787execa('unicorns', {stdout: [stringOrUint8ArrayGenerator]});788expectError(execaSync('unicorns', {stdout: [stringOrUint8ArrayGenerator]}));880execa('unicorns', {stdout: unknownArrayGenerator});881expectError(execaSync('unicorns', {stdout: unknownArrayGenerator}));882execa('unicorns', {stdout: [unknownArrayGenerator]});883expectError(execaSync('unicorns', {stdout: [unknownArrayGenerator]}));884expectError(execa('unicorns', {stdout: booleanGenerator}));885expectError(execa('unicorns', {stdout: arrayGenerator}));886expectError(execa('unicorns', {stdout: invalidReturnGenerator}));887expectError(execa('unicorns', {stdout: syncGenerator}));793execa('unicorns', {stdout: {transform: stringOrUint8ArrayGenerator}});794expectError(execaSync('unicorns', {stdout: {transform: stringOrUint8ArrayGenerator}}));795execa('unicorns', {stdout: [{transform: stringOrUint8ArrayGenerator}]});796expectError(execaSync('unicorns', {stdout: [{transform: stringOrUint8ArrayGenerator}]}));888execa('unicorns', {stdout: {transform: unknownArrayGenerator}});889expectError(execaSync('unicorns', {stdout: {transform: unknownArrayGenerator}}));890execa('unicorns', {stdout: [{transform: unknownArrayGenerator}]});891expectError(execaSync('unicorns', {stdout: [{transform: unknownArrayGenerator}]}));892expectError(execa('unicorns', {stdout: {transform: booleanGenerator}}));893expectError(execa('unicorns', {stdout: {transform: arrayGenerator}}));894expectError(execa('unicorns', {stdout: {transform: invalidReturnGenerator}}));895expectError(execa('unicorns', {stdout: {transform: syncGenerator}}));896expectError(execa('unicorns', {stdout: {}}));897expectError(execa('unicorns', {stdout: {binary: true}}));898expectError(execa('unicorns', {stdout: {objectMode: true}}));803execa('unicorns', {stdout: {transform: stringOrUint8ArrayGenerator, binary: true}});804expectError(execa('unicorns', {stdout: {transform: stringOrUint8ArrayGenerator, binary: 'true'}}));899execa('unicorns', {stdout: {transform: unknownArrayGenerator, binary: true}});900expectError(execa('unicorns', {stdout: {transform: unknownArrayGenerator, binary: 'true'}}));901execa('unicorns', {stdout: {transform: unknownArrayGenerator, objectMode: true}});902expectError(execa('unicorns', {stdout: {transform: unknownArrayGenerator, objectMode: 'true'}}));903execa('unicorns', {stdout: undefined});904execaSync('unicorns', {stdout: undefined});905execa('unicorns', {stdout: [undefined]});906execaSync('unicorns', {stdout: [undefined]});
50 unmodified lines
957execa('unicorns', {stderr: 1});958execaSync('unicorns', {stderr: 1});959execa('unicorns', {stderr: [1]});960execaSync('unicorns', {stderr: [1]});863execa('unicorns', {stderr: stringOrUint8ArrayGenerator});864expectError(execaSync('unicorns', {stderr: stringOrUint8ArrayGenerator}));865execa('unicorns', {stderr: [stringOrUint8ArrayGenerator]});866expectError(execaSync('unicorns', {stderr: [stringOrUint8ArrayGenerator]}));961execa('unicorns', {stderr: unknownArrayGenerator});962expectError(execaSync('unicorns', {stderr: unknownArrayGenerator}));963execa('unicorns', {stderr: [unknownArrayGenerator]});964expectError(execaSync('unicorns', {stderr: [unknownArrayGenerator]}));965expectError(execa('unicorns', {stderr: booleanGenerator}));966expectError(execa('unicorns', {stderr: arrayGenerator}));967expectError(execa('unicorns', {stderr: invalidReturnGenerator}));968expectError(execa('unicorns', {stderr: syncGenerator}));871execa('unicorns', {stderr: {transform: stringOrUint8ArrayGenerator}});872expectError(execaSync('unicorns', {stderr: {transform: stringOrUint8ArrayGenerator}}));873execa('unicorns', {stderr: [{transform: stringOrUint8ArrayGenerator}]});874expectError(execaSync('unicorns', {stderr: [{transform: stringOrUint8ArrayGenerator}]}));969execa('unicorns', {stderr: {transform: unknownArrayGenerator}});970expectError(execaSync('unicorns', {stderr: {transform: unknownArrayGenerator}}));971execa('unicorns', {stderr: [{transform: unknownArrayGenerator}]});972expectError(execaSync('unicorns', {stderr: [{transform: unknownArrayGenerator}]}));973expectError(execa('unicorns', {stderr: {transform: booleanGenerator}}));974expectError(execa('unicorns', {stderr: {transform: arrayGenerator}}));975expectError(execa('unicorns', {stderr: {transform: invalidReturnGenerator}}));976expectError(execa('unicorns', {stderr: {transform: syncGenerator}}));977expectError(execa('unicorns', {stderr: {}}));978expectError(execa('unicorns', {stderr: {binary: true}}));979expectError(execa('unicorns', {stderr: {objectMode: true}}));881execa('unicorns', {stderr: {transform: stringOrUint8ArrayGenerator, binary: true}});882expectError(execa('unicorns', {stderr: {transform: stringOrUint8ArrayGenerator, binary: 'true'}}));980execa('unicorns', {stderr: {transform: unknownArrayGenerator, binary: true}});981expectError(execa('unicorns', {stderr: {transform: unknownArrayGenerator, binary: 'true'}}));982execa('unicorns', {stderr: {transform: unknownArrayGenerator, objectMode: true}});983expectError(execa('unicorns', {stderr: {transform: unknownArrayGenerator, objectMode: 'true'}}));984execa('unicorns', {stderr: undefined});985execaSync('unicorns', {stderr: undefined});986execa('unicorns', {stderr: [undefined]});987execaSync('unicorns', {stderr: [undefined]});
28 unmodified lines
1016expectError(execa('unicorns', {stdio: 'ipc'}));1017expectError(execaSync('unicorns', {stdio: 'ipc'}));1018expectError(execa('unicorns', {stdio: 1}));1019expectError(execaSync('unicorns', {stdio: 1}));919expectError(execa('unicorns', {stdio: stringOrUint8ArrayGenerator}));920expectError(execaSync('unicorns', {stdio: stringOrUint8ArrayGenerator}));921expectError(execa('unicorns', {stdio: {transform: stringOrUint8ArrayGenerator}}));922expectError(execaSync('unicorns', {stdio: {transform: stringOrUint8ArrayGenerator}}));1020expectError(execa('unicorns', {stdio: unknownArrayGenerator}));1021expectError(execaSync('unicorns', {stdio: unknownArrayGenerator}));1022expectError(execa('unicorns', {stdio: {transform: unknownArrayGenerator}}));1023expectError(execaSync('unicorns', {stdio: {transform: unknownArrayGenerator}}));1024expectError(execa('unicorns', {stdio: fileUrl}));1025expectError(execaSync('unicorns', {stdio: fileUrl}));1026expectError(execa('unicorns', {stdio: {file: './test'}}));1027expectError(execaSync('unicorns', {stdio: {file: './test'}}));
24 unmodified lines
1052execa('unicorns', {stdio: [['pipe'], ['pipe'], [new Writable()]]});1053execaSync('unicorns', {stdio: [['pipe'], ['pipe'], [new Writable()]]});1054expectError(execa('unicorns', {stdio: [new Writable(), 'pipe', 'pipe']}));1055expectError(execaSync('unicorns', {stdio: [new Writable(), 'pipe', 'pipe']}));955expectError(execa('unicorns', {stdio: [[new Writable()], ['pipe'], ['pipe']]}));1056expectError(execaSync('unicorns', {stdio: [[new Writable()], ['pipe'], ['pipe']]}));1057expectError(execa('unicorns', {stdio: ['pipe', new Readable(), 'pipe']}));1058expectError(execaSync('unicorns', {stdio: ['pipe', new Readable(), 'pipe']}));1059expectError(execa('unicorns', {stdio: [['pipe'], [new Readable()], ['pipe']]}));
10 unmodified lines
1070 'ignore',1071 'inherit',1072 process.stdin,1073 1,974 stringOrUint8ArrayGenerator,975 {transform: stringOrUint8ArrayGenerator},976 {transform: stringOrUint8ArrayGenerator, binary: true},1074 unknownArrayGenerator,1075 {transform: unknownArrayGenerator},1076 {transform: unknownArrayGenerator, binary: true},1077 {transform: unknownArrayGenerator, objectMode: true},1078 undefined,1079 fileUrl,1080 {file: './test'},1081 new Writable(),
21 unmodified lines
1103 new Readable(),1104 new Uint8Array(),1105 ],1106});1006expectError(execaSync('unicorns', {stdio: [stringOrUint8ArrayGenerator]}));1007expectError(execaSync('unicorns', {stdio: [{transform: stringOrUint8ArrayGenerator}]}));1107expectError(execaSync('unicorns', {stdio: [unknownArrayGenerator]}));1108expectError(execaSync('unicorns', {stdio: [{transform: unknownArrayGenerator}]}));1109expectError(execaSync('unicorns', {stdio: [new WritableStream()]}));1110expectError(execaSync('unicorns', {stdio: [new ReadableStream()]}));1111expectError(execaSync('unicorns', {stdio: [emptyStringGenerator()]}));1112expectError(execaSync('unicorns', {stdio: [asyncStringGenerator()]}));
6 unmodified lines
1119 ['ignore'],1120 ['inherit'],1121 [process.stdin],1122 [1],1022 [stringOrUint8ArrayGenerator],1023 [{transform: stringOrUint8ArrayGenerator}],1024 [{transform: stringOrUint8ArrayGenerator, binary: true}],1123 [unknownArrayGenerator],1124 [{transform: unknownArrayGenerator}],1125 [{transform: unknownArrayGenerator, binary: true}],1126 [{transform: unknownArrayGenerator, objectMode: true}],1127 [undefined],1128 [fileUrl],1129 [{file: './test'}],1130 [new Writable()],1131 [new Readable()],1132 [new WritableStream()],1133 [new ReadableStream()],1134 [new Uint8Array()],1135 [['foo', 'bar']],1136 [[new Uint8Array(), new Uint8Array()]],1137 [[{}, {}]],1138 [emptyStringGenerator()],1139 [asyncStringGenerator()],1140 ],1141});
14 unmodified lines
1156 [new Readable()],1157 [new Uint8Array()],1158 ],1159});1055expectError(execaSync('unicorns', {stdio: [[stringOrUint8ArrayGenerator]]}));1056expectError(execaSync('unicorns', {stdio: [[{transform: stringOrUint8ArrayGenerator}]]}));1160expectError(execaSync('unicorns', {stdio: [[unknownArrayGenerator]]}));1161expectError(execaSync('unicorns', {stdio: [[{transform: unknownArrayGenerator}]]}));1162expectError(execaSync('unicorns', {stdio: [[new WritableStream()]]}));1163expectError(execaSync('unicorns', {stdio: [[new ReadableStream()]]}));1164expectError(execaSync('unicorns', {stdio: [[['foo', 'bar']]]}));1165expectError(execaSync('unicorns', {stdio: [[[new Uint8Array(), new Uint8Array()]]]}));1166expectError(execaSync('unicorns', {stdio: [[[{}, {}]]]}));1167expectError(execaSync('unicorns', {stdio: [[emptyStringGenerator()]]}));1168expectError(execaSync('unicorns', {stdio: [[asyncStringGenerator()]]}));1169execa('unicorns', {serialization: 'advanced'});1170expectError(execaSync('unicorns', {serialization: 'advanced'}));
139 unmodified lines
modified:readme.md+10 added-8 removed
45 unmodified lines
46- [Scripts interface](#scripts-interface), like `zx`.47- Improved [Windows support](https://github.com/IndigoUnited/node-cross-spawn#why), including [shebang](https://en.wikipedia.org/wiki/Shebang_(Unix)) binaries.48- Executes [locally installed binaries](#preferlocal) without `npx`.49- [Cleans up](#cleanup) child processes when the parent process ends.50- Redirect [`stdin`](#stdin)/[`stdout`](#stdout-1)/[`stderr`](#stderr-1) to files, streams, iterables, strings or `Uint8Array`.50- Redirect [`stdin`](#stdin)/[`stdout`](#stdout-1)/[`stderr`](#stderr-1) from/to files, streams, iterables, strings, `Uint8Array` or [objects](docs/transform.md#object-mode).51- [Transform](docs/transform.md) `stdin`/`stdout`/`stderr` with simple functions.52- Iterate over [each text line](docs/transform.md#binary-data) output by the process.53- [Graceful termination](#optionsforcekillaftertimeout).54- Get [interleaved output](#all) from `stdout` and `stderr` similar to what is printed on the terminal.
355 unmodified lines
410This is `undefined` when the process could not be spawned or was terminated by a [signal](#signal-1).411412#### stdout413414Type: `string | Uint8Array | undefined`414Type: `string | Uint8Array | unknown[] | undefined`415416The output of the process on `stdout`.417418This is `undefined` if the [`stdout`](#stdout-1) option is set to [`'inherit'`, `'ipc'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio).418This is `undefined` if the [`stdout`](#stdout-1) option is set to [`'inherit'`, `'ipc'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio). This is an array if the `stdout` option is a [transform in object mode](docs/transform.md#object-mode).419420#### stderr421422Type: `string | Uint8Array | undefined`422Type: `string | Uint8Array | unknown[] | undefined`423424The output of the process on `stderr`.425426This is `undefined` if the [`stderr`](#stderr-1) option is set to [`'inherit'`, `'ipc'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio).426This is `undefined` if the [`stderr`](#stderr-1) option is set to [`'inherit'`, `'ipc'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio). This is an array if the `stderr` option is a [transform in object mode](docs/transform.md#object-mode).427428#### all429430Type: `string | Uint8Array | undefined`430Type: `string | Uint8Array | unknown[] | undefined`431432The output of the process with `stdout` and `stderr` [interleaved](#ensuring-all-output-is-interleaved).433434This is `undefined` if either:435- the [`all` option](#all-2) is `false` (the default value)436- both [`stdout`](#stdout-1) and [`stderr`](#stderr-1) options are set to [`'inherit'`, `'ipc'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio)437438This is an array if either the `stdout` or `stderr` option is a [transform in object mode](docs/transform.md#object-mode).439440#### stdio441440Type: `Array<string | Uint8Array | undefined>`442Type: `Array<string | Uint8Array | unknown[] | undefined>`443444The output of the process on [`stdin`](#stdin), [`stdout`](#stdout-1), [`stderr`](#stderr-1) and [other file descriptors](#stdio-1).445444Items are `undefined` when their corresponding [`stdio`](#stdio-1) option is set to [`'inherit'`, `'ipc'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio).446Items are `undefined` when their corresponding [`stdio`](#stdio-1) option is set to [`'inherit'`, `'ipc'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio). Items are arrays when their corresponding `stdio` option is a [transform in object mode](docs/transform.md#object-mode).447448#### failed449450Type: `boolean`
498 unmodified lines