Skip to content
Myr

Allow `stdout`/`stderr` option to be a `WritableStream` (#619)

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

authored by ehmicky · committed by GitHub · parent fcf648e · Browse files · 6 files+147 added−45 removed
This commit

State

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

Diff stats

6 files+147 added−45 removed

  • tests:+38 added−2 removed
  • other:+109 added−43 removed

6 files+147 added−45 removed

modified:lib/stdio.js+87 added-33 removed
1import {createReadStream, readFileSync} from 'node:fs';2import {isAbsolute} from 'node:path';3import {Readable} from 'node:stream';3import {Readable, Writable} from 'node:stream';4import {isStream as isNodeStream} from 'is-stream';56const aliases = ['stdin', 'stdout', 'stderr'];7
4 unmodified lines
12 && !isNodeStream(stdinOption)13 && !isReadableStream(stdinOption)14 && (typeof stdinOption[Symbol.asyncIterator] === 'function' || typeof stdinOption[Symbol.iterator] === 'function');1516const getIterableStdin = stdioArray => isIterableStdin(stdioArray[0])17 ? stdioArray[0]16const getIterableStdin = stdioOption => isIterableStdin(stdioOption)17 ? stdioOption18 : undefined;1920const isUrlInstance = stdioOption => Object.prototype.toString.call(stdioOption) === '[object URL]';21const hasFileProtocol = url => url.protocol === 'file:';
4 unmodified lines
26const isFilePath = stdioOption => typeof stdioOption === 'string' && stringIsFilePath(stdioOption);27const isUnknownStdioString = stdioOption => typeof stdioOption === 'string' && !stringIsFilePath(stdioOption) && !KNOWN_STDIO.has(stdioOption);2829const isReadableStream = stdioOption => Object.prototype.toString.call(stdioOption) === '[object ReadableStream]';30const isWritableStream = stdioOption => Object.prototype.toString.call(stdioOption) === '[object WritableStream]';3132// Check whether the `stdin` option results in `spawned.stdin` being `undefined`.33// We use a deny list instead of an allow list to be forward compatible with new options.33const cannotPipeStdio = stdioOption => NO_PIPE_STDIO.has(stdioOption)34 || isNodeStream(stdioOption)35 || isReadableStream(stdioOption)36 || typeof stdioOption === 'number'37 || isIterableStdin(stdioOption)38 || isFileUrl(stdioOption)39 || isFilePath(stdioOption);34const cannotPipeStdin = stdinOption => NO_PIPE_STDIO.has(stdinOption)35 || isNodeStream(stdinOption)36 || isReadableStream(stdinOption)37 || typeof stdinOption === 'number'38 || isIterableStdin(stdinOption)39 || isFileUrl(stdinOption)40 || isFilePath(stdinOption);4142const NO_PIPE_STDIO = new Set(['ipc', 'ignore', 'inherit']);43const KNOWN_STDIO = new Set([...NO_PIPE_STDIO, 'overlapped', 'pipe']);44
12 unmodified lines
57 if (input !== undefined && inputFile !== undefined) {58 throw new TypeError('The `input` and `inputFile` options cannot be both set.');59 }6060 const noPipeStdin = cannotPipeStdio(stdioArray[0]);61 const noPipeStdin = cannotPipeStdin(stdioArray[0]);62 if (noPipeStdin && input !== undefined) {63 throw new TypeError('The `input` and `stdin` options cannot be both set.');64 }65
3 unmodified lines
6970 validateFileSdio(stdioArray[0]);71};7272const getStdioStreams = (stdioArray, {input, inputFile}) => {73 const iterableStdin = getIterableStdin(stdioArray);73const getStdioStreams = (stdioArray, {input, inputFile}) => ({74 ...getStdinStream(stdioArray[0], input, inputFile),75 ...getStdoutStream(stdioArray[1]),76 ...getStderrStream(stdioArray[2]),77});7879const getStdinStream = (stdinOption, input, inputFile) => {80 const iterableStdin = getIterableStdin(stdinOption);8182 if (iterableStdin !== undefined) {83 return {stdinStream: Readable.from(iterableStdin)};84 }8579 if (isReadableStream(stdioArray[0])) {80 return {stdinStream: Readable.fromWeb(stdioArray[0])};86 if (isReadableStream(stdinOption)) {87 return {stdinStream: Readable.fromWeb(stdinOption)};88 }8983 if (isFileUrl(stdioArray[0]) || isFilePath(stdioArray[0])) {84 return {stdinStream: createReadStream(stdioArray[0])};90 if (isFileUrl(stdinOption) || isFilePath(stdinOption)) {91 return {stdinStream: createReadStream(stdinOption)};92 }9394 if (inputFile !== undefined) {95 return {stdinStream: createReadStream(inputFile)};
9 unmodified lines
105106 return {stdinInput: input};107};108102// When the `stdin: iterable`, `input` or `inputFile` option is used, we pipe to `spawned.stdin`.103// Therefore the `stdin` option must be either `pipe` or `overlapped`. Other values do not set `spawned.stdin`.104const willPipeStdin = (index, {stdinStream, stdinInput}) =>105 index === 0 && (stdinStream !== undefined || stdinInput !== undefined);109const getStdoutStream = stdoutOption => {110 const stdoutStream = getOutputStream(stdoutOption);111 return stdoutStream === undefined ? {} : {stdoutStream};112};113114const getStderrStream = stderrOption => {115 const stderrStream = getOutputStream(stderrOption);116 return stderrStream === undefined ? {} : {stderrStream};117};118119const getOutputStream = stdioOption => {120 if (isWritableStream(stdioOption)) {121 return Writable.fromWeb(stdioOption);122 }123};124125// When the `stdin: Iterable | ReadableStream | URL | filePath`, `input` or `inputFile` option is used, we pipe to `spawned.std*`.126// Therefore the `std*` options must be either `pipe` or `overlapped`. Other values do not set `spawned.std*`.127const willPipeStreams = (index, {stdinStream, stdinInput, stdoutStream, stderrStream}) => {128 if (index === 0) {129 return stdinStream !== undefined || stdinInput !== undefined;130 }131132 if (index === 1) {133 return stdoutStream !== undefined;134 }135136 if (index === 2) {137 return stderrStream !== undefined;138 }139140 return false;141};142143const transformStdioItem = (stdioItem, index, stdioStreams) =>108 willPipeStdin(index, stdioStreams) && stdioItem !== 'overlapped' ? 'pipe' : stdioItem;144 willPipeStreams(index, stdioStreams) && stdioItem !== 'overlapped' ? 'pipe' : stdioItem;145146const transformStdio = (stdio, stdioStreams) => Array.isArray(stdio)147 ? stdio.map((stdioItem, index) => transformStdioItem(stdioItem, index, stdioStreams))148 : stdio;
8 unmodified lines
157 return stdioStreams;158};159160// Handle `input`, `inputFile` and `stdin` options, after spawning, in async mode125export const pipeStdioOption = (spawned, {stdinStream, stdinInput}) => {161export const pipeStdioOption = (spawned, {stdinStream, stdinInput, stdoutStream, stderrStream}) => {162 if (stdinStream !== undefined) {163 stdinStream.pipe(spawned.stdin);128 return;164 }165166 if (stdinInput !== undefined) {167 spawned.stdin.end(stdinInput);168 }169170 if (stdoutStream !== undefined) {171 spawned.stdout.pipe(stdoutStream);172 }173174 if (stderrStream !== undefined) {175 spawned.stderr.pipe(stderrStream);176 }177};178179const transformStdioItemSync = stdioItem => isFileUrl(stdioItem) || isFilePath(stdioItem) ? 'pipe' : stdioItem;180181const transformStdioSync = stdio => Array.isArray(stdio)182 ? stdio.map(stdioItem => transformStdioItemSync(stdioItem))183 : stdio;184142const validateInputOptionsSync = (stdioArray, input) => {143 if (getIterableStdin(stdioArray) !== undefined) {185const validateInputOptionsSync = (stdinOption, input) => {186 if (getIterableStdin(stdinOption) !== undefined) {187 throw new TypeError('The `stdin` option cannot be an iterable in sync mode');188 }189147 if (isReadableStream(stdioArray[0])) {190 if (isReadableStream(stdinOption)) {191 throw new TypeError('The `stdin` option cannot be a stream in sync mode');192 }193194 if (isNodeStream(input)) {195 throw new TypeError('The `input` option cannot be a stream in sync mode');196 }197};198156const getInputOption = (stdio, {input, inputFile}) => {157 const stdioArray = arrifyStdio(stdio);199const validateOutputOptionsSync = (stdioOption, optionName) => {200 if (isWritableStream(stdioOption)) {201 throw new TypeError(`The \`${optionName}\` option cannot be a stream in sync mode`);202 }203};204205const validateOptionsSync = (stdioArray, {input, inputFile}) => {206 validateInputOptions(stdioArray, input, inputFile);159 validateInputOptionsSync(stdioArray, input);207 validateInputOptionsSync(stdioArray[0], input);208 validateOutputOptionsSync(stdioArray[1], 'stdout');209 validateOutputOptionsSync(stdioArray[2], 'stderr');210};211212const getInputOption = (stdinOption, {input, inputFile}) => {161 if (isFileUrl(stdioArray[0]) || isFilePath(stdioArray[0])) {162 return readFileSync(stdioArray[0]);213 if (isFileUrl(stdinOption) || isFilePath(stdinOption)) {214 return readFileSync(stdinOption);215 }216217 if (inputFile !== undefined) {218 return readFileSync(inputFile);
4 unmodified lines
223224// Handle `input`, `inputFile` and `stdin` options, before spawning, in sync mode225export const handleInputOption = options => {226 const stdio = normalizeStdio(options);227 const stdioArray = arrifyStdio(stdio);228 validateOptionsSync(stdioArray, options);229176 const input = getInputOption(stdio, options);230 const input = getInputOption(stdioArray[0], options);231 if (input !== undefined) {232 options.input = input;233 }234
50 unmodified lines
modified:lib/stream.js+4 added-4 removed
modified:test/stream.js+38 added-2 removed
184 unmodified lines
185 }, {message: /`inputFile` and `stdin` options/});186});187188test('stdin option handles errors in iterables', async t => {189 const {originalMessage} = await t.throwsAsync(() => execa('stdin.js', {stdin: throwingGenerator()}));189 const {originalMessage} = await t.throwsAsync(execa('stdin.js', {stdin: throwingGenerator()}));190 t.is(originalMessage, 'generator error');191});192193const testWritableStreamError = async (t, streamName) => {194 const writableStream = new WritableStream({195 start(controller) {196 controller.error(new Error('foobar'));197 },198 });199 const {originalMessage} = await t.throwsAsync(execa('noop.js', {[streamName]: writableStream}));200 t.is(originalMessage, 'foobar');201};202203test('stdout option handles errors in WritableStream', testWritableStreamError, 'stdout');204test('stderr option handles errors in WritableStream', testWritableStreamError, 'stderr');205206test('input option can be a String', async t => {207 const {stdout} = await execa('stdin.js', {input: 'foobar'});208 t.is(stdout, 'foobar');209});
39 unmodified lines
249 const {stdout} = await execa('stdin.js', {stdin});250 t.is(stdout, 'howdy');251});252253const testWritableStream = async (t, streamName, fixtureName) => {254 const result = [];255 const writableStream = new WritableStream({256 write(chunk) {257 result.push(chunk);258 },259 });260 await execa(fixtureName, ['foobar'], {[streamName]: writableStream});261 t.is(result.join(''), 'foobar\n');262};263264test('stdout can be a WritableStream', testWritableStream, 'stdout', 'noop.js');265test('stderr can be a WritableStream', testWritableStream, 'stderr', 'noop-err.js');266267test('stdin cannot be a ReadableStream when input is used', t => {268 const stdin = Stream.Readable.toWeb(Stream.Readable.from('howdy'));269 t.throws(() => {270 execa('stdin.js', {stdin, input: 'foobar'});
109 unmodified lines
380 });381 t.is(stdout, undefined);382});383357test('input cannot be a stream in sync mode', t => {384test('input cannot be a Node.js Readable in sync mode', t => {385 t.throws(() => {386 execaSync('stdin.js', {input: new Stream.PassThrough()});387 }, {message: /The `input` option cannot be a stream in sync mode/});388});
4 unmodified lines
393 execaSync('stdin.js', {stdin});394 }, {message: /The `stdin` option cannot be a stream in sync mode/});395});396397const testWritableStreamSync = (t, streamName) => {398 t.throws(() => {399 execaSync('noop.js', {[streamName]: new WritableStream()});400 }, {message: new RegExp(`The \`${streamName}\` option cannot be a stream in sync mode`)});401};402403test('stdout cannot be a WritableStream in sync mode', testWritableStreamSync, 'stdout');404test('stderr cannot be a WritableStream in sync mode', testWritableStreamSync, 'stderr');405406test('stdin can be a file URL - sync', t => {407 const inputFile = tempfile();408 fs.writeFileSync(inputFile, 'howdy');409 const stdin = pathToFileURL(inputFile);
181 unmodified lines
modified:index.d.ts+11 added-3 removed
18 unmodified lines
19 | URL20 | string21 | ReadableStream;2223export type StdoutStderrOption =24 | StdioOption25 | WritableStream;2627type EncodingOption =28 | 'utf8'29 // eslint-disable-next-line unicorn/text-encoding-identifier-case30 | 'utf-8'
66 unmodified lines
9798 /**99 Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).10097 It can also be a file path, a file URL, a web stream ([`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream)) an [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) or an [`AsyncIterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols), providing neither [`execaSync()`](#execasyncfile-arguments-options), the [`input` option](#input) nor the [`inputFile` option](#inputfile) is used. If the file path is relative, it must start with `.`.101 It can also be a file path, a file URL, a web stream ([`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream)), an [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) or an [`AsyncIterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols), unless either [`execaSync()`](#execasyncfile-arguments-options), the [`input` option](#input) or the [`inputFile` option](#inputfile) is used. If the file path is relative, it must start with `.`.102103 @default `inherit` with `$`, `pipe` otherwise104 */105 readonly stdin?: StdinOption;106107 /**108 Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).109110 It can also be a web stream ([`WritableStream`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream)), unless [`execaSync()`](#execasyncfile-arguments-options) is used.111112 @default 'pipe'113 */108 readonly stdout?: StdioOption;114 readonly stdout?: StdoutStderrOption;115116 /**117 Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).118119 It can also be a web stream ([`WritableStream`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream)), unless [`execaSync()`](#execasyncfile-arguments-options) is used.120121 @default 'pipe'122 */115 readonly stderr?: StdioOption;123 readonly stderr?: StdoutStderrOption;124125 /**126 Setting this to `false` resolves the promise with the error instead of rejecting it.127
886 unmodified lines
modified:index.test-d.ts+2 added
173 unmodified lines
174execa('unicorns', {stdout: 'ipc'});175execa('unicorns', {stdout: 'ignore'});176execa('unicorns', {stdout: 'inherit'});177execa('unicorns', {stdout: process.stdout});178execa('unicorns', {stdout: new WritableStream()});179execa('unicorns', {stdout: 1});180execa('unicorns', {stdout: undefined});181execa('unicorns', {stderr: 'pipe'});182execa('unicorns', {stderr: 'overlapped'});183execa('unicorns', {stderr: 'ipc'});184execa('unicorns', {stderr: 'ignore'});185execa('unicorns', {stderr: 'inherit'});186execa('unicorns', {stderr: process.stderr});187execa('unicorns', {stderr: new WritableStream()});188execa('unicorns', {stderr: 1});189execa('unicorns', {stderr: undefined});190execa('unicorns', {all: true});191execa('unicorns', {reject: false});
179 unmodified lines
modified:readme.md+5 added-3 removed
562 unmodified lines
563Default: `inherit` with [`$`](#command), `pipe` otherwise564565Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).566567It can also be a file path, a file URL, a web stream ([`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream)) an [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) or an [`AsyncIterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols), providing neither [`execaSync()`](#execasyncfile-arguments-options), the [`input` option](#input) nor the [`inputFile` option](#inputfile) is used. If the file path is relative, it must start with `.`.567It can also be a file path, a file URL, a web stream ([`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream)), an [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) or an [`AsyncIterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols), unless either [`execaSync()`](#execasyncfile-arguments-options), the [`input` option](#input) or the [`inputFile` option](#inputfile) is used. If the file path is relative, it must start with `.`.568569#### stdout570571Type: `string | number | Stream | undefined`\571Type: `string | number | stream.Writable | WritableStream | undefined`\572Default: `pipe`573574Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).575576It can also be a web stream ([`WritableStream`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream)), unless [`execaSync()`](#execasyncfile-arguments-options) is used.577578#### stderr579578Type: `string | number | Stream | undefined`\580Type: `string | number | stream.Writable | WritableStream | undefined`\581Default: `pipe`582583Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).584
231 unmodified lines