"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createPromiseFromStreams = createPromiseFromStreams; var _stream = require("stream"); /* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ /** * Take an array of streams, pipe the output * from each one into the next, listening for * errors from any of the streams, and then resolve * the promise once the final stream has finished * writing/reading. * * If the last stream is readable, it's final value * will be provided as the promise value. * * Errors emitted from any stream will cause * the promise to be rejected with that error. * * @param {Array} streams * @return {Promise} */ function isReadable(stream) { return 'read' in stream && typeof stream.read === 'function'; } async function createPromiseFromStreams(streams) { let finalChunk; const last = streams[streams.length - 1]; if (!isReadable(last) && streams.length === 1) { // For a nicer error than what stream.pipeline throws throw new Error('A minimum of 2 streams is required when a non-readable stream is given'); } if (isReadable(last)) { // We are pushing a writable stream to capture the last chunk streams.push(new _stream.Writable({ // Use object mode even when "last" stream isn't. This allows to // capture the last chunk as-is. objectMode: true, write(chunk, enc, done) { finalChunk = chunk; done(); } })); } return new Promise((resolve, reject) => { // @ts-expect-error 'pipeline' doesn't support variable length of arguments (0, _stream.pipeline)(...streams, err => { if (err) return reject(err); resolve(finalChunk); }); }); }