Fix `stdin` iterables and input transforms edge cases
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Sindre Sorhus · committed by Sindre Sorhus · parent 5f80cde · Browse files · 11 files·+271 added−28 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
11 files+271 added−28 removed
- tests:+190 added−9 removed
- other:+81 added−19 removed
Provenance
- Commit
6925cc3- Tree
27689d1- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
5f80cde
11 files changed+271 added−28 removed
modified:lib/io/input-sync.js+15 added-4 removed
25 unmodified lines2627282930313031323334353637383940414243444546434748454950515253545556575825 unmodified lines throw new TypeError(`Only the \`stdin\` option, not \`${optionName}\`, can be ${TYPE_TO_MESSAGE[type]} with synchronous methods.`); }
// All input sources are merged into a single list of chunks, like asynchronous methods merge input streams, so that transforms receive a single stream of data: line splitting spans all sources and `final` runs only once. // Files are read lazily, so that a read failure is reported like any other early error const chunks = allStdioItems.flatMap(({contents}) => typeof contents === 'function' ? contents() : contents); // Files and iterables are read lazily, so that a read failure is reported like any other early error const chunks = allStdioItems.flatMap(({type, contents}) => getChunks(type, typeof contents === 'function' ? contents() : contents)); options.input = applyInputGeneratorsSync(chunks, stdioItems, options.encoding);};
// Like with asynchronous methods, an empty input is not passed as a chunk, otherwise binary transforms, which do not split lines, would run on it.// Iterables are left as is, since each of their items is a chunk.const getChunks = (type, chunks) => type === 'iterable' ? chunks : chunks.filter(chunk => chunk.length > 0);
const applyInputGeneratorsSync = (chunks, stdioItems, encoding) => { // Input transforms use UTF-8 with text encodings, since those only apply to the output const newContents = runGeneratorsSync(chunks, stdioItems, getInputEncoding(encoding), true); validateSerializable(newContents); return joinToUint8Array(newContents);};
const validateSerializable = newContents => { const invalidItem = newContents.find(item => typeof item !== 'string' && !isUint8Array(item)); const invalidItem = newContents.find(item => !isSerializableInput(item)); if (invalidItem !== undefined) { throw new TypeError(`The \`stdin\` option is invalid: when passing objects as input, a transform must be used to serialize them to strings or Uint8Arrays: ${invalidItem}.`); throwOnSerializableInput('stdin', invalidItem); }};
// Values written to the subprocess, which is not in object modeexport const isSerializableInput = item => typeof item === 'string' || isUint8Array(item);
export const throwOnSerializableInput = (optionName, invalidItem) => { throw new TypeError(`The \`${optionName}\` option is invalid: when passing objects as input, a transform must be used to serialize them to strings or Uint8Arrays: ${invalidItem}.`);};modified:lib/resolve/wait-stream.js+15 added-2 removed
20 unmodified lines2122232425252627282910 unmodified lines404142434445464747484950515212 unmodified lines656667686970717273747576777879808182838437 unmodified lines20 unmodified lines writable, }), ]); } catch (error) { if (!state.stdinCleanedUp) { if (!state.stdinCleanedUp && !isInputTransformAbort(stream, fdNumber, streamInfo, error)) { handleStreamError(error, fdNumber, streamInfo, isSameDirection); } } finally { abortController.abort();10 unmodified lines// For example, `stdin: 'pipe'` is implemented as a TCP socket, and its `.destroy()` method waits for TCP disconnection.// Therefore `.destroy()` might end before or after subprocess exit, based on OS speed and load.// The only way to detect this is to spy on `subprocess.stdin._destroy()` by wrapping it.// If `subprocess.exitCode` or `subprocess.signalCode` is set, it means `.destroy()` is being called by Node.js itself.// With an input transform, `subprocess.stdin` is that transform, so Node.js destroys it instead of the original `stdin`.const handleStdinDestroy = (stream, {originalStreams, subprocess}) => { const [originalStdin] = originalStreams; const state = {stdinCleanedUp: false}; if (stream === originalStdin) { if (stream === originalStdin || stream === subprocess.stdin) { spyOnStdinDestroy(stream, subprocess, state); }
return state;12 unmodified lines state.stdinCleanedUp = true; }};
// An input transform writes to the subprocess' original stream. When that stream is closed first, e.g. when the subprocess exits without reading its input, the transform is aborted.// Like `EPIPE` with `stdin: 'pipe'`, this is not an error.// When the transform is aborted by the user instead, the original stream is still open at that point.const isInputTransformAbort = (stream, fdNumber, streamInfo, error) => { const originalStream = streamInfo.originalStreams[fdNumber]; return stream !== originalStream && isInputFileDescriptor(streamInfo, fdNumber) && originalStream?.destroyed === true // A `TransformStream` is aborted with an `AbortError` && (isStreamAbort(error) || error?.code === 'ABORT_ERR');};
// We ignore EPIPEs on writable streams and aborts on readable streams since those can happen normally.// When one stream errors, the error is propagated to the other streams on the same file descriptor.// Those other streams might have a different direction due to the above.// When this happens, the direction of both the initial stream and the others should then be taken into account.37 unmodified linesmodified:lib/stdio/handle-async.js+38 added-9 removed
1 unmodified line2 import {Buffer} from 'node:buffer';3 import {Readable, Writable, Duplex} from 'node:stream';4 import {generatorToStream} from '../transform/generator.js';5 import {getInputEncoding} from '../arguments/encoding-option.js';6+import {isSerializableInput, throwOnSerializableInput} from '../io/input-sync.js';7 import {handleStdio} from './handle.js';8 import {TYPE_TO_MESSAGE} from './type.js';9 10 // Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in async mode9 unmodified lines20 fileNumber: forbiddenIfAsync,21 generator: generatorToStream,22 asyncGenerator: generatorToStream,23 nodeStream: ({value}) => ({stream: value}),23- webTransform({value: {transform, writableObjectMode, readableObjectMode}}) {24- const objectMode = writableObjectMode || readableObjectMode;25- const stream = Duplex.fromWeb(transform, {objectMode});26- return {stream};27- },24+ // `Duplex.fromWeb()` uses the same `objectMode` for both sides25+ webTransform: ({value: {transform, writableObjectMode, readableObjectMode}}) => ({26+ stream: Duplex.from({27+ writable: Writable.fromWeb(transform.writable, {objectMode: writableObjectMode}),28+ readable: Readable.fromWeb(transform.readable, {objectMode: readableObjectMode}),29+ }),30+ }),31 duplex: ({value: {transform}}) => ({stream: transform}),32 native() {},33 };34 35+// Without transforms in object mode, iterable values are written to the subprocess, which only accepts strings and Uint8Arrays.36+// `Readable.from()` emits the values of synchronous iterables on a later tick, where `subprocess.stdin.write()` throwing would crash the current process. Throwing while iterating errors the stream instead.37+// Synchronous iterables must stay synchronous, otherwise their order would change when they are combined with other input sources.38+const validateIterable = function * (iterable, optionName) {39+ for (const value of iterable) {40+ validateIterableValue(value, optionName);41+ yield value;42+ }43+};44+45+const validateAsyncIterable = async function * (iterable, optionName) {46+ for await (const value of iterable) {47+ validateIterableValue(value, optionName);48+ yield value;49+ }50+};51+52+const validateIterableValue = (value, optionName) => {53+ if (!isSerializableInput(value)) {54+ throwOnSerializableInput(optionName, value);55+ }56+};57+58+// Empty input is not passed as a chunk, otherwise binary transforms, which do not split lines, would run on it59+const readableFromChunk = chunk => Readable.from(chunk.length === 0 ? [] : [chunk]);60+61 // Input transforms use UTF-8 with text encodings, since those only apply to the output62 const generatorToInputStream = (stdioItem, {encoding}) => generatorToStream(stdioItem, {encoding: getInputEncoding(encoding)});63 64 const addPropertiesAsync = {3 unmodified lines68 asyncGenerator: generatorToInputStream,69 fileUrl: ({value}) => ({stream: createReadStream(value)}),70 filePath: ({value: {file}}) => ({stream: createReadStream(file)}),71 webStream: ({value}) => ({stream: Readable.fromWeb(value)}),43- iterable: ({value}) => ({stream: Readable.from(value)}),44- asyncIterable: ({value}) => ({stream: Readable.from(value)}),45- string: ({value}) => ({stream: Readable.from(value)}),46- uint8Array: ({value}) => ({stream: Readable.from(Buffer.from(value))}),72+ iterable: ({value, optionName}, options, objectMode) => ({stream: Readable.from(objectMode ? value : validateIterable(value, optionName))}),73+ asyncIterable: ({value, optionName}, options, objectMode) => ({stream: Readable.from(objectMode ? value : validateAsyncIterable(value, optionName))}),74+ string: ({value}) => ({stream: readableFromChunk(value)}),75+ uint8Array: ({value}) => ({stream: readableFromChunk(Buffer.from(value))}),76 },77 output: {78 ...addProperties,79 fileUrl: ({value}) => ({stream: createWriteStream(value)}),8 unmodified linesmodified:lib/stdio/handle-sync.js+10 added-2 removed
26 unmodified lines27 28 return forbiddenNativeIfSync(stdioItem);29 };30 31+// For the same reason, an input transform can only be used with `stdin`, which is fed with the `input` option32+const forbiddenInputTransformIfSync = ({optionName}) => {33+ if (optionName !== 'stdin') {34+ throw new TypeError(`Only the \`stdin\` option, not \`${optionName}\`, can be an input transform with synchronous methods.`);35+ }36+};37+38 const throwInvalidSyncValue = (optionName, value) => {39 throw new TypeError(`The \`${optionName}\` option cannot be ${value} with synchronous methods.`);40 };41 12 unmodified lines54 55 const addPropertiesSync = {56 input: {57 ...addProperties,58+ generator: forbiddenInputTransformIfSync,59 native: forbiddenNativeInputIfSync,52- // Files are read lazily, so that a file which cannot be read is reported like any other early error, instead of being thrown as a raw error60+ // Files and iterables are read lazily, so that a file which cannot be read, or an iterable which throws, is reported like any other early error, instead of being thrown as a raw error61 fileUrl: ({value}) => ({contents: () => [bufferToUint8Array(readFileSync(value))]}),62 filePath: ({value: {file}}) => ({contents: () => [bufferToUint8Array(readFileSync(file))]}),63 fileNumber: forbiddenIfSync,56- iterable: ({value}) => ({contents: [...value]}),64+ iterable: ({value}) => ({contents: () => [...value]}),65 string: ({value}) => ({contents: [value]}),66 // `contents` is already set when reading from a file descriptor67 uint8Array: ({value, contents = [value]}) => ({contents}),68 },10 unmodified linesmodified:lib/stdio/handle.js+3 added-2 removed
209 unmodified lines210 finalFileDescriptor.stdioItems.push(addStreamProperties({211 stdioItem,212 addProperties,213 direction,214+ objectMode,215 options,216 fileDescriptors,217 isSync,218 }));219 }220 };221 221-const addStreamProperties = ({stdioItem, addProperties, direction, options, fileDescriptors, isSync}) => {222+const addStreamProperties = ({stdioItem, addProperties, direction, objectMode, options, fileDescriptors, isSync}) => {223 const duplicateStream = getDuplicateStream({224 stdioItem,225 direction,226 fileDescriptors,5 unmodified lines232 }233 234 return {235 ...stdioItem,235- ...addProperties[direction][stdioItem.type](stdioItem, options),236+ ...addProperties[direction][stdioItem.type](stdioItem, options, objectMode),237 };238 };239 240 // The stream error handling is performed by the piping logic above, which cannot be performed before subprocess spawning.27 unmodified linesadded:test/fixtures/nested-input-transform-chunks.js+17 added
1234567891011121314151617#!/usr/bin/env nodeimport process from 'node:process';import {execa, execaSync} from '../../index.js';
// Prints the number of chunks a binary input transform receives, when `stdin` is inherited from the current processconst chunks = [];const execaMethod = process.argv[2] === 'sync' ? execaSync : execa;await execaMethod('stdin.js', { stdin: ['inherit', { * transform(chunk) { chunks.push(chunk); yield chunk; }, binary: true, }],});console.log(chunks.length);modified:test/resolve/wait-abort.js+25 added-1 removed
2 unmodified lines3 import test from 'node:test';4 import {assertRejects, assertLike} from '../helpers/assert.js';5 import {execa} from '../../index.js';6 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';7-import {prematureClose} from '../helpers/stdio.js';7+import {prematureClose, getStdio} from '../helpers/stdio.js';8+import {noopGenerator, noopAsyncGenerator} from '../helpers/generator.js';9+import {noopDuplex as noopDuplexTransform} from '../helpers/duplex.js';10+import {foobarString} from '../helpers/input.js';11 import {noopReadable, noopWritable, noopDuplex} from '../helpers/stream.js';12 import {13 endOptionStream,14 destroyOptionStream,88 unmodified lines103 test('Throws abort error when stderr option aborts with no more writes, with a transform', () => testStreamAbortFail(destroyOptionStream, noopWritable(), 2, true));104 test('Throws abort error when stderr option Duplex aborts with no more writes, with a transform', () => testStreamAbortFail(destroyOptionStream, noopDuplex(), 2, true));105 test('Throws abort error when output stdio[*] option aborts with no more writes, with a transform', () => testStreamAbortFail(destroyOptionStream, noopWritable(), 3, true));106 test('Throws abort error when output stdio[*] Duplex option aborts with no more writes, with a transform', () => testStreamAbortFail(destroyOptionStream, noopDuplex(), 3, true));107+108+// Like with `stdin: 'pipe'`, the subprocess does not need to read its input, nor `subprocess.stdin` to be ended109+const testUnusedInputTransform = async (fdNumber, transform) => {110+ const {exitCode} = await execa('empty.js', getStdio(fdNumber, {value: transform, input: true}));111+ assert.equal(exitCode, 0);112+};113+114+test('Passes when the subprocess does not read stdin, with a transform', () => testUnusedInputTransform(0, noopGenerator(false)));115+test('Passes when the subprocess does not read stdin, with an async transform', () => testUnusedInputTransform(0, noopAsyncGenerator(false)));116+test('Passes when the subprocess does not read stdin, with a Duplex', () => testUnusedInputTransform(0, noopDuplexTransform(false)));117+test('Passes when the subprocess does not read stdin, with a TransformStream', () => testUnusedInputTransform(0, {transform: new TransformStream()}));118+test('Passes when the subprocess does not read stdio[*], with a transform', () => testUnusedInputTransform(3, noopGenerator(false)));119+test('Passes when the subprocess does not read stdin, with stdin: "pipe"', () => testUnusedInputTransform(0, 'pipe'));120+test('Passes when the subprocess does not read stdio[*], with stdio[*]: "pipe"', () => testUnusedInputTransform(3, 'pipe'));121+122+test('Passes when the subprocess does not read the stdin transform it is written to', async () => {123+ const subprocess = execa('empty.js', {stdin: noopGenerator(false)});124+ subprocess.stdin.write(foobarString);125+ const {exitCode} = await subprocess;126+ assert.equal(exitCode, 0);127+});modified:test/stdio/direction.js+35 added
103 unmodified lines104 execaSync('empty.js', {...getStdio(3, {value: 'pipe', input: true}), buffer: false});105 }, {message: /can be an input pipe with synchronous methods/});106 });107 108+// Nothing could write to that file descriptor after spawning, so the subprocess would hang reading it109+const testInputTransformSync = stdioOption => {110+ assertThrows(() => {111+ execaSync('stdin-fd.js', ['3'], getStdio(3, stdioOption));112+ }, {message: /Only the `stdin` option, not `stdio\[3\]`, can be an input transform with synchronous methods/});113+};114+115+test('stdio[*] { value: generator, input: true } cannot be used in sync mode', () => testInputTransformSync({116+ * value(line) {117+ yield line;118+ },119+ input: true,120+}));121+test('stdio[*] { value: {transform}, input: true } cannot be used in sync mode', () => testInputTransformSync({122+ value: {123+ * transform(line) {124+ yield line;125+ },126+ },127+ input: true,128+}));129+130+test('stdin { value: generator, input: true } can be used in sync mode', () => {131+ const {stdout} = execaSync('stdin.js', {132+ stdin: {133+ * value(line) {134+ yield line.toUpperCase();135+ },136+ input: true,137+ },138+ input: foobarString,139+ });140+ assert.equal(stdout, foobarString.toUpperCase());141+});142+143 const testDirectionOutputPipe = async (stdioOption, execaMethod) => {144 const {stdio} = await execaMethod('noop-fd.js', ['3', foobarString], getStdio(3, stdioOption));145 assert.equal(stdio[3], foobarString);146 };96 unmodified linesmodified:test/stdio/iterable.js+33 added-7 removed
1 unmodified line2 import {once} from 'node:events';3 import {setImmediate} from 'node:timers/promises';4 import test from 'node:test';5 import {assertThrows, assertRejects} from '../helpers/assert.js';6-import {execa, execaSync} from '../../index.js';6+import {execa, execaSync, ExecaSyncError} from '../../index.js';7 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';8 import {getStdio} from '../helpers/stdio.js';9 import {10 foobarString,86 unmodified lines97 test('stdio[*] option can be an async iterable of objects', () => testObjectIterable(foobarAsyncObjectGenerator(), 3, execa));98 test('stdin option can be an array of objects - sync', () => testObjectIterable([foobarObject], 0, execaSync));99 test('stdin option can be an iterable of objects - sync', () => testObjectIterable(foobarObjectGenerator(), 0, execaSync));100 101+// Writing those objects to `subprocess.stdin` fails, which must not crash the current process102+const testIterableNoGenerators = async (stdioOption, fdNumber) => {103+ await assertRejects(execa('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, stdioOption)), {message: /must be used to serialize/});104+};105+106+test('stdin option cannot be an array of objects without generators', () => testIterableNoGenerators([[foobarObject]], 0));107+test('stdin option cannot be an array of numbers without generators', () => testIterableNoGenerators([[0]], 0));108+test('stdio[*] option cannot be an array of objects without generators', () => testIterableNoGenerators([[foobarObject]], 3));109+test('stdin option cannot be an iterable of objects without generators', () => testIterableNoGenerators(foobarObjectGenerator(), 0));110+test('stdin option cannot be an async iterable of objects without generators', () => testIterableNoGenerators(foobarAsyncObjectGenerator(), 0));111+test('stdin option cannot be an array of strings and objects without generators', () => testIterableNoGenerators([[foobarString, foobarObject]], 0));112+113 const testIterableNoGeneratorsSync = (stdioOption, fdNumber) => {114 assertThrows(() => {115 execaSync('empty.js', getStdio(fdNumber, stdioOption));116 }, {message: /must be used to serialize/});44 unmodified lines161 162 test('stdin option handles errors in iterables', () => testIterableError(0));163 test('stdio[*] option handles errors in iterables', () => testIterableError(3));164 153-const testIterableErrorSync = fdNumber => {165+// Like with asynchronous methods, the iterable's error is reported as the subprocess error166+test('stdin option handles errors in iterables - sync', () => {167 const cause = new Error(foobarString);168 const error = assertThrows(() => {156- execaSync('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, throwingGenerator(cause)().transform()));169+ execaSync('stdin-fd.js', ['0'], getStdio(0, throwingGenerator(cause)().transform()));170 });171+ assert.ok(error instanceof ExecaSyncError);172+ assert.equal(error.cause, cause);158- assert.equal(error, cause);159-};173+ assert.equal(error.stdout, '');174+});175 161-test('stdin option handles errors in iterables - sync', () => testIterableErrorSync(0));162-test('stdio[*] option handles errors in iterables - sync', () => testIterableErrorSync(3));176+test('stdin option handles errors in iterables, reject: false - sync', () => {177+ const cause = new Error(foobarString);178+ const {failed, cause: errorCause} = execaSync('stdin-fd.js', ['0'], {...getStdio(0, throwingGenerator(cause)().transform()), reject: false});179+ assert.equal(failed, true);180+ assert.equal(errorCause, cause);181+});182 183+test('stdio[*] option cannot be an iterable - sync', () => {184+ const error = assertThrows(() => {185+ execaSync('stdin-fd.js', ['3'], getStdio(3, [[foobarString]]));186+ }, {message: /Only the `stdin` option, not `stdio\[3\]`, can be an iterable with synchronous methods/});187+ assert.ok(error instanceof ExecaSyncError);188+});189+190 const testNoIterableOutput = (stdioOption, fdNumber, execaMethod) => {191 assertThrows(() => {192 execaMethod('empty.js', getStdio(fdNumber, stdioOption));193 }, {message: /cannot be an iterable/});45 unmodified linesmodified:test/stdio/web-transform.js+35 added-1 removed
1 import assert from 'node:assert/strict';2 import {promisify} from 'node:util';3 import {gunzip} from 'node:zlib';4 import test from 'node:test';5+import {assertRejects} from '../helpers/assert.js';6 import {execa} from '../../index.js';7 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';7-import {foobarString, foobarUtf16Uint8Array, foobarUint8Array} from '../helpers/input.js';8+import {9+ foobarString,10+ foobarUtf16Uint8Array,11+ foobarUint8Array,12+ foobarObject,13+ foobarObjectString,14+} from '../helpers/input.js';15+import {outputObjectGenerator} from '../helpers/generator.js';16+import {serializeWebTransform, outputObjectWebTransform, noopWebTransform} from '../helpers/web-transform.js';17 18 setFixtureDirectory();19 20 test('Can use CompressionStream()', async () => {9 unmodified lines30 encoding: 'buffer',31 });32 assert.deepEqual(stdout, foobarUint8Array);33 });34+35+// A `TransformStream` has no `objectMode` of its own, so the `objectMode` option applies to its output, while its input uses the previous transform's36+const testWebTransformObjectModeFalse = async (getTransforms, expectedOutput) => {37+ const {stdout} = await execa('noop.js', [foobarString], {stdout: getTransforms()});38+ assert.deepEqual(stdout, expectedOutput);39+};40+41+test('TransformStream with "objectMode: false" can follow an objectMode transform', () => testWebTransformObjectModeFalse(() => [outputObjectGenerator(), serializeWebTransform(false)], foobarObjectString));42+test('TransformStream with "objectMode: false" can follow an objectMode TransformStream', () => testWebTransformObjectModeFalse(() => [outputObjectWebTransform(), serializeWebTransform(false)], foobarObjectString));43+test('TransformStream with "objectMode: false" splits lines after an objectMode transform', () => testWebTransformObjectModeFalse(() => [outputObjectGenerator(), {44+ transform: new TransformStream({45+ transform(object, controller) {46+ controller.enqueue(`${JSON.stringify(object)}\n${JSON.stringify(object)}\n`);47+ },48+ }),49+ objectMode: false,50+}], `${foobarObjectString}\n${foobarObjectString}`));51+test('TransformStream with "objectMode: true" can follow a TransformStream with "objectMode: false"', () => testWebTransformObjectModeFalse(() => [noopWebTransform(false), outputObjectWebTransform()], [foobarObject]));52+53+test('Destroying subprocess.stdin fails the subprocess when it is a TransformStream', async () => {54+ const subprocess = execa('stdin.js', {stdin: new TransformStream()});55+ subprocess.stdin.destroy();56+ const {cause} = await assertRejects(subprocess);57+ assert.equal(cause.code, 'ABORT_ERR');58+});modified:test/transform/generator-input.js+45 added
1 import assert from 'node:assert/strict';2 import {Buffer} from 'node:buffer';3+import {writeFile, rm} from 'node:fs/promises';4 import test from 'node:test';5+import tempfile from 'tempfile';6 import {execa, execaSync} from '../../index.js';7 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';8 import {getStdio} from '../helpers/stdio.js';9 import {148 unmodified lines158 test('Can use webTransforms with subprocess.stdio[*] as input', () => testGeneratorStdioInputPipe(false, false, 'webTransform'));159 test('Can use webTransforms with subprocess.stdio[*] as input, objectMode', () => testGeneratorStdioInputPipe(true, false, 'webTransform'));160 test('Can use webTransforms with subprocess.stdio[*] as input, noop transform', () => testGeneratorStdioInputPipe(false, true, 'webTransform'));161 test('Can use webTransforms with subprocess.stdio[*] as input, objectMode, noop transform', () => testGeneratorStdioInputPipe(true, true, 'webTransform'));162+163+// Like with the output, an empty input is not passed as a chunk to binary transforms, which do not split lines164+const testEmptyInput = async (options, execaMethod) => {165+ const chunks = [];166+ const {stdout} = await execaMethod('stdin.js', {167+ ...options,168+ stdin: {169+ * transform(chunk) {170+ chunks.push(chunk);171+ yield chunk;172+ },173+ binary: true,174+ },175+ });176+ assert.equal(stdout, '');177+ assert.deepEqual(chunks, []);178+};179+180+test('Binary input generators are not called with an empty "input" string', () => testEmptyInput({input: ''}, execa));181+test('Binary input generators are not called with an empty "input" Uint8Array', () => testEmptyInput({input: new Uint8Array()}, execa));182+test('Binary input generators are not called with an empty "input" string, sync', () => testEmptyInput({input: ''}, execaSync));183+test('Binary input generators are not called with an empty "input" Uint8Array, sync', () => testEmptyInput({input: new Uint8Array()}, execaSync));184+185+const testEmptyInputFile = async execaMethod => {186+ const filePath = tempfile();187+ await writeFile(filePath, '');188+ try {189+ await testEmptyInput({inputFile: filePath}, execaMethod);190+ } finally {191+ await rm(filePath);192+ }193+};194+195+test('Binary input generators are not called with an empty "inputFile"', () => testEmptyInputFile(execa));196+test('Binary input generators are not called with an empty "inputFile", sync', () => testEmptyInputFile(execaSync));197+198+const testEmptyInheritedInput = async isSync => {199+ const {stdout} = await execa('nested-input-transform-chunks.js', [isSync ? 'sync' : 'async'], {input: ''});200+ assert.equal(stdout, '0');201+};202+203+test('Binary input generators are not called with an empty inherited stdin', () => testEmptyInheritedInput(false));204+test('Binary input generators are not called with an empty inherited stdin, sync', () => testEmptyInheritedInput(true));