setup.js
This file
Path
lib/pipe/setup.js
230 lines · 7.8 KiB · JavaScript
Last changed by
Add `.readableStream()`, `.writableStream()` and `.transformStream()` methods (#1254)Sindre Sorhusbefore adoption29d9cfc
History of this fileTake it
The walk stopped after 200 commits: lines older than c8a6ed7 point at it.
Improve documentation (#1003)ehmickybefore adoptionc8a6ed7
line 1why, one step back1import isPlainObject from 'is-plain-obj';Expose the destination subprocess methods on `.pipe()` (#1252)Sindre Sorhusbefore adoptionc31c94c
lines 2–5why, one step back2import {SUBPROCESS_OPTIONS} from '../arguments/fd-options.js';3import {initializeConcurrentStreams} from '../convert/concurrent.js';4import {createIterable} from '../convert/iterable.js';5import {createReadable} from '../convert/readable.js';Add `.readableStream()`, `.writableStream()` and `.transformStream()` methods (#1254)Sindre Sorhusbefore adoption29d9cfc
line 6why, one step back6import {createReadableStream} from '../convert/web.js';Expose the destination subprocess methods on `.pipe()` (#1252)Sindre Sorhusbefore adoptionc31c94c
lines 7–8why, one step back7import {internalGetOneMessageOptions} from '../ipc/get-one.js';8import {internalGetEachMessageOptions} from '../ipc/get-each.js';Improve documentation (#1003)ehmickybefore adoptionc8a6ed7
lines 9–24why, one step back9import {normalizePipeArguments} from './pipe-arguments.js';10import {handlePipeArgumentsError} from './throw.js';11import {waitForBothSubprocesses} from './sequence.js';12import {pipeSubprocessStream} from './streaming.js';13import {unpipeOnAbort} from './abort.js';1415// Pipe a subprocess' `stdout`/`stderr`/`stdio` into another subprocess' `stdin`16export const pipeToSubprocess = (sourceInfo, ...pipeArguments) => {17 if (isPlainObject(pipeArguments[0])) {18 return pipeToSubprocess.bind(undefined, {19 ...sourceInfo,20 boundOptions: {...sourceInfo.boundOptions, ...pipeArguments[0]},21 });22 }2324 const {destination, ...normalizedInfo} = normalizePipeArguments(sourceInfo, ...pipeArguments);Expose the destination subprocess methods on `.pipe()` (#1252)Sindre Sorhusbefore adoptionc31c94c
lines 25–26why, one step back25 const pipeFailureController = new AbortController();26 const promise = handlePipePromise({...normalizedInfo, destination, pipeFailureController});Improve documentation (#1003)ehmickybefore adoptionc8a6ed7
lines 27–32why, one step back27 promise.pipe = pipeToSubprocess.bind(undefined, {28 ...sourceInfo,29 source: destination,30 sourcePromise: promise,31 boundOptions: {},32 });Expose the destination subprocess methods on `.pipe()` (#1252)Sindre Sorhusbefore adoptionc31c94c
line 33why, one step back33 forwardDestinationMethods(promise, destination, pipeFailureController.signal);Improve documentation (#1003)ehmickybefore adoptionc8a6ed7
lines 34–36why, one step back34 return promise;35};36Expose the destination subprocess methods on `.pipe()` (#1252)Sindre Sorhusbefore adoptionc31c94c
lines 37–63why, one step back37/*38The return value of `.pipe()` exposes the destination subprocess' output, but its iteration and stream conversion methods must await the whole pipe so source failures are propagated too. The destination is `undefined` when `.pipe()` was passed invalid arguments, in which case the promise rejects and there is nothing to forward.39*/40const forwardDestinationMethods = (promise, destination, pipeFailureSignal) => {41 if (destination === undefined) {42 return;43 }4445 forwardReadableMethods(promise, destination);46 forwardIpcMethods(promise, destination, pipeFailureSignal);47};4849const forwardReadableMethods = (promise, destination) => {50 const subprocessOptions = SUBPROCESS_OPTIONS.get(destination);51 SUBPROCESS_OPTIONS.set(promise, subprocessOptions);52 promise.stdio = destination.stdio;53 promise.all = destination.all;5455 const {options: {encoding}} = subprocessOptions;56 const concurrentStreams = initializeConcurrentStreams();57 promise[Symbol.asyncIterator] = createIterable.bind(undefined, promise, encoding, {});58 promise.iterable = createIterable.bind(undefined, promise, encoding);59 promise.readable = createPipeReadable.bind(undefined, promise, {60 subprocess: promise,61 concurrentStreams,62 encoding,63 });Add `.readableStream()`, `.writableStream()` and `.transformStream()` methods (#1254)Sindre Sorhusbefore adoption29d9cfc
line 64why, one step back64 promise.readableStream = createReadableStream.bind(undefined, promise);Expose the destination subprocess methods on `.pipe()` (#1252)Sindre Sorhusbefore adoptionc31c94c
lines 65–179why, one step back65 forwardAll(promise, destination);66};6768const forwardAll = (promise, destination) => {69 if (destination.all === undefined) {70 promise.all = undefined;71 return;72 }7374 Object.defineProperty(promise, 'all', {75 get() {76 setAllProperty(promise, destination.all);77 const all = promise.readable({from: 'all'});78 setAllProperty(promise, all);79 return all;80 },81 enumerable: true,82 configurable: true,83 });84};8586const setAllProperty = (promise, value) => {87 Object.defineProperty(promise, 'all', {88 value,89 writable: true,90 enumerable: true,91 configurable: true,92 });93};9495const createPipeReadable = (promise, readableOptions, ...arguments_) => {96 const readable = createReadable(readableOptions, ...arguments_);97 destroyOnPipeFailure(promise, readable);98 return readable;99};100101const destroyOnPipeFailure = async (promise, readable) => {102 try {103 await promise;104 } catch (error) {105 readable.destroy(error);106 }107};108109const forwardIpcMethods = (promise, destination, pipeFailureSignal) => {110 promise.sendMessage = destination.sendMessage;111 promise.getOneMessage = getOnePipeMessage.bind(undefined, destination, pipeFailureSignal);112 promise.getEachMessage = getEachPipeMessage.bind(undefined, promise, destination, pipeFailureSignal);113};114115const getOnePipeMessage = (destination, pipeFailureSignal, ...arguments_) => {116 const controller = new AbortController();117 const messagePromise = destination.getOneMessage(...addPipeOptions(arguments_, controller.signal, internalGetOneMessageOptions));118 return waitForOnePipeMessage(pipeFailureSignal, messagePromise, controller);119};120121const waitForOnePipeMessage = async (pipeFailureSignal, messagePromise, controller) => {122 try {123 return await Promise.race([messagePromise, getSignalRejection(pipeFailureSignal, controller.signal)]);124 } finally {125 controller.abort();126 }127};128129const getSignalRejection = (signal, listenerSignal) => new Promise((_, reject) => {130 if (signal.aborted) {131 reject(signal.reason);132 return;133 }134135 signal.addEventListener('abort', () => {136 reject(signal.reason);137 }, {once: true, signal: listenerSignal});138});139140const getEachPipeMessage = (promise, destination, pipeFailureSignal, ...arguments_) => {141 const controller = new AbortController();142 // Create the destination iterator before awaiting the pipe so option validation stays synchronous.143 const iterator = destination.getEachMessage(...addPipeOptions(arguments_, controller.signal, internalGetEachMessageOptions));144 abortOnSignal(pipeFailureSignal, controller);145 return iterateOnPipeMessages(promise, iterator, controller);146};147148const iterateOnPipeMessages = async function * (promise, iterator, controller) {149 try {150 yield * iterator;151 } finally {152 controller.abort();153 await promise;154 }155};156157const addPipeOptions = (arguments_, signal, internalOptionsSymbol) => {158 if (arguments_[0] === null) {159 // Preserve the public validation error from `getEachMessage(null)` instead of masking it with a pipe failure.160 return arguments_;161 }162163 const [options] = arguments_;164 // The returned pipe promise is awaited by the forwarded IPC iterator, so the destination IPC iterator must not also await the destination subprocess on close.165 return [{...options, [internalOptionsSymbol]: {signal, shouldAwait: false}}];166};167168const abortOnSignal = (signal, controller) => {169 if (signal.aborted) {170 controller.abort();171 return;172 }173174 // Interrupt pending IPC reads when the pipe rejects, including `unpipeSignal` cancellation while the destination keeps running.175 signal.addEventListener('abort', () => {176 controller.abort();177 }, {once: true, signal: controller.signal});178};179Add `.readableStream()`, `.writableStream()` and `.transformStream()` methods (#1254)Sindre Sorhusbefore adoption29d9cfc
line 180why, one step back180// `writable()`, `duplex()`, `writableStream()` and `transformStream()` are intentionally not forwarded: they write to the destination's `stdin`, which is already being piped from the source.Expose the destination subprocess methods on `.pipe()` (#1252)Sindre Sorhusbefore adoptionc31c94c
line 181why, one step back181Improve documentation (#1003)ehmickybefore adoptionc8a6ed7
lines 182–193why, one step back182// Asynchronous logic when piping subprocesses183const handlePipePromise = async ({184 sourcePromise,185 sourceStream,186 sourceOptions,187 sourceError,188 destination,189 destinationStream,190 destinationError,191 unpipeSignal,192 fileDescriptors,193 startTime,Expose the destination subprocess methods on `.pipe()` (#1252)Sindre Sorhusbefore adoptionc31c94c
line 194why, one step back194 pipeFailureController,Improve documentation (#1003)ehmickybefore adoptionc8a6ed7
lines 195–197why, one step back195}) => {196 const maxListenersController = new AbortController();197 try {Expose the destination subprocess methods on `.pipe()` (#1252)Sindre Sorhusbefore adoptionc31c94c
lines 198–207why, one step back198 const subprocessPromises = getSubprocessPromises(sourcePromise, destination);199 handlePipeArgumentsError({200 sourceStream,201 sourceError,202 destinationStream,203 destinationError,204 fileDescriptors,205 sourceOptions,206 startTime,207 });Improve documentation (#1003)ehmickybefore adoptionc8a6ed7
lines 208–218why, one step back208 const mergedStream = pipeSubprocessStream(sourceStream, destinationStream, maxListenersController);209 return await Promise.race([210 waitForBothSubprocesses(subprocessPromises),211 ...unpipeOnAbort(unpipeSignal, {212 sourceStream,213 mergedStream,214 sourceOptions,215 fileDescriptors,216 startTime,217 }),218 ]);Expose the destination subprocess methods on `.pipe()` (#1252)Sindre Sorhusbefore adoptionc31c94c
lines 219–221why, one step back219 } catch (error) {220 pipeFailureController.abort(error);221 throw error;Improve documentation (#1003)ehmickybefore adoptionc8a6ed7
lines 222–230why, one step back222 } finally {223 maxListenersController.abort();224 }225};226227// `.pipe()` awaits the subprocess promises.228// When invalid arguments are passed to `.pipe()`, we throw an error, which prevents awaiting them.229// We need to ensure this does not create unhandled rejections.230const getSubprocessPromises = (sourcePromise, destination) => Promise.allSettled([sourcePromise, destination]);