1 // Ported from https://github.com/mafintosh/pump with
2 // permission from the author, Mathias Buus (@mafintosh).
7 function once(callback) {
12 callback.apply(void 0, arguments);
16 var _require$codes = require('../../../errors').codes,
17 ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS,
18 ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;
21 // Rethrow the error if it exists to avoid swallowing it
25 function isRequest(stream) {
26 return stream.setHeader && typeof stream.abort === 'function';
29 function destroyer(stream, reading, writing, callback) {
30 callback = once(callback);
32 stream.on('close', function () {
35 if (eos === undefined) eos = require('./end-of-stream');
40 if (err) return callback(err);
44 var destroyed = false;
45 return function (err) {
47 if (destroyed) return;
48 destroyed = true; // request.destroy just do .end - .abort is what we want
50 if (isRequest(stream)) return stream.abort();
51 if (typeof stream.destroy === 'function') return stream.destroy();
52 callback(err || new ERR_STREAM_DESTROYED('pipe'));
60 function pipe(from, to) {
64 function popCallback(streams) {
65 if (!streams.length) return noop;
66 if (typeof streams[streams.length - 1] !== 'function') return noop;
71 for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) {
72 streams[_key] = arguments[_key];
75 var callback = popCallback(streams);
76 if (Array.isArray(streams[0])) streams = streams[0];
78 if (streams.length < 2) {
79 throw new ERR_MISSING_ARGS('streams');
83 var destroys = streams.map(function (stream, i) {
84 var reading = i < streams.length - 1;
86 return destroyer(stream, reading, writing, function (err) {
87 if (!error) error = err;
88 if (err) destroys.forEach(call);
90 destroys.forEach(call);
94 return streams.reduce(pipe);
97 module.exports = pipeline;