All files / lib/internal/streams pipeline.js

95.17% Statements 256/269
93.1% Branches 81/87
100% Functions 7/7
95.17% Lines 256/269

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 27019x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 139x 139x 139x 139x 139x 112x 139x 139x 139x 139x 134x 134x 134x 134x 134x 134x 134x 12x 134x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 134x 133x 133x 139x 139x 139x 135x 68x 68x 135x 139x 139x 19x 82x 82x 82x 82x 82x 82x 82x 19x 46x 46x 43x 46x 3x 3x 3x     46x 19x 3x 3x 1x 1x 2x 2x 3x 19x 27x 27x 2x 2x 27x 27x 27x     27x 27x 34x 4x 1x   34x 15x 27x 9x 27x 27x 27x 27x 19x 82x 82x 82x 82x 82x 2x 2x 80x 82x 2x 2x 78x 78x 78x 78x 78x 78x 78x 78x 162x 162x 162x 44x 44x 162x 162x 44x 44x 118x 161x 135x 135x 118x 159x 73x 73x 162x 78x 78x 82x 175x 175x 175x 175x 175x 121x 121x 121x 175x 175x 78x 20x 20x 1x 1x 1x 78x 58x 58x         175x 25x 25x 25x 25x 5x 1x 1x 1x 25x 20x 2x 2x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 20x 12x 12x 7x 7x 12x 4x 12x 12x 20x 6x 6x 8x 2x 2x 2x 18x 18x 18x 18x 18x 18x 97x 72x 51x 51x 51x 51x 51x 51x 2x 2x 72x 21x 21x 21x 21x 21x 72x 72x         175x 171x 171x 171x 171x 171x 82x 19x 19x  
// Ported from https://github.com/mafintosh/pump with
// permission from the author, Mathias Buus (@mafintosh).
 
'use strict';
 
const {
  ArrayIsArray,
  SymbolAsyncIterator,
} = primordials;
 
let eos;
 
const { once } = require('internal/util');
const destroyImpl = require('internal/streams/destroy');
const {
  ERR_INVALID_ARG_TYPE,
  ERR_INVALID_RETURN_VALUE,
  ERR_MISSING_ARGS,
  ERR_STREAM_DESTROYED
} = require('internal/errors').codes;
 
const { validateCallback } = require('internal/validators');
 
const {
  isIterable,
  isReadable,
  isStream,
} = require('internal/streams/utils');
 
let EE;
let PassThrough;
let Readable;
 
function destroyer(stream, reading, writing, callback) {
  callback = once(callback);
 
  let finished = false;
  stream.on('close', () => {
    finished = true;
  });
 
  if (eos === undefined) eos = require('internal/streams/end-of-stream');
  eos(stream, { readable: reading, writable: writing }, (err) => {
    finished = !err;
 
    const rState = stream._readableState;
    if (
      err &&
      err.code === 'ERR_STREAM_PREMATURE_CLOSE' &&
      reading &&
      (rState && rState.ended && !rState.errored && !rState.errorEmitted)
    ) {
      // Some readable streams will emit 'close' before 'end'. However, since
      // this is on the readable side 'end' should still be emitted if the
      // stream has been ended and no error emitted. This should be allowed in
      // favor of backwards compatibility. Since the stream is piped to a
      // destination this should not result in any observable difference.
      // We don't need to check if this is a writable premature close since
      // eos will only fail with premature close on the reading side for
      // duplex streams.
      stream
        .once('end', callback)
        .once('error', callback);
    } else {
      callback(err);
    }
  });
 
  return (err) => {
    if (finished) return;
    finished = true;
    destroyImpl.destroyer(stream, err);
    callback(err || new ERR_STREAM_DESTROYED('pipe'));
  };
}
 
function popCallback(streams) {
  // Streams should never be an empty array. It should always contain at least
  // a single stream. Therefore optimize for the average case instead of
  // checking for length === 0 as well.
  validateCallback(streams[streams.length - 1]);
  return streams.pop();
}
 
function makeAsyncIterable(val) {
  if (isIterable(val)) {
    return val;
  } else if (isReadable(val)) {
    // Legacy streams are not Iterable.
    return fromReadable(val);
  }
  throw new ERR_INVALID_ARG_TYPE(
    'val', ['Readable', 'Iterable', 'AsyncIterable'], val);
}
 
async function* fromReadable(val) {
  if (!Readable) {
    Readable = require('internal/streams/readable');
  }
 
  yield* Readable.prototype[SymbolAsyncIterator].call(val);
}
 
async function pump(iterable, writable, finish) {
  if (!EE) {
    EE = require('events');
  }
  let error;
  try {
    if (writable.writableNeedDrain === true) {
      await EE.once(writable, 'drain');
    }
 
    for await (const chunk of iterable) {
      if (!writable.write(chunk)) {
        if (writable.destroyed) return;
        await EE.once(writable, 'drain');
      }
    }
    writable.end();
  } catch (err) {
    error = err;
  } finally {
    finish(error);
  }
}
 
function pipeline(...streams) {
  const callback = once(popCallback(streams));
 
  // stream.pipeline(streams, callback)
  if (ArrayIsArray(streams[0]) && streams.length === 1) {
    streams = streams[0];
  }
 
  if (streams.length < 2) {
    throw new ERR_MISSING_ARGS('streams');
  }
 
  let error;
  let value;
  const destroys = [];
 
  let finishCount = 0;
 
  function finish(err) {
    const final = --finishCount === 0;
 
    if (err && (!error || error.code === 'ERR_STREAM_PREMATURE_CLOSE')) {
      error = err;
    }
 
    if (!error && !final) {
      return;
    }
 
    while (destroys.length) {
      destroys.shift()(error);
    }
 
    if (final) {
      callback(error, value);
    }
  }
 
  let ret;
  for (let i = 0; i < streams.length; i++) {
    const stream = streams[i];
    const reading = i < streams.length - 1;
    const writing = i > 0;
 
    if (isStream(stream)) {
      finishCount++;
      destroys.push(destroyer(stream, reading, writing, finish));
    }
 
    if (i === 0) {
      if (typeof stream === 'function') {
        ret = stream();
        if (!isIterable(ret)) {
          throw new ERR_INVALID_RETURN_VALUE(
            'Iterable, AsyncIterable or Stream', 'source', ret);
        }
      } else if (isIterable(stream) || isReadable(stream)) {
        ret = stream;
      } else {
        throw new ERR_INVALID_ARG_TYPE(
          'source', ['Stream', 'Iterable', 'AsyncIterable', 'Function'],
          stream);
      }
    } else if (typeof stream === 'function') {
      ret = makeAsyncIterable(ret);
      ret = stream(ret);
 
      if (reading) {
        if (!isIterable(ret, true)) {
          throw new ERR_INVALID_RETURN_VALUE(
            'AsyncIterable', `transform[${i - 1}]`, ret);
        }
      } else {
        if (!PassThrough) {
          PassThrough = require('internal/streams/passthrough');
        }
 
        // If the last argument to pipeline is not a stream
        // we must create a proxy stream so that pipeline(...)
        // always returns a stream which can be further
        // composed through `.pipe(stream)`.
 
        const pt = new PassThrough({
          objectMode: true
        });
 
        // Handle Promises/A+ spec, `then` could be a getter that throws on
        // second use.
        const then = ret?.then;
        if (typeof then === 'function') {
          then.call(ret,
                    (val) => {
                      value = val;
                      pt.end(val);
                    }, (err) => {
                      pt.destroy(err);
                    },
          );
        } else if (isIterable(ret, true)) {
          finishCount++;
          pump(ret, pt, finish);
        } else {
          throw new ERR_INVALID_RETURN_VALUE(
            'AsyncIterable or Promise', 'destination', ret);
        }
 
        ret = pt;
 
        finishCount++;
        destroys.push(destroyer(ret, false, true, finish));
      }
    } else if (isStream(stream)) {
      if (isReadable(ret)) {
        ret.pipe(stream);
 
        // Compat. Before node v10.12.0 stdio used to throw an error so
        // pipe() did/does not end() stdio destinations.
        // Now they allow it but "secretly" don't close the underlying fd.
        if (stream === process.stdout || stream === process.stderr) {
          ret.on('end', () => stream.end());
        }
      } else {
        ret = makeAsyncIterable(ret);
 
        finishCount++;
        pump(ret, stream, finish);
      }
      ret = stream;
    } else {
      const name = reading ? `transform[${i - 1}]` : 'destination';
      throw new ERR_INVALID_ARG_TYPE(
        name, ['Stream', 'Function'], stream);
    }
  }
 
  // TODO(ronag): Consider returning a Duplex proxy if the first argument
  // is a writable. Would improve composability.
  // See, https://github.com/nodejs/node/issues/32020
  return ret;
}
 
module.exports = pipeline;